From 62b5e607994edff9273b5180291a38707fa51852 Mon Sep 17 00:00:00 2001 From: Chrissy LeMaire Date: Sat, 9 Aug 2025 06:44:07 +0200 Subject: [PATCH 01/14] Refactor and expand Pester tests for Find/Export commands Refactored Pester test files for several Find-* and Export-DbaXESessionTemplate commands to use param blocks, improved parameter validation, and modernized test structure. Added BeforeAll/AfterAll setup and teardown, improved assertions, and enhanced test coverage and clarity for integration and unit tests. --- tests/Export-DbaXESessionTemplate.Tests.ps1 | 80 ++- tests/Find-DbaAgentJob.Tests.ps1 | 142 ++++-- tests/Find-DbaBackup.Tests.ps1 | 251 ++++++---- tests/Find-DbaCommand.Tests.ps1 | 69 ++- tests/Find-DbaDatabase.Tests.ps1 | 86 +++- tests/Find-DbaDbDisabledIndex.Tests.ps1 | 55 ++- tests/Find-DbaDbDuplicateIndex.Tests.ps1 | 74 ++- tests/Find-DbaDbGrowthEvent.Tests.ps1 | 88 ++-- tests/Find-DbaDbUnusedIndex.Tests.ps1 | 76 ++- tests/Find-DbaInstance.Tests.ps1 | 45 +- tests/Find-DbaLoginInGroup.Tests.ps1 | 34 +- tests/Find-DbaOrphanedFile.Tests.ps1 | 159 ++++-- tests/Find-DbaSimilarTable.Tests.ps1 | 70 ++- tests/Find-DbaStoredProcedure.Tests.ps1 | 142 +++++- tests/Find-DbaTrigger.Tests.ps1 | 90 ++-- tests/Find-DbaView.Tests.ps1 | 74 ++- tests/Format-DbaBackupInformation.Tests.ps1 | 263 ++++++---- tests/Get-DbaAgBackupHistory.Tests.ps1 | 48 +- tests/Get-DbaAgDatabase.Tests.ps1 | 105 ++-- tests/Get-DbaAgHadr.Tests.ps1 | 36 +- tests/Get-DbaAgListener.Tests.ps1 | 81 ++- tests/Get-DbaAgReplica.Tests.ps1 | 87 +++- tests/Get-DbaAgentAlert.Tests.ps1 | 66 ++- tests/Get-DbaAgentAlertCategory.Tests.ps1 | 51 +- tests/Get-DbaAgentJob.Tests.ps1 | 97 ++-- tests/Get-DbaAgentJobCategory.Tests.ps1 | 64 ++- tests/Get-DbaAgentJobHistory.Tests.ps1 | 514 +++++++++++--------- tests/Get-DbaAgentJobOutputFile.Tests.ps1 | 124 ++--- tests/Get-DbaAgentJobStep.Tests.ps1 | 56 ++- tests/Get-DbaAgentLog.Tests.ps1 | 59 ++- tests/Get-DbaAgentOperator.Tests.ps1 | 57 ++- tests/Get-DbaAgentProxy.Tests.ps1 | 143 ++++-- tests/Get-DbaAgentSchedule.Tests.ps1 | 232 +++++---- tests/Get-DbaAgentServer.Tests.ps1 | 36 +- tests/Get-DbaAvailabilityGroup.Tests.ps1 | 80 ++- tests/Get-DbaAvailableCollation.Tests.ps1 | 38 +- tests/Get-DbaBackupDevice.Tests.ps1 | 58 ++- tests/Get-DbaBackupInformation.Tests.ps1 | 178 +++++-- tests/Get-DbaBinaryFileTable.Tests.ps1 | 87 +++- 39 files changed, 2837 insertions(+), 1258 deletions(-) diff --git a/tests/Export-DbaXESessionTemplate.Tests.ps1 b/tests/Export-DbaXESessionTemplate.Tests.ps1 index 1dca24d55412..6aadaa787d72 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-DbaAgentJob.Tests.ps1 b/tests/Find-DbaAgentJob.Tests.ps1 index b28e4a089dd9..f60569038002 100644 --- a/tests/Find-DbaAgentJob.Tests.ps1 +++ b/tests/Find-DbaAgentJob.Tests.ps1 @@ -1,91 +1,127 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Find-DbaAgentJob", + $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', 'JobName', 'ExcludeJobName', 'StepName', 'LastUsed', 'IsDisabled', 'IsFailed', 'IsNotScheduled', 'IsNoEmailNotification', 'Category', 'Owner', 'Since', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +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", + "JobName", + "ExcludeJobName", + "StepName", + "LastUsed", + "IsDisabled", + "IsFailed", + "IsNotScheduled", + "IsNoEmailNotification", + "Category", + "Owner", + "Since", + "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 + + #subsystemServer needs the real underlying name, and it doesn't work if targeting something like localhost\namedinstance + # the typical error would be WARNING: [17:19:26][New-DbaAgentJobStep] Something went wrong creating the job step | The specified '@server' is + #invalid (valid values are returned by sp_helpserver). + $srvName = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Query "select @@servername as sn" -as PSObject + $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job "dbatoolsci_testjob" -OwnerLogin "sa" + $null = New-DbaAgentJobStep -SqlInstance $TestConfig.instance2 -Job "dbatoolsci_testjob" -StepId 1 -StepName "dbatoolsci Failed" -Subsystem TransactSql -SubsystemServer $srvName.sn -Command "RAISERROR (15600,-1,-1, 'dbatools_error');" -CmdExecSuccessCode 0 -OnSuccessAction QuitWithSuccess -OnFailAction QuitWithFailure -Database master -RetryAttempts 1 -RetryInterval 2 + $null = Start-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job "dbatoolsci_testjob" + $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job "dbatoolsregr_testjob" -OwnerLogin "sa" + $null = New-DbaAgentJobStep -SqlInstance $TestConfig.instance2 -Job "dbatoolsregr_testjob" -StepId 1 -StepName "dbatoolsci Failed" -Subsystem TransactSql -SubsystemServer $srvName.sn -Command "RAISERROR (15600,-1,-1, 'dbatools_error');" -CmdExecSuccessCode 0 -OnSuccessAction QuitWithSuccess -OnFailAction QuitWithFailure -Database master -RetryAttempts 1 -RetryInterval 2 + $null = New-DbaAgentJobCategory -SqlInstance $TestConfig.instance2 -Category "dbatoolsci_job_category" -CategoryType LocalJob + $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job "dbatoolsci_testjob_disabled" -Category "dbatoolsci_job_category" -Disabled + $null = New-DbaAgentJobStep -SqlInstance $TestConfig.instance2 -Job "dbatoolsci_testjob_disabled" -StepId 1 -StepName "dbatoolsci Test Step" -Subsystem TransactSql -SubsystemServer $srvName.sn -Command "SELECT * FROM master.sys.all_columns" -CmdExecSuccessCode 0 -OnSuccessAction QuitWithSuccess -OnFailAction QuitWithFailure -Database master -RetryAttempts 1 -RetryInterval 2 + + # 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 + + $null = Remove-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob, dbatoolsregr_testjob, dbatoolsci_testjob_disabled + $null = Remove-DbaAgentJobCategory -SqlInstance $TestConfig.instance2 -Category "dbatoolsci_job_category" + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. + } Context "Command finds jobs using all parameters" { - BeforeAll { - #subsystemServer needs the real underlying name, and it doesn't work if targeting something like localhost\namedinstance - # the typical error would be WARNING: [17:19:26][New-DbaAgentJobStep] Something went wrong creating the job step | The specified '@server' is - #invalid (valid values are returned by sp_helpserver). - $srvName = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Query "select @@servername as sn" -as PSObject - $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job 'dbatoolsci_testjob' -OwnerLogin 'sa' - $null = New-DbaAgentJobStep -SqlInstance $TestConfig.instance2 -Job 'dbatoolsci_testjob' -StepId 1 -StepName 'dbatoolsci Failed' -Subsystem TransactSql -SubsystemServer $srvName.sn -Command "RAISERROR (15600,-1,-1, 'dbatools_error');" -CmdExecSuccessCode 0 -OnSuccessAction QuitWithSuccess -OnFailAction QuitWithFailure -Database master -RetryAttempts 1 -RetryInterval 2 - $null = Start-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job 'dbatoolsci_testjob' - $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job 'dbatoolsregr_testjob' -OwnerLogin 'sa' - $null = New-DbaAgentJobStep -SqlInstance $TestConfig.instance2 -Job 'dbatoolsregr_testjob' -StepId 1 -StepName 'dbatoolsci Failed' -Subsystem TransactSql -SubsystemServer $srvName.sn -Command "RAISERROR (15600,-1,-1, 'dbatools_error');" -CmdExecSuccessCode 0 -OnSuccessAction QuitWithSuccess -OnFailAction QuitWithFailure -Database master -RetryAttempts 1 -RetryInterval 2 - $null = New-DbaAgentJobCategory -SqlInstance $TestConfig.instance2 -Category 'dbatoolsci_job_category' -CategoryType LocalJob - $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job 'dbatoolsci_testjob_disabled' -Category 'dbatoolsci_job_category' -Disabled - $null = New-DbaAgentJobStep -SqlInstance $TestConfig.instance2 -Job 'dbatoolsci_testjob_disabled' -StepId 1 -StepName 'dbatoolsci Test Step' -Subsystem TransactSql -SubsystemServer $srvName.sn -Command 'SELECT * FROM master.sys.all_columns' -CmdExecSuccessCode 0 -OnSuccessAction QuitWithSuccess -OnFailAction QuitWithFailure -Database master -RetryAttempts 1 -RetryInterval 2 - } - AfterAll { - $null = Remove-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob, dbatoolsregr_testjob, dbatoolsci_testjob_disabled -Confirm:$false - $null = Remove-DbaAgentJobCategory -SqlInstance $TestConfig.instance2 -Category 'dbatoolsci_job_category' -Confirm:$false - } - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob It "Should find a specific job" { - $results.name | Should Be "dbatoolsci_testjob" + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob + $results.name | Should -Be "dbatoolsci_testjob" } - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job *dbatoolsci* -ExcludeJobName dbatoolsci_testjob_disabled It "Should find a specific job but not an excluded job" { - $results.name | Should Not Be "dbatoolsci_testjob_disabled" + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job *dbatoolsci* -ExcludeJobName dbatoolsci_testjob_disabled + $results.name | Should -Not -Be "dbatoolsci_testjob_disabled" } - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -StepName 'dbatoolsci Test Step' It "Should find a specific job with a specific step" { - $results.name | Should Be "dbatoolsci_testjob_disabled" + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -StepName "dbatoolsci Test Step" + $results.name | Should -Be "dbatoolsci_testjob_disabled" } - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -LastUsed 10 It "Should find jobs not used in the last 10 days" { - $results | Should not be null + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -LastUsed 10 + $results | Should -Not -BeNullOrEmpty } - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsDisabled It "Should find jobs disabled from running" { - $results.name | Should be "dbatoolsci_testjob_disabled" + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsDisabled + $results.name | Should -Be "dbatoolsci_testjob_disabled" } - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsDisabled It "Should find 1 job disabled from running" { - $results.count | Should be 1 + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsDisabled + @($results).Count | Should -Be 1 } - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsNotScheduled It "Should find jobs that have not been scheduled" { - $results | Should not be null + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsNotScheduled + $results | Should -Not -BeNullOrEmpty } - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsNotScheduled -Job *dbatoolsci* It "Should find 2 jobs that have no schedule" { - $results.count | Should be 2 + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsNotScheduled -Job *dbatoolsci* + @($results).Count | Should -Be 2 } - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsNoEmailNotification It "Should find jobs that have no email notification" { - $results | Should not be null + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsNoEmailNotification + $results | Should -Not -BeNullOrEmpty } - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Category 'dbatoolsci_job_category' It "Should find jobs that have a category of dbatoolsci_job_category" { - $results.name | Should be "dbatoolsci_testjob_disabled" + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Category "dbatoolsci_job_category" + $results.name | Should -Be "dbatoolsci_testjob_disabled" } - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Owner 'sa' It "Should find jobs that are owned by sa" { - $results | Should not be null + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Owner "sa" + $results | Should -Not -BeNullOrEmpty } - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsFailed -Since '2016-07-01 10:47:00' It "Should find jobs that have been failed since July of 2016" { - $results | Should not be null + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsFailed -Since "2016-07-01 10:47:00" + $results | Should -Not -BeNullOrEmpty } - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job *dbatoolsci*,*dbatoolsregr* -ExcludeJobName dbatoolsci_testjob_disabled It "Should work with multiple wildcard passed in (see #9572)" { - $results.Count | Should -Be 2 + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job *dbatoolsci*,*dbatoolsregr* -ExcludeJobName dbatoolsci_testjob_disabled + @($results).Count | Should -Be 2 } } } diff --git a/tests/Find-DbaBackup.Tests.ps1 b/tests/Find-DbaBackup.Tests.ps1 index 2521874a9f51..4b8f8f4887d1 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 6ed8fb02dcab..aad70037dd17 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 43ee07bca44e..4074672f5d9d 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 056e32e02b8a..148739d4bd8b 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 65b58562c588..85f62c65841d 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 } } } diff --git a/tests/Find-DbaDbGrowthEvent.Tests.ps1 b/tests/Find-DbaDbGrowthEvent.Tests.ps1 index c888c252f9e5..38b44d00187c 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 a89748b594de..202df31e18c9 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. #> -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 869a8392f20c..8031fb81a175 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 a29fdef91f5b..a2a53bb13d34 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 +# \ No newline at end of file diff --git a/tests/Find-DbaOrphanedFile.Tests.ps1 b/tests/Find-DbaOrphanedFile.Tests.ps1 index 0f1fee7d7948..0545f9edffd0 100644 --- a/tests/Find-DbaOrphanedFile.Tests.ps1 +++ b/tests/Find-DbaOrphanedFile.Tests.ps1 @@ -1,52 +1,81 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Find-DbaOrphanedFile", + $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', '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 +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", + "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 { - $dbname = "dbatoolsci_orphanedfile_$(Get-Random)" + # 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 orphaned file detection, we need databases that can be detached to create orphaned files, + # and backup files to test recursive searching and file type filtering. + + # Set variables. They are available in all the It blocks. + $dbname = "dbatoolsci_orphanedfile_$(Get-Random)" + $dbname2 = "dbatoolsci_orphanedfile_$(Get-Random)" + $tmpdir = "c:\temp\orphan_$(Get-Random)" + $tmpdirInner = Join-Path $tmpdir "inner" + $tmpBackupPath = Join-Path $tmpdirInner "backup" + $tmpdir2 = "c:\temp\orphan_$(Get-Random)" + $tmpdirInner2 = Join-Path $tmpdir2 "inner" + $tmpBackupPath2 = Join-Path $tmpdirInner2 "backup" + + # Create the objects. $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 $db1 = New-DbaDatabase -SqlInstance $server -Name $dbname - - $dbname2 = "dbatoolsci_orphanedfile_$(Get-Random)" $db2 = New-DbaDatabase -SqlInstance $server -Name $dbname2 - $tmpdir = "c:\temp\orphan_$(Get-Random)" if (-not(Test-Path $tmpdir)) { - $null = New-Item -Path $tmpdir -type Container + $null = New-Item -Path $tmpdir -ItemType Container } - $tmpdirInner = Join-Path $tmpdir "inner" - $null = New-Item -Path $tmpdirInner -type Container - $tmpBackupPath = Join-Path $tmpdirInner "backup" - $null = New-Item -Path $tmpBackupPath -type Container + $null = New-Item -Path $tmpdirInner -ItemType Container + $null = New-Item -Path $tmpBackupPath -ItemType Container - $tmpdir2 = "c:\temp\orphan_$(Get-Random)" if (-not(Test-Path $tmpdir2)) { - $null = New-Item -Path $tmpdir2 -type Container + $null = New-Item -Path $tmpdir2 -ItemType Container } - $tmpdirInner2 = Join-Path $tmpdir2 "inner" - $null = New-Item -Path $tmpdirInner2 -type Container - $tmpBackupPath2 = Join-Path $tmpdirInner2 "backup" - $null = New-Item -Path $tmpBackupPath2 -type Container + $null = New-Item -Path $tmpdirInner2 -ItemType Container + $null = New-Item -Path $tmpBackupPath2 -ItemType Container $result = Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname - if ($result.count -eq 0) { - It "has failed setup" { - Set-TestInconclusive -message "Setup failed" - } - throw "has failed setup" + if ($result.Count -eq 0) { + throw "Setup failed - database $dbname was not created" } $backupFile = Backup-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname -Path $tmpBackupPath -Type Full @@ -54,61 +83,89 @@ 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 Container + + # 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 { - Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname, $dbname2 | 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 + + # Cleanup all created objects. + Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname, $dbname2 -ErrorAction SilentlyContinue | 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 + + # 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 "Has the correct properties" { $null = Detach-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname -Force - $results = Find-DbaOrphanedFile -SqlInstance $TestConfig.instance2 - $ExpectedStdProps = 'ComputerName,InstanceName,SqlInstance,Filename,RemoteFilename'.Split(',') + $results = @(Find-DbaOrphanedFile -SqlInstance $TestConfig.instance2) + $ExpectedStdProps = @( + "ComputerName", + "InstanceName", + "SqlInstance", + "Filename", + "RemoteFilename" + ) ($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" + ) ($results[0].PsObject.Properties.Name | Sort-Object) | Should -Be ($ExpectedProps | Sort-Object) } - It "Finds two files" { - $results = Find-DbaOrphanedFile -SqlInstance $TestConfig.instance2 - $results.Filename.Count | Should -Be 2 + $results = @(Find-DbaOrphanedFile -SqlInstance $TestConfig.instance2) + $results.Status.Count | Should -Be 2 } It "Finds zero files after cleaning up" { - $results = Find-DbaOrphanedFile -SqlInstance $TestConfig.instance2 + $results = @(Find-DbaOrphanedFile -SqlInstance $TestConfig.instance2) $results.FileName | Remove-Item - $results = Find-DbaOrphanedFile -SqlInstance $TestConfig.instance2 - $results.Filename.Count | Should -Be 0 + $results = @(Find-DbaOrphanedFile -SqlInstance $TestConfig.instance2) + $results.Status.Count | Should -Be 0 } + It "works with -Recurse" { "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 - $results = Find-DbaOrphanedFile -SqlInstance $TestConfig.instance2 -Path $tmpdir - $results.Filename.Count | Should -Be 0 - $results = Find-DbaOrphanedFile -SqlInstance $TestConfig.instance2 -Path $tmpdir -Recurse - $results.Filename.Count | Should -Be 1 + $results = @(Find-DbaOrphanedFile -SqlInstance $TestConfig.instance2 -Path $tmpdir) + $results.Status.Count | Should -Be 1 + Move-Item "$tmpdir\out.mdf" -Destination $tmpdirInner + $results = @(Find-DbaOrphanedFile -SqlInstance $TestConfig.instance2 -Path $tmpdir) + $results.Status.Count | Should -Be 0 + $results = @(Find-DbaOrphanedFile -SqlInstance $TestConfig.instance2 -Path $tmpdir -Recurse) + $results.Status.Count | Should -Be 1 Copy-Item -Path "$tmpdirInner\out.mdf" -Destination $tmpBackupPath3 -Confirm:$false - $results = Find-DbaOrphanedFile -SqlInstance $TestConfig.instance2 -Path $tmpdir, $tmpdir2 -Recurse -FileType bak + $results = @(Find-DbaOrphanedFile -SqlInstance $TestConfig.instance2 -Path $tmpdir, $tmpdir2 -Recurse -FileType bak) $results.Filename | Should -Contain $backupFile.BackupPath $results.Filename | Should -Contain $backupFile2.BackupPath $results.Filename | Should -Contain "$tmpdirInner\out.mdf" $results.Filename | Should -Contain "$tmpBackupPath3\out.mdf" $results.Count | Should -Be 4 - $results = Find-DbaOrphanedFile -SqlInstance $TestConfig.instance2 -Recurse + $results = @(Find-DbaOrphanedFile -SqlInstance $TestConfig.instance2 -Recurse) $results.Filename | Should -Be "$tmpBackupPath3\out.mdf" } + It "works with -Path" { - $results = Find-DbaOrphanedFile -SqlInstance $TestConfig.instance2 -Path "C:" -FileType bak + $results = @(Find-DbaOrphanedFile -SqlInstance $TestConfig.instance2 -Path "C:" -FileType bak) $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 50c226b368a1..ac300bb135e2 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") - } - $results = Find-DbaSimilarTable -SqlInstance $TestConfig.instance1 -Database tempdb | Where-Object Table -Match dbatoolsci + # As this is the last block we do not need to reset the $PSDefaultParameterValues. + } - It "returns at least two rows" { # not an exact count because who knows - $results.Count -ge 2 | Should Be $true + It "returns at least two rows" { + # not an exact count because who knows + $results = Find-DbaSimilarTable -SqlInstance $TestConfig.instance1 -Database tempdb | Where-Object Table -Match dbatoolsci + + $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 f3d429a00b0b..8cde9990229d 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 724046f1e214..aae1ed3d9676 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 e9cb17fe49b0..3294ca141e27 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 824d703e99bb..69b19d3056f6 100644 --- a/tests/Format-DbaBackupInformation.Tests.ps1 +++ b/tests/Format-DbaBackupInformation.Tests.ps1 @@ -1,179 +1,274 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Format-DbaBackupInformation", + $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 = '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 +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 += @( + "BackupHistory", + "ReplaceDatabaseName", + "ReplaceDbNameInFile", + "DataFileDirectory", + "LogFileDirectory", + "DestinationFileStreamDirectory", + "DatabaseNamePrefix", + "DatabaseFilePrefix", + "DatabaseFileSuffix", + "RebaseBackupFolder", + "Continue", + "FileMapping", + "PathSep", + "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 "Rename a Database" { - $History = Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\ContinuePointTest.xml - $output = $history | Format-DbaBackupInformation -ReplaceDatabaseName 'Pester' + BeforeAll { + $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 { $PSItem.Database -ne "Pester" }).Count | Should -BeExactly 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 { $PSItem.PhysicalName -like "*ContinuePointTest*" }).Count | Should -BeExactly 0 } - } Context "Test it works as a parameter as well" { - $History = Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\ContinuePointTest.xml - $output = Format-DbaBackupInformation -BackupHistory $History -ReplaceDatabaseName 'Pester' + BeforeAll { + $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 { $PSItem.Database -ne "Pester" }).Count | Should -BeExactly 0 } + It "Should have renamed datafiles as well" { - ($out | Select-Object -ExpandProperty filelist | Where-Object {$_.PhysicalName -like 'ContinuePointTest'}).count | Should Be 0 + ($output | Select-Object -ExpandProperty filelist | Where-Object { $PSItem.PhysicalName -like "*ContinuePointTest*" }).Count | Should -BeExactly 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'} + BeforeAll { + $History = Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\ContinuePointTest.xml + $History += Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\RestoreTimeClean.xml + $splatFormat = @{ + BackupHistory = $History + ReplaceDatabaseName = @{"ContinuePointTest" = "Spiggy"; "RestoreTimeClean" = "Eldritch"} + } + $output = Format-DbaBackupInformation @splatFormat + } + It "Should have no databases other than spiggy and eldritch" { - ($output | Where-Object {$_.Database -notin ('Spiggy', 'Eldritch')}).count | Should be 0 + ($output | Where-Object { $PSItem.Database -notin ("Spiggy", "Eldritch") }).Count | Should -BeExactly 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 { $PSItem.OriginalDatabase -eq "RestoreTimeClean" } | Where-Object { $PSItem.Database -ne "Eldritch" }).Count | Should -BeExactly 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 + It "Should have renamed all the RestoreTimeClean files to Eldritch" { + ($output | Where-Object { $PSItem.OriginalDatabase -eq "RestoreTimeClean" } | Select-Object -ExpandProperty filelist | Where-Object { $PSItem.PhysicalName -like "*RestoreTimeClean*" }).Count | Should -BeExactly 0 + ($output | Where-Object { $PSItem.OriginalDatabase -eq "RestoreTimeClean" } | Select-Object -ExpandProperty filelist | Where-Object { $PSItem.PhysicalName -like "*eldritch*" }).Count | Should -BeExactly ($output | Where-Object { $PSItem.OriginalDatabase -eq "RestoreTimeClean" } | 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 { $PSItem.OriginalDatabase -eq "ContinuePointTest" } | Where-Object { $PSItem.Database -ne "Spiggy" }).Count | Should -BeExactly 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 + It "Should have renamed all the ContinuePointTest files to Spiggy" { + ($output | Where-Object { $PSItem.OriginalDatabase -eq "ContinuePointTest" } | Select-Object -ExpandProperty filelist | Where-Object { $PSItem.PhysicalName -like "*ContinuePointTest*" }).Count | Should -BeExactly 0 + ($output | Where-Object { $PSItem.OriginalDatabase -eq "ContinuePointTest" } | Select-Object -ExpandProperty filelist | Where-Object { $PSItem.PhysicalName -like "*spiggy*" }).Count | Should -BeExactly ($output | Where-Object { $PSItem.OriginalDatabase -eq "ContinuePointTest" } | Select-Object -ExpandProperty filelist).Count } } 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'} - It "Should have no databases other than spiggy and eldritch" { - ($output | Where-Object {$_.Database -notin ('RestoreTimeClean', 'Alice')}).count | Should be 0 + BeforeAll { + $History = Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\ContinuePointTest.xml + $History += Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\RestoreTimeClean.xml + $splatRename = @{ + BackupHistory = $History + ReplaceDatabaseName = @{"ContinuePointTest" = "Alice"} + } + $output = Format-DbaBackupInformation @splatRename } + + It "Should have no databases other than RestoreTimeClean and Alice" { + ($output | Where-Object { $PSItem.Database -notin ("RestoreTimeClean", "Alice") }).Count | Should -BeExactly 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 { $PSItem.OriginalDatabase -eq "RestoreTimeClean" } | Where-Object { $PSItem.Database -ne "RestoreTimeClean" }).Count | Should -BeExactly 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 { $PSItem.OriginalDatabase -eq "ContinuePointTest" } | Where-Object { $PSItem.Database -ne "Alice" }).Count | Should -BeExactly 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 { $PSItem.OriginalDatabase -eq "ContinuePointTest" } | Select-Object -ExpandProperty filelist | Where-Object { $PSItem.PhysicalName -like "*ContinuePointTest*" }).Count | Should -BeExactly 0 + ($output | Where-Object { $PSItem.OriginalDatabase -eq "ContinuePointTest" } | Select-Object -ExpandProperty filelist | Where-Object { $PSItem.PhysicalName -like "*alice*" }).Count | Should -BeExactly ($output | Where-Object { $PSItem.OriginalDatabase -eq "ContinuePointTest" } | Select-Object -ExpandProperty filelist).Count } } Context "Check DB Name prefix and suffix" { - $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 + BeforeAll { + $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 { $PSItem.Database -like "PREFIX*" }).Count | Should -BeExactly $output.Count + } } Context "Check DataFileDirectory moves all files" { - $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 -DataFileDirectory c:\restores + BeforeAll { + $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 -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 { $PSItem -ne "c:\restores" }).Count | Should -BeExactly 0 } } Context "Check DataFileDirectory and LogFileDirectory work independently" { - $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 -DataFileDirectory c:\restores\ -LogFileDirectory c:\logs + BeforeAll { + $History = Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\ContinuePointTest.xml + $History += Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\RestoreTimeClean.xml + $splatDirectories = @{ + BackupHistory = $History + DataFileDirectory = "c:\restores\" + LogFileDirectory = "c:\logs" + } + $output = Format-DbaBackupInformation @splatDirectories + } 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 { $PSItem.Type -eq "D" }).PhysicalName | Split-Path | Where-Object { $PSItem -ne "c:\restores" }).Count | Should -BeExactly 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 { $PSItem.Type -eq "L" }).PhysicalName | Split-Path | Where-Object { $PSItem -ne "c:\logs" }).Count | Should -BeExactly 0 } } Context "Check LogFileDirectory works for just logfiles" { - $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 -DataFileDirectory c:\restores\ -LogFileDirectory c:\logs + BeforeAll { + $History = Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\ContinuePointTest.xml + $History += Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\RestoreTimeClean.xml + $splatLogFiles = @{ + BackupHistory = $History + DataFileDirectory = "c:\restores\" + LogFileDirectory = "c:\logs" + } + $output = Format-DbaBackupInformation @splatLogFiles + } - 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 + It "Should not have moved all data files to c:\logs\" { + (($output | Select-Object -ExpandProperty Filelist | Where-Object { $PSItem.Type -eq "D" }).PhysicalName | Split-Path | Where-Object { $PSItem -eq "c:\logs" }).Count | Should -BeExactly 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 { $PSItem.Type -eq "L" }).PhysicalName | Split-Path | Where-Object { $PSItem -ne "c:\logs" }).Count | Should -BeExactly 0 } } Context "Test RebaseBackupFolder" { - $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 -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 + BeforeAll { + $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 -RebaseBackupFolder c:\backups\ } + It "Should have moved all backup files to c:\backups" { + ($output | Select-Object -ExpandProperty FullName | Split-Path | Where-Object { $PSItem -eq "c:\backups" }).Count | Should -BeExactly $History.Count + } } Context "Test PathSep" { - $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 -RebaseBackupFolder 'c:\backups' + BeforeAll { + $History = Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\ContinuePointTest.xml + $History += Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\RestoreTimeClean.xml + $outputDefault = Format-DbaBackupInformation -BackupHistory $History -RebaseBackupFolder "c:\backups" + $outputExplicit = Format-DbaBackupInformation -BackupHistory $History -RebaseBackupFolder "c:\backups" -PathSep "\" + $splatLinux = @{ + BackupHistory = $History + RebaseBackupFolder = "/opt/mssql/backups" + PathSep = "/" + } + $outputLinux = Format-DbaBackupInformation @splatLinux + } + 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 + ($outputDefault | Select-Object -ExpandProperty FullName | Split-Path | Where-Object { $PSItem -eq "c:\backups" }).Count | Should -BeExactly $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 + + It "Should not have changed the default path separator even when passed explicitly" { + ($outputExplicit | Select-Object -ExpandProperty FullName | Split-Path | Where-Object { $PSItem -eq "c:\backups" }).Count | Should -BeExactly $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 = $outputLinux | Select-Object -ExpandProperty FullName | ForEach-Object { + $all = $PSItem.Split("/") + $all[0..($all.Length - 2)] -Join "/" + } + ($result | Where-Object { $PSItem -eq "/opt/mssql/backups" }).Count | Should -BeExactly $History.Count } } Context "Test everything all at once" { - $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\ + BeforeAll { + $History = Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\ContinuePointTest.xml + $splatEverything = @{ + ReplaceDatabaseName = "Pester" + DataFileDirectory = "c:\restores" + LogFileDirectory = "c:\logs\" + RebaseBackupFolder = "c:\backups\" + } + $output = $History | Format-DbaBackupInformation @splatEverything + } + It "Should have a database name of Pester" { - ($output | Where-Object {$_.Database -ne 'Pester'}).count | Should be 0 + ($output | Where-Object { $PSItem.Database -ne "Pester" }).Count | Should -BeExactly 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 { $PSItem.PhysicalName -like "*ContinuePointTest*" }).Count | Should -BeExactly 0 } + 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 { $PSItem.Type -eq "D" }).PhysicalName | Split-Path | Where-Object { $PSItem -ne "c:\restores" }).Count | Should -BeExactly 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 - } - 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 Filelist | Where-Object { $PSItem.Type -eq "L" }).PhysicalName | Split-Path | Where-Object { $PSItem -ne "c:\logs" }).Count | Should -BeExactly 0 } + It "Should have moved all backup files to c:\backups" { + ($output | Select-Object -ExpandProperty FullName | Split-Path | Where-Object { $PSItem -eq "c:\backups" }).Count | Should -BeExactly $History.Count + } } } \ No newline at end of file diff --git a/tests/Get-DbaAgBackupHistory.Tests.ps1 b/tests/Get-DbaAgBackupHistory.Tests.ps1 index 7ecc2b608b31..e8ac02d98d26 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 3ab863dc389d..361a9c8c2e94 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 diff --git a/tests/Get-DbaAgHadr.Tests.ps1 b/tests/Get-DbaAgHadr.Tests.ps1 index ecd586d65274..a24fe5ad23d5 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 0a4e3670e888..ff5b91a31290 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 6d1992f66059..266330cef655 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 2f092795586a..e372feba80b6 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 ad6425b1827f..178c62942d4b 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 d5c41b23cc61..c5d6fcbdfe33 100644 --- a/tests/Get-DbaAgentJob.Tests.ps1 +++ b/tests/Get-DbaAgentJob.Tests.ps1 @@ -1,81 +1,114 @@ -$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", + "ExcludeCategory", + "ExcludeDisabledJobs", + "IncludeExecution", + "Type", + "EnableException" + ) + } - 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 $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob_disabled -Disabled } + AfterAll { $null = Remove-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob, dbatoolsci_testjob_disabled -Confirm:$false } - $results = Get-DbaAgentJob -SqlInstance $TestConfig.instance2 | Where-Object { $_.Name -match "dbatoolsci_testjob" } + It "Should get 2 dbatoolsci jobs" { - $results.count | Should Be 2 + $results = Get-DbaAgentJob -SqlInstance $TestConfig.instance2 | 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 { $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob_disabled -Disabled } + AfterAll { $null = Remove-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob, dbatoolsci_testjob_disabled -Confirm:$false } - $results = Get-DbaAgentJob -SqlInstance $TestConfig.instance2 -ExcludeDisabledJobs | Where-Object { $_.Name -match "dbatoolsci_testjob" } + It "Should return only enabled jobs" { - $results.enabled -contains $False | Should Be $False + $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" { BeforeAll { $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob_disabled -Disabled } + AfterAll { $null = Remove-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob, dbatoolsci_testjob_disabled -Confirm:$false } - $results = Get-DbaAgentJob -SqlInstance $TestConfig.instance2 -ExcludeJob dbatoolsci_testjob | Where-Object { $_.Name -match "dbatoolsci_testjob" } + It "Should not return excluded job" { - $results.name -contains "dbatoolsci_testjob" | Should Be $False + $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" { BeforeAll { $jobName1 = "dbatoolsci_dbfilter_$(Get-Random)" @@ -90,23 +123,29 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { $null = New-DbaAgentJobStep -SqlInstance $TestConfig.instance2 -Job $jobName2 -StepName "TSQL-y" -Subsystem TransactSql -Database "model" $null = New-DbaAgentJobStep -SqlInstance $TestConfig.instance2 -Job $jobName2 -StepName "TSQL-z" -Subsystem TransactSql -Database "master" } + AfterAll { $null = Remove-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job $jobName1, $jobName2 -Confirm:$false } - $resultSingleDatabase = Get-DbaAgentJob -SqlInstance $TestConfig.instance2 -Database tempdb + It "Returns result with single database" { + $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 3344a55e11a1..cb7a3ad32249 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-DbaAgentJobHistory.Tests.ps1 b/tests/Get-DbaAgentJobHistory.Tests.ps1 index 862a38dc0ff6..612c5669b25a 100644 --- a/tests/Get-DbaAgentJobHistory.Tests.ps1 +++ b/tests/Get-DbaAgentJobHistory.Tests.ps1 @@ -1,398 +1,472 @@ -$commandname = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaAgentJobHistory", + $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', 'StartDate', 'EndDate', 'OutcomeType', 'ExcludeJobSteps', 'WithOutputFile', 'JobCollection', '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", + "StartDate", + "EndDate", + "OutcomeType", + "ExcludeJobSteps", + "WithOutputFile", + "JobCollection", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$CommandName Unittests" -Tag 'UnitTests' { - InModuleScope 'dbatools' { - Mock Connect-DbaInstance -MockWith { - # Thanks @Fred - $obj = [PSCustomObject]@{ - Name = 'BASEName' - ComputerName = 'BASEComputerName' - InstanceName = 'BASEInstanceName' - DomainInstanceName = 'BASEDomainInstanceName' - InstallDataDirectory = 'BASEInstallDataDirectory' - ErrorLogPath = 'BASEErrorLog_{0}_{1}_{2}_Path' -f "'", '"', ']' - ServiceName = 'BASEServiceName' - JobServer = New-Object PSObject - ConnectionContext = New-Object PSObject - } - Add-Member -InputObject $obj.ConnectionContext -Name ConnectionString -MemberType NoteProperty -Value 'put=an=equal=in=it' - Add-Member -InputObject $obj.JobServer -Name EnumJobHistory -MemberType ScriptMethod -Value { - param ($filter) - return @( - @{ - JobName = 'Job1' - JobID = [guid]'E7718A84-8B43-46D0-8F8D-4FC4464F9FC5' - StepID = 0 - StepName = '(Job outcome)' - RunDate = [DateTime]::Parse('2017-09-26T13:00:00') - RunDuration = 112 - RunStatus = 0 - }, - @{ - JobName = 'Job1' - JobID = [guid]'E7718A84-8B43-46D0-8F8D-4FC4464F9FC5' - StepID = 1 - StepName = 'Job1Step1' - RunDate = [DateTime]::Parse('2017-09-26T13:00:00') - RunDuration = 1 - RunStatus = 0 - }, - @{ - JobName = 'Job1' - JobID = [guid]'E7718A84-8B43-46D0-8F8D-4FC4464F9FC5' - StepID = 2 - StepName = 'Job1Step2' - RunDate = [DateTime]::Parse('2017-09-26T13:00:01') - RunDuration = 1 - RunStatus = 0 - }, - @{ - JobName = 'Job2' - JobID = [guid]'9C9A6819-58CE-451A-8DD7-6D17593F0DFA' - StepID = 0 - StepName = '(Job outcome)' - RunDate = [DateTime]::Parse('2017-09-26T01:00:00') - RunDuration = 2 - RunStatus = 0 - }, - @{ - JobName = 'Job2' - JobID = [guid]'9C9A6819-58CE-451A-8DD7-6D17593F0DFA' - StepID = 1 - StepName = 'Job2Step1' - RunDate = [DateTime]::Parse('2017-09-26T01:00:00') - RunDuration = 1 - RunStatus = 0 - }, - @{ - JobName = 'Job2' - JobID = [guid]'9C9A6819-58CE-451A-8DD7-6D17593F0DFA' - StepID = 2 - StepName = 'Job2Step2' - RunDate = [DateTime]::Parse('2017-09-26T01:00:01') - RunDuration = 1 - RunStatus = 0 - } - ) - } - $obj.PSObject.TypeNames.Clear() - $obj.PSObject.TypeNames.Add("Microsoft.SqlServer.Management.Smo.Server") - return $obj - } #mock Connect-DbaInstance - Context "Return values" { - - Mock Get-DbaAgentJobOutputFile -MockWith { - @( - @{ - Job = 'Job1' - StepId = 1 - OutputFileName = 'Job1Output1' - }, - @{ - Job = 'Job1' - StepId = 2 - OutputFileName = 'Job1Output2' - }, - @{ - Job = 'Job2' - StepId = 2 - OutputFileName = 'Job2Output1' - } - ) +Describe "$CommandName Unittests" -Tag UnitTests { + BeforeAll { + InModuleScope "dbatools" { + Mock Connect-DbaInstance -MockWith { + # Thanks @Fred + $obj = [PSCustomObject]@{ + Name = "BASEName" + ComputerName = "BASEComputerName" + InstanceName = "BASEInstanceName" + DomainInstanceName = "BASEDomainInstanceName" + InstallDataDirectory = "BASEInstallDataDirectory" + ErrorLogPath = "BASEErrorLog_{0}_{1}_{2}_Path" -f "'", '"', ']' + ServiceName = "BASEServiceName" + JobServer = New-Object PSObject + ConnectionContext = New-Object PSObject + } + Add-Member -InputObject $obj.ConnectionContext -Name ConnectionString -MemberType NoteProperty -Value "put=an=equal=in=it" + Add-Member -InputObject $obj.JobServer -Name EnumJobHistory -MemberType ScriptMethod -Value { + param ($filter) + return @( + @{ + JobName = "Job1" + JobID = [guid]"E7718A84-8B43-46D0-8F8D-4FC4464F9FC5" + StepID = 0 + StepName = "(Job outcome)" + RunDate = [DateTime]::Parse("2017-09-26T13:00:00") + RunDuration = 112 + RunStatus = 0 + }, + @{ + JobName = "Job1" + JobID = [guid]"E7718A84-8B43-46D0-8F8D-4FC4464F9FC5" + StepID = 1 + StepName = "Job1Step1" + RunDate = [DateTime]::Parse("2017-09-26T13:00:00") + RunDuration = 1 + RunStatus = 0 + }, + @{ + JobName = "Job1" + JobID = [guid]"E7718A84-8B43-46D0-8F8D-4FC4464F9FC5" + StepID = 2 + StepName = "Job1Step2" + RunDate = [DateTime]::Parse("2017-09-26T13:00:01") + RunDuration = 1 + RunStatus = 0 + }, + @{ + JobName = "Job2" + JobID = [guid]"9C9A6819-58CE-451A-8DD7-6D17593F0DFA" + StepID = 0 + StepName = "(Job outcome)" + RunDate = [DateTime]::Parse("2017-09-26T01:00:00") + RunDuration = 2 + RunStatus = 0 + }, + @{ + JobName = "Job2" + JobID = [guid]"9C9A6819-58CE-451A-8DD7-6D17593F0DFA" + StepID = 1 + StepName = "Job2Step1" + RunDate = [DateTime]::Parse("2017-09-26T01:00:00") + RunDuration = 1 + RunStatus = 0 + }, + @{ + JobName = "Job2" + JobID = [guid]"9C9A6819-58CE-451A-8DD7-6D17593F0DFA" + StepID = 2 + StepName = "Job2Step2" + RunDate = [DateTime]::Parse("2017-09-26T01:00:01") + RunDuration = 1 + RunStatus = 0 + } + ) + } + $obj.PSObject.TypeNames.Clear() + $obj.PSObject.TypeNames.Add("Microsoft.SqlServer.Management.Smo.Server") + return $obj + } #mock Connect-DbaInstance + } + } + + Context "Return values" { + BeforeAll { + InModuleScope "dbatools" { + Mock Get-DbaAgentJobOutputFile -MockWith { + @( + @{ + Job = "Job1" + StepId = 1 + OutputFileName = "Job1Output1" + }, + @{ + Job = "Job1" + StepId = 2 + OutputFileName = "Job1Output2" + }, + @{ + Job = "Job2" + StepId = 2 + OutputFileName = "Job2Output1" + } + ) + } } - It "Throws when ExcludeJobSteps and WithOutputFile" { - { Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -ExcludeJobSteps -WithOutputFile -EnableException } | Should Throw + } + + It "Throws when ExcludeJobSteps and WithOutputFile" { + InModuleScope "dbatools" { + { Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -ExcludeJobSteps -WithOutputFile -EnableException } | Should -Throw } - It "Returns full history by default" { + } + + It "Returns full history by default" { + InModuleScope "dbatools" { $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' - $Results.Length | Should Be 6 + $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" + $Results.Count | Should -BeExactly 6 } - It "Returns only runs with no steps with ExcludeJobSteps" { + } + + It "Returns only runs with no steps with ExcludeJobSteps" { + InModuleScope "dbatools" { $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -ExcludeJobSteps - $Results.Length | Should Be 2 + $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -ExcludeJobSteps + $Results.Count | Should -BeExactly 2 } - It 'Returns our own "augmented" properties, too' { + } + + It "Returns our own 'augmented' properties, too" { + InModuleScope "dbatools" { $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -ExcludeJobSteps - $Results[0].psobject.properties.Name | Should -Contain 'StartDate' - $Results[0].psobject.properties.Name | Should -Contain 'EndDate' - $Results[0].psobject.properties.Name | Should -Contain 'Duration' + $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -ExcludeJobSteps + $Results[0].psobject.properties.Name | Should -Contain "StartDate" + $Results[0].psobject.properties.Name | Should -Contain "EndDate" + $Results[0].psobject.properties.Name | Should -Contain "Duration" } - It 'Returns "augmented" properties that are correct' { + } + + It "Returns 'augmented' properties that are correct" { + InModuleScope "dbatools" { $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -ExcludeJobSteps + $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -ExcludeJobSteps $Results[0].StartDate | Should -Be $Results[0].RunDate - $Results[0].RunDuration | Should -Be 112 - $Results[0].Duration.TotalSeconds | Should -Be 72 + $Results[0].RunDuration | Should -BeExactly 112 + $Results[0].Duration.TotalSeconds | Should -BeExactly 72 $Results[0].EndDate | Should -Be ($Results[0].StartDate.AddSeconds($Results[0].Duration.TotalSeconds)) } - It "Figures out plain outputfiles" { + } + + It "Figures out plain outputfiles" { + InModuleScope "dbatools" { $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -WithOutputFile + $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile # no output for outcomes - ($Results | Where-Object StepID -eq 0).Length | Should Be 2 - ($Results | Where-Object StepID -eq 0).OutputFileName -Join '' | Should Be '' + ($Results | Where-Object StepID -eq 0).Count | Should -BeExactly 2 + ($Results | Where-Object StepID -eq 0).OutputFileName -Join "" | Should -Be "" # correct output for job1 - ($Results | Where-Object StepID -ne 0 | Where-Object JobName -eq 'Job1').OutputFileName | Should Match 'Job1Output[12]' + ($Results | Where-Object StepID -ne 0 | Where-Object JobName -eq "Job1").OutputFileName | Should -Match "Job1Output[12]" # correct output for job2 - ($Results | Where-Object StepID -eq 2 | Where-Object JobName -eq 'Job2').OutputFileName | Should Match 'Job2Output1' - ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq 'Job2').OutputFileName | Should Be '' + ($Results | Where-Object StepID -eq 2 | Where-Object JobName -eq "Job2").OutputFileName | Should -Match "Job2Output1" + ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job2").OutputFileName | Should -Be "" } } - Context "SQL Agent Tokens" { - It "Handles INST" { + } + + Context "SQL Agent Tokens" { + It "Handles INST" { + InModuleScope "dbatools" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ - Job = 'Job1' + Job = "Job1" StepId = 1 - OutputFileName = '$(INST)__Job1Output1' + OutputFileName = "$(INST)__Job1Output1" } ) } $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -WithOutputFile - - ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq 'Job1').OutputFileName | Should Be 'BASEServiceName__Job1Output1' + $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile + ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "BASEServiceName__Job1Output1" } - It "Handles MACH" { + } + + It "Handles MACH" { + InModuleScope "dbatools" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ - Job = 'Job1' + Job = "Job1" StepId = 1 - OutputFileName = '$(MACH)__Job1Output1' + OutputFileName = "$(MACH)__Job1Output1" } ) } $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -WithOutputFile - - ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq 'Job1').OutputFileName | Should Be 'BASEComputerName__Job1Output1' + $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile + ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "BASEComputerName__Job1Output1" } - It "Handles SQLDIR" { + } + + It "Handles SQLDIR" { + InModuleScope "dbatools" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ - Job = 'Job1' + Job = "Job1" StepId = 1 - OutputFileName = '$(SQLDIR)__Job1Output1' + OutputFileName = "$(SQLDIR)__Job1Output1" } ) } $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -WithOutputFile - - ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq 'Job1').OutputFileName | Should Be 'BASEInstallDataDirectory__Job1Output1' + $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile + ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "BASEInstallDataDirectory__Job1Output1" } - It "Handles SQLLOGDIR" { + } + + It "Handles SQLLOGDIR" { + InModuleScope "dbatools" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ - Job = 'Job1' + Job = "Job1" StepId = 1 - OutputFileName = '$(SQLLOGDIR)__Job1Output1' + OutputFileName = "$(SQLLOGDIR)__Job1Output1" } ) } $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -WithOutputFile - - ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq 'Job1').OutputFileName | Should Be 'BASEErrorLog_''_"_]_Path__Job1Output1' + $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile + ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "BASEErrorLog_'_""_]_Path__Job1Output1" } - It "Handles SRVR" { + } + + It "Handles SRVR" { + InModuleScope "dbatools" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ - Job = 'Job1' + Job = "Job1" StepId = 1 - OutputFileName = '$(SRVR)__Job1Output1' + OutputFileName = "$(SRVR)__Job1Output1" } ) } $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -WithOutputFile - - ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq 'Job1').OutputFileName | Should Be 'BASEDomainInstanceName__Job1Output1' + $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile + ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "BASEDomainInstanceName__Job1Output1" } + } - It "Handles STEPID" { + It "Handles STEPID" { + InModuleScope "dbatools" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ - Job = 'Job1' + Job = "Job1" StepId = 1 - OutputFileName = '$(STEPID)__Job1Output1' + OutputFileName = "$(STEPID)__Job1Output1" } ) } $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -WithOutputFile - ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq 'Job1').OutputFileName | Should Be '1__Job1Output1' - + $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile + ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "1__Job1Output1" } - It "Handles JOBID" { + } + + It "Handles JOBID" { + InModuleScope "dbatools" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ - Job = 'Job1' + Job = "Job1" StepId = 1 - OutputFileName = '$(JOBID)__Job1Output1' + OutputFileName = "$(JOBID)__Job1Output1" } ) } $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -WithOutputFile - - ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq 'Job1').OutputFileName | Should Be '0x848A71E7438BD0468F8D4FC4464F9FC5__Job1Output1' + $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile + ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "0x848A71E7438BD0468F8D4FC4464F9FC5__Job1Output1" } + } - - It "Handles STRTDT" { + It "Handles STRTDT" { + InModuleScope "dbatools" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ - Job = 'Job1' + Job = "Job1" StepId = 1 - OutputFileName = '$(STRTDT)__Job1Output1' + OutputFileName = "$(STRTDT)__Job1Output1" } ) } $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -WithOutputFile - ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq 'Job1').OutputFileName | Should Be '20170926__Job1Output1' + $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile + ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "20170926__Job1Output1" } - It "Handles STRTTM" { + } + + It "Handles STRTTM" { + InModuleScope "dbatools" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ - Job = 'Job1' + Job = "Job1" StepId = 1 - OutputFileName = '$(STRTTM)__Job1Output1' + OutputFileName = "$(STRTTM)__Job1Output1" } ) } $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -WithOutputFile - ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq 'Job1').OutputFileName | Should Be '130000__Job1Output1' + $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile + ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "130000__Job1Output1" } - It "Handles DATE" { + } + + It "Handles DATE" { + InModuleScope "dbatools" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ - Job = 'Job1' + Job = "Job1" StepId = 1 - OutputFileName = '$(DATE)__Job1Output1' + OutputFileName = "$(DATE)__Job1Output1" } ) } $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -WithOutputFile - ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq 'Job1').OutputFileName | Should Be '20170926__Job1Output1' + $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile + ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "20170926__Job1Output1" } + } - It "Handles TIME" { + It "Handles TIME" { + InModuleScope "dbatools" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ - Job = 'Job1' + Job = "Job1" StepId = 2 - OutputFileName = '$(TIME)__Job1Output1' + OutputFileName = "$(TIME)__Job1Output1" } ) } $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -WithOutputFile - ($Results | Where-Object StepID -eq 2 | Where-Object JobName -eq 'Job1').OutputFileName | Should Be '130001__Job1Output1' - + $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile + ($Results | Where-Object StepID -eq 2 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "130001__Job1Output1" } } - Context "SQL Agent escape sequences" { - It "Handles ESCAPE_NONE" { + } + + Context "SQL Agent escape sequences" { + It "Handles ESCAPE_NONE" { + InModuleScope "dbatools" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ - Job = 'Job1' + Job = "Job1" StepId = 1 - OutputFileName = '$(ESCAPE_NONE(SQLLOGDIR))__Job1Output1' + OutputFileName = "$(ESCAPE_NONE(SQLLOGDIR))__Job1Output1" } ) } $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -WithOutputFile - - ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq 'Job1').OutputFileName | Should Be 'BASEErrorLog_''_"_]_Path__Job1Output1' + $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile + ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "BASEErrorLog_'_""_]_Path__Job1Output1" } - It "Handles ESCAPE_SQUOTE" { + } + + It "Handles ESCAPE_SQUOTE" { + InModuleScope "dbatools" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ - Job = 'Job1' + Job = "Job1" StepId = 1 - OutputFileName = '$(ESCAPE_SQUOTE(SQLLOGDIR))__Job1Output1' + OutputFileName = "$(ESCAPE_SQUOTE(SQLLOGDIR))__Job1Output1" } ) } $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -WithOutputFile - - ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq 'Job1').OutputFileName | Should Be 'BASEErrorLog_''''_"_]_Path__Job1Output1' + $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile + ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "BASEErrorLog_''''_""_]_Path__Job1Output1" } - It "Handles ESCAPE_DQUOTE" { + } + + It "Handles ESCAPE_DQUOTE" { + InModuleScope "dbatools" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ - Job = 'Job1' + Job = "Job1" StepId = 1 - OutputFileName = '$(ESCAPE_DQUOTE(SQLLOGDIR))__Job1Output1' + OutputFileName = "$(ESCAPE_DQUOTE(SQLLOGDIR))__Job1Output1" } ) } $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -WithOutputFile - - ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq 'Job1').OutputFileName | Should Be 'BASEErrorLog_''_""_]_Path__Job1Output1' + $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile + ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "BASEErrorLog_'_""""_]_Path__Job1Output1" } - It "Handles ESCAPE_RBRACKET" { + } + + It "Handles ESCAPE_RBRACKET" { + InModuleScope "dbatools" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ - Job = 'Job1' + Job = "Job1" StepId = 1 - OutputFileName = '$(ESCAPE_RBRACKET(SQLLOGDIR))__Job1Output1' + OutputFileName = "$(ESCAPE_RBRACKET(SQLLOGDIR))__Job1Output1" } ) } $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -WithOutputFile - - ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq 'Job1').OutputFileName | Should Be 'BASEErrorLog_''_"_]]_Path__Job1Output1' + $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile + ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "BASEErrorLog_'_""_]]_Path__Job1Output1" } } } diff --git a/tests/Get-DbaAgentJobOutputFile.Tests.ps1 b/tests/Get-DbaAgentJobOutputFile.Tests.ps1 index ea63f48ded44..37a0d89025d7 100644 --- a/tests/Get-DbaAgentJobOutputFile.Tests.ps1 +++ b/tests/Get-DbaAgentJobOutputFile.Tests.ps1 @@ -1,66 +1,76 @@ -$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-DbaAgentJobOutputFile", + $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', 'Job', 'ExcludeJob', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe $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", + "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" { + Context "Return values" { + BeforeAll { Mock Connect-DbaInstance -MockWith { [object]@{ - Name = 'SQLServerName' - ComputerName = 'SQLServerName' + Name = "SQLServerName" + ComputerName = "SQLServerName" JobServer = @{ Jobs = @( @{ - Name = 'Job1' + Name = "Job1" JobSteps = @( @{ Id = 1 - Name = 'Job1Step1' - OutputFileName = 'Job1Output1' + Name = "Job1Step1" + OutputFileName = "Job1Output1" }, @{ Id = 2 - Name = 'Job1Step2' - OutputFileName = 'Job1Output2' + Name = "Job1Step2" + OutputFileName = "Job1Output2" } ) }, @{ - Name = 'Job2' + Name = "Job2" JobSteps = @( @{ Id = 1 - Name = 'Job2Step1' - OutputFileName = 'Job2Output1' + Name = "Job2Step1" + OutputFileName = "Job2Output1" }, @{ Id = 2 - Name = 'Job2Step2' + Name = "Job2Step2" } ) }, @{ - Name = 'Job3' + Name = "Job3" JobSteps = @( @{ Id = 1 - Name = 'Job3Step1' + Name = "Job3Step1" }, @{ Id = 2 - Name = 'Job3Step2' + Name = "Job3Step2" } ) } @@ -68,35 +78,35 @@ Describe "$CommandName Unittests" -Tag 'UnitTests' { } } #object } #mock Connect-DbaInstance - It "Gets only steps with output files" { - $Results = @() - $Results += Get-DbaAgentJobOutputFile -SqlInstance 'SQLServerName' - $Results.Length | Should Be 3 - $Results.Job | Should Match 'Job[12]' - $Results.JobStep | Should Match 'Job[12]Step[12]' - $Results.OutputFileName | Should Match 'Job[12]Output[12]' - $Results.RemoteOutputFileName | Should Match '\\\\SQLServerName\\Job[12]Output[12]' - } - It "Honors the Job parameter" { - $Results = @() - $Results += Get-DbaAgentJobOutputFile -SqlInstance 'SQLServerName' -Job 'Job1' - $Results.Job | Should Match 'Job1' - $Results.JobStep | Should Match 'Job1Step[12]' - $Results.OutputFileName | Should Match 'Job1Output[12]' - } - It "Honors the ExcludeJob parameter" { - $Results = @() - $Results += Get-DbaAgentJobOutputFile -SqlInstance 'SQLServerName' -ExcludeJob 'Job1' - $Results.Length | Should Be 1 - $Results.Job | Should Match 'Job2' - $Results.OutputFileName | Should Be 'Job2Output1' - $Results.StepId | Should Be 1 - } - It "Does not return even with a specific job without outputfiles" { - $Results = @() - $Results += Get-DbaAgentJobOutputFile -SqlInstance 'SQLServerName' -Job 'Job3' - $Results.Length | Should Be 0 - } + } + + It "Gets only steps with output files" { + $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" { + $results = @(Get-DbaAgentJobOutputFile -SqlInstance "SQLServerName" -Job "Job1") + $results.Job | Should -Match "Job1" + $results.JobStep | Should -Match "Job1Step[12]" + $results.OutputFileName | Should -Match "Job1Output[12]" + } + + It "Honors the ExcludeJob parameter" { + $results = @(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" { + $results = @(Get-DbaAgentJobOutputFile -SqlInstance "SQLServerName" -Job "Job3") + $results.Count | Should -BeExactly 0 } } } \ No newline at end of file diff --git a/tests/Get-DbaAgentJobStep.Tests.ps1 b/tests/Get-DbaAgentJobStep.Tests.ps1 index b32e78277058..030d585ba423 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-DbaAgentLog.Tests.ps1 b/tests/Get-DbaAgentLog.Tests.ps1 index 1445215a9d62..da812b7dc8ef 100644 --- a/tests/Get-DbaAgentLog.Tests.ps1 +++ b/tests/Get-DbaAgentLog.Tests.ps1 @@ -1,35 +1,62 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaAgentLog", + $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', 'LogNumber', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe $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", + "LogNumber", + "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 + + # Get the agent log for testing + $agentLogResults = Get-DbaAgentLog -SqlInstance $TestConfig.instance2 + $currentLogResults = Get-DbaAgentLog -SqlInstance $TestConfig.instance2 -LogNumber 0 + + # 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') + } + Context "Command gets agent log" { - $results = Get-DbaAgentLog -SqlInstance $TestConfig.instance2 It "Results are not empty" { - $results | Should Not Be $Null + $agentLogResults | Should -Not -BeNullOrEmpty } + It "Results contain SQLServerAgent version" { - $results.text -like '`[100`] Microsoft SQLServerAgent version*' | Should Be $true + $agentLogResults.text -like "`[100`] Microsoft SQLServerAgent version*" | Should -Be $true } + It "LogDate is a DateTime type" { - $($results | Select-Object -first 1).LogDate | Should BeOfType DateTime + $agentLogResults[0].LogDate | Should -BeOfType DateTime } } + Context "Command gets current agent log using LogNumber parameter" { - $results = Get-DbaAgentLog -SqlInstance $TestConfig.instance2 -LogNumber 0 It "Results are not empty" { - $results | Should Not Be $Null + $currentLogResults | Should -Not -BeNullOrEmpty } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaAgentOperator.Tests.ps1 b/tests/Get-DbaAgentOperator.Tests.ps1 index 9cc587ebbcd9..e3f24595317e 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 55d5ff43ece0..065cf947966d 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 75743080d0f1..1573a26dca93 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 0a843e4fcddd..8858ae1f9de8 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' { +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 + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "EnableException" + ) + } + It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { Context "Command gets server agent" { - $results = Get-DbaAgentServer -SqlInstance $TestConfig.instance2 + BeforeAll { + $results = @(Get-DbaAgentServer -SqlInstance $TestConfig.instance2) + } + It "Should get 1 agent server" { - $results.count | Should Be 1 + $results.Status.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 2ba96710a153..cedf6c372714 100644 --- a/tests/Get-DbaAvailabilityGroup.Tests.ps1 +++ b/tests/Get-DbaAvailabilityGroup.Tests.ps1 @@ -1,36 +1,76 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#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 -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 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 for specific AG" { + $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 908ecc0f1012..19a88d755e24 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 } } } diff --git a/tests/Get-DbaBackupDevice.Tests.ps1 b/tests/Get-DbaBackupDevice.Tests.ps1 index bb169b6d2672..41a8189ed057 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 3372108a8ebf..fc983d9ab3e7 100644 --- a/tests/Get-DbaBackupInformation.Tests.ps1 +++ b/tests/Get-DbaBackupInformation.Tests.ps1 @@ -1,31 +1,70 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaBackupInformation", + $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', '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 +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", + "SqlInstance", + "SqlCredential", + "DatabaseName", + "SourceInstance", + "NoXpDirTree", + "NoXpDirRecurse", + "DirectoryRecurse", + "EnableException", + "MaintenanceSolution", + "IgnoreLogBackup", + "IgnoreDiffBackup", + "ExportPath", + "AzureCredential", + "Import", + "Anonymise", + "NoClobber", + "PassThru" + ) + } + + 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 + + # 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. + $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 + $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 @@ -33,18 +72,24 @@ Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { $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 + $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\* @@ -53,89 +98,128 @@ 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 + $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 { + # 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 object. $null = Get-DbaDatabase -SqlInstance $TestConfig.instance1 -Database $dbname, $dbname2, $dbname3 | Remove-DbaDatabase -Confirm:$false - Remove-Item -Path $DestBackupDir, $DestBackupDirOla -Recurse -Confirm:$false + Remove-Item -Path $DestBackupDir, $DestBackupDirOla -Recurse -Confirm:$false -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 { + $allDbResults = Get-DbaBackupInformation -SqlInstance $TestConfig.instance1 -Path $DestBackupDir + } + It "Should be 6 backups returned" { - $results.count | Should Be 6 + $allDbResults.Status.Count | Should -BeExactly 6 } + It "Should return 2 full backups" { - ($results | Where-Object {$_.Type -eq 'Database'}).count | Should be 2 + ($allDbResults | Where-Object Type -eq "Database").Status.Count | Should -BeExactly 2 } + It "Should return 2 log backups" { - ($results | Where-Object {$_.Type -eq 'Transaction Log'}).count | Should be 2 + ($allDbResults | Where-Object Type -eq "Transaction Log").Status.Count | Should -BeExactly 2 } } Context "Get history for one database" { - $results = Get-DbaBackupInformation -SqlInstance $TestConfig.instance1 -Path $DestBackupDir -DatabaseName $dbname2 + BeforeAll { + $singleDbResults = Get-DbaBackupInformation -SqlInstance $TestConfig.instance1 -Path $DestBackupDir -DatabaseName $dbname2 + } + It "Should be 3 backups returned" { - $results.count | Should Be 3 + $singleDbResults.Status.Count | Should -BeExactly 3 } + It "Should Be 1 full backup" { - ($results | Where-Object {$_.Type -eq 'Database'}).count | Should be 1 + ($singleDbResults | Where-Object Type -eq "Database").Status.Count | Should -BeExactly 1 } + It "Should be 1 log backups" { - ($results | Where-Object {$_.Type -eq 'Transaction Log'}).count | Should be 1 + ($singleDbResults | Where-Object Type -eq "Transaction Log").Status.Count | Should -BeExactly 1 } + It "Should only be backups of $dbname2" { - ($results | Where-Object {$_.Database -ne $dbname2 }).count | Should Be 0 + ($singleDbResults | Where-Object Database -ne $dbname2).Status.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 + $exportResults = Get-DbaBackupInformation -SqlInstance $TestConfig.instance1 -Path $DestBackupDir -DatabaseName $dbname2 -ExportPath "$DestBackupDir\history.xml" - # 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 + ($exportResults | Where-Object RestoreComplete -eq $false).Status.Count | Should -BeExactly 0 } } Context "Test Maintenance solution options" { - $results = Get-DbaBackupInformation -SqlInstance $TestConfig.instance1 -Path $DestBackupDirOla -MaintenanceSolution + BeforeAll { + $olaResults = Get-DbaBackupInformation -SqlInstance $TestConfig.instance1 -Path $DestBackupDirOla -MaintenanceSolution + $olaResultsSanLog = Get-DbaBackupInformation -SqlInstance $TestConfig.instance1 -Path $DestBackupDirOla -MaintenanceSolution -IgnoreLogBackup + $olaResultsWarnTest = Get-DbaBackupInformation -SqlInstance $TestConfig.instance1 -Path $DestBackupDirOla -IgnoreLogBackup -WarningVariable warnvar -WarningAction SilentlyContinue 3> $null + } + It "Should be 3 backups returned" { - $results.count | Should Be 3 + $olaResults.Status.Count | Should -BeExactly 3 } + It "Should Be 1 full backup" { - ($results | Where-Object {$_.Type -eq 'Database'}).count | Should be 1 + ($olaResults | Where-Object Type -eq "Database").Status.Count | Should -BeExactly 1 } + It "Should be 1 log backups" { - ($results | Where-Object {$_.Type -eq 'Transaction Log'}).count | Should be 1 + ($olaResults | Where-Object Type -eq "Transaction Log").Status.Count | Should -BeExactly 1 } + It "Should only be backups of $dbname3" { - ($results | Where-Object {$_.Database -ne $dbname3 }).count | Should Be 0 + ($olaResults | Where-Object Database -ne $dbname3).Status.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 + $olaResultsSanLog.Status.Count | Should -BeExactly 2 } + It "Should Be 1 full backup" { - ($ResultsSanLog | Where-Object {$_.Type -eq 'Database'}).count | Should be 1 + ($olaResultsSanLog | Where-Object Type -eq "Database").Status.Count | Should -BeExactly 1 } + It "Should be 0 log backups" { - ($resultsSanLog | Where-Object {$_.Type -eq 'Transaction Log'}).count | Should be 0 + ($olaResultsSanLog | Where-Object Type -eq "Transaction Log").Status.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" { $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 + $olaResultsWarnTest.Status.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 f350d7a7c41f..32e27507274b 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" { From 1f17830b00715d96d6e27afd839e0a4d4445f5aa Mon Sep 17 00:00:00 2001 From: Chrissy LeMaire Date: Sat, 9 Aug 2025 07:42:28 +0200 Subject: [PATCH 02/14] Enhance formatter to preserve alignment and avoid unnecessary writes Updated Invoke-DbatoolsFormatter to use custom PSSA settings that preserve manually aligned hashtables and assignment operators. The script now only writes files if formatting changes are detected, reducing unnecessary file writes. --- public/Invoke-DbatoolsFormatter.ps1 | 62 +++++++++++++++++++++++++++-- 1 file changed, 59 insertions(+), 3 deletions(-) diff --git a/public/Invoke-DbatoolsFormatter.ps1 b/public/Invoke-DbatoolsFormatter.ps1 index 257af695f4e6..07b8e0b9ce4c 100644 --- a/public/Invoke-DbatoolsFormatter.ps1 +++ b/public/Invoke-DbatoolsFormatter.ps1 @@ -5,6 +5,8 @@ function Invoke-DbatoolsFormatter { .DESCRIPTION Uses PSSA's Invoke-Formatter to format the target files and saves it without the BOM. + Preserves manually aligned hashtables and assignment operators. + Only writes files if formatting changes are detected. .PARAMETER Path The path to the ps1 file that needs to be formatted @@ -57,6 +59,48 @@ function Invoke-DbatoolsFormatter { $CBHRex = [regex]'(?smi)\s+\<\#[^#]*\#\>' $CBHStartRex = [regex]'(?[ ]+)\<\#' $CBHEndRex = [regex]'(?[ ]*)\#\>' + + # Create custom formatter settings that preserve alignment + $customSettings = @{ + IncludeRules = @( + 'PSPlaceOpenBrace', + 'PSPlaceCloseBrace', + 'PSUseConsistentIndentation', + 'PSUseConsistentWhitespace' + ) + Rules = @{ + PSPlaceOpenBrace = @{ + Enable = $true + OnSameLine = $true + NewLineAfter = $true + IgnoreOneLineBlock = $true + } + PSPlaceCloseBrace = @{ + Enable = $true + NewLineAfter = $false + IgnoreOneLineBlock = $true + NoEmptyLineBefore = $false + } + PSUseConsistentIndentation = @{ + Enable = $true + Kind = 'space' + PipelineIndentation = 'IncreaseIndentationForFirstPipeline' + IndentationSize = 4 + } + PSUseConsistentWhitespace = @{ + Enable = $true + CheckInnerBrace = $true + CheckOpenBrace = $true + CheckOpenParen = $true + CheckOperator = $false # This is key - don't mess with operator spacing + CheckPipe = $true + CheckPipeForRedundantWhitespace = $false + CheckSeparator = $true + CheckParameter = $false + } + } + } + $OSEOL = "`n" if ($psVersionTable.Platform -ne 'Unix') { $OSEOL = "`r`n" @@ -71,7 +115,9 @@ function Invoke-DbatoolsFormatter { Stop-Function -Message "Cannot find or resolve $p" -Continue } - $content = Get-Content -Path $realPath -Raw -Encoding UTF8 + $originalContent = Get-Content -Path $realPath -Raw -Encoding UTF8 + $content = $originalContent + if ($OSEOL -eq "`r`n") { # See #5830, we are in Windows territory here # Is the file containing at least one `r ? @@ -85,7 +131,8 @@ function Invoke-DbatoolsFormatter { #strip ending empty lines $content = $content -replace "(?s)$OSEOL\s*$" try { - $content = Invoke-Formatter -ScriptDefinition $content -Settings CodeFormattingOTBS -ErrorAction Stop + # Use custom settings instead of CodeFormattingOTBS + $content = Invoke-Formatter -ScriptDefinition $content -Settings $customSettings -ErrorAction Stop } catch { Write-Message -Level Warning "Unable to format $p" } @@ -118,7 +165,16 @@ function Invoke-DbatoolsFormatter { #trim whitespace lines $realContent += $line.Replace("`t", " ").TrimEnd() } - [System.IO.File]::WriteAllText($realPath, ($realContent -Join "$OSEOL"), $Utf8NoBomEncoding) + + $finalContent = $realContent -Join "$OSEOL" + + # Only write the file if there are actual changes + if ($finalContent -ne $originalContent) { + Write-Message -Level Verbose "Formatting changes detected in $realPath" + [System.IO.File]::WriteAllText($realPath, $finalContent, $Utf8NoBomEncoding) + } else { + Write-Message -Level Verbose "No formatting changes needed for $realPath" + } } } } \ No newline at end of file From b07ac96cd1b07e00f4320a15d84570b3adf9df72 Mon Sep 17 00:00:00 2001 From: Chrissy LeMaire Date: Sat, 9 Aug 2025 07:51:17 +0200 Subject: [PATCH 03/14] Improve file handling in Invoke-DbatoolsFormatter Added checks to skip directories and non-PowerShell files, improved error handling for file read/write operations, and ensured only valid content is processed. These changes enhance robustness and prevent errors when processing invalid or unreadable files. --- public/Invoke-DbatoolsFormatter.ps1 | 44 +++++++++++++++++++++++++---- 1 file changed, 39 insertions(+), 5 deletions(-) diff --git a/public/Invoke-DbatoolsFormatter.ps1 b/public/Invoke-DbatoolsFormatter.ps1 index 07b8e0b9ce4c..28e1c26ef694 100644 --- a/public/Invoke-DbatoolsFormatter.ps1 +++ b/public/Invoke-DbatoolsFormatter.ps1 @@ -68,7 +68,7 @@ function Invoke-DbatoolsFormatter { 'PSUseConsistentIndentation', 'PSUseConsistentWhitespace' ) - Rules = @{ + Rules = @{ PSPlaceOpenBrace = @{ Enable = $true OnSameLine = $true @@ -115,7 +115,29 @@ function Invoke-DbatoolsFormatter { Stop-Function -Message "Cannot find or resolve $p" -Continue } - $originalContent = Get-Content -Path $realPath -Raw -Encoding UTF8 + # Skip directories and non-PowerShell files + if (Test-Path -Path $realPath -PathType Container) { + Write-Message -Level Verbose "Skipping directory: $realPath" + continue + } + + if ($realPath -notmatch '\.ps1$|\.psm1$|\.psd1$') { + Write-Message -Level Verbose "Skipping non-PowerShell file: $realPath" + continue + } + + try { + $originalContent = Get-Content -Path $realPath -Raw -Encoding UTF8 + } catch { + Stop-Function -Message "Unable to read file $realPath : $($_.Exception.Message)" -Continue + } + + # If Get-Content failed, originalContent might be null or empty + if (-not $originalContent) { + Write-Message -Level Verbose "Skipping empty or unreadable file: $realPath" + continue + } + $content = $originalContent if ($OSEOL -eq "`r`n") { @@ -134,8 +156,16 @@ function Invoke-DbatoolsFormatter { # Use custom settings instead of CodeFormattingOTBS $content = Invoke-Formatter -ScriptDefinition $content -Settings $customSettings -ErrorAction Stop } catch { - Write-Message -Level Warning "Unable to format $p" + Write-Message -Level Warning "Unable to format $realPath : $($_.Exception.Message)" + continue + } + + # Ensure $content is a string before processing + if (-not $content -or $content -isnot [string]) { + Write-Message -Level Warning "Formatter returned unexpected content type for $realPath" + continue } + #match the ending indentation of CBH with the starting one, see #4373 $CBH = $CBHRex.Match($content).Value if ($CBH) { @@ -170,8 +200,12 @@ function Invoke-DbatoolsFormatter { # Only write the file if there are actual changes if ($finalContent -ne $originalContent) { - Write-Message -Level Verbose "Formatting changes detected in $realPath" - [System.IO.File]::WriteAllText($realPath, $finalContent, $Utf8NoBomEncoding) + try { + Write-Message -Level Verbose "Formatting changes detected in $realPath" + [System.IO.File]::WriteAllText($realPath, $finalContent, $Utf8NoBomEncoding) + } catch { + Stop-Function -Message "Unable to write file $realPath : $($_.Exception.Message)" -Continue + } } else { Write-Message -Level Verbose "No formatting changes needed for $realPath" } From 4b4c3b5d20f6bf9c6930a32a9d3ea5de5b10f57a Mon Sep 17 00:00:00 2001 From: Chrissy LeMaire Date: Sat, 9 Aug 2025 08:04:14 +0200 Subject: [PATCH 04/14] Improve formatting comparison in Invoke-DbatoolsFormatter Enhances the formatter to compare processed, formatted content rather than raw content, ensuring that only meaningful formatting changes trigger file writes. Also applies CBH (Comment-Based Help) fixes and whitespace normalization to both the original and formatted content for accurate comparison. --- public/Invoke-DbatoolsFormatter.ps1 | 51 ++++++++++++++++++++++------- 1 file changed, 40 insertions(+), 11 deletions(-) diff --git a/public/Invoke-DbatoolsFormatter.ps1 b/public/Invoke-DbatoolsFormatter.ps1 index 28e1c26ef694..d2ad580c3766 100644 --- a/public/Invoke-DbatoolsFormatter.ps1 +++ b/public/Invoke-DbatoolsFormatter.ps1 @@ -68,7 +68,7 @@ function Invoke-DbatoolsFormatter { 'PSUseConsistentIndentation', 'PSUseConsistentWhitespace' ) - Rules = @{ + Rules = @{ PSPlaceOpenBrace = @{ Enable = $true OnSameLine = $true @@ -150,36 +150,55 @@ function Invoke-DbatoolsFormatter { } } - #strip ending empty lines + # Strip ending empty lines from both original and working content $content = $content -replace "(?s)$OSEOL\s*$" + $originalStripped = $originalContent -replace "(?s)$OSEOL\s*$" + try { - # Use custom settings instead of CodeFormattingOTBS + # Format the content $content = Invoke-Formatter -ScriptDefinition $content -Settings $customSettings -ErrorAction Stop + # Also format the original to compare + $originalFormatted = Invoke-Formatter -ScriptDefinition $originalStripped -Settings $customSettings -ErrorAction Stop } catch { Write-Message -Level Warning "Unable to format $realPath : $($_.Exception.Message)" continue } - # Ensure $content is a string before processing + # Ensure both contents are strings before processing if (-not $content -or $content -isnot [string]) { Write-Message -Level Warning "Formatter returned unexpected content type for $realPath" continue } - #match the ending indentation of CBH with the starting one, see #4373 + if (-not $originalFormatted -or $originalFormatted -isnot [string]) { + Write-Message -Level Warning "Formatter returned unexpected content type for original in $realPath" + continue + } + + # Apply CBH fix to formatted content $CBH = $CBHRex.Match($content).Value if ($CBH) { - #get starting spaces $startSpaces = $CBHStartRex.Match($CBH).Groups['spaces'] if ($startSpaces) { - #get end $newCBH = $CBHEndRex.Replace($CBH, "$startSpaces#>") if ($newCBH) { - #replace the CBH $content = $content.Replace($CBH, $newCBH) } } } + + # Apply CBH fix to original formatted content + $originalCBH = $CBHRex.Match($originalFormatted).Value + if ($originalCBH) { + $startSpaces = $CBHStartRex.Match($originalCBH).Groups['spaces'] + if ($startSpaces) { + $newOriginalCBH = $CBHEndRex.Replace($originalCBH, "$startSpaces#>") + if ($newOriginalCBH) { + $originalFormatted = $originalFormatted.Replace($originalCBH, $newOriginalCBH) + } + } + } + $Utf8NoBomEncoding = New-Object System.Text.UTF8Encoding $False $correctCase = @( 'DbaInstanceParameter' @@ -187,19 +206,29 @@ function Invoke-DbatoolsFormatter { 'PSCustomObject' 'PSItem' ) + + # Process the formatted content $realContent = @() foreach ($line in $content.Split("`n")) { foreach ($item in $correctCase) { $line = $line -replace $item, $item } - #trim whitespace lines $realContent += $line.Replace("`t", " ").TrimEnd() } - $finalContent = $realContent -Join "$OSEOL" + # Process the original formatted content the same way + $originalProcessed = @() + foreach ($line in $originalFormatted.Split("`n")) { + foreach ($item in $correctCase) { + $line = $line -replace $item, $item + } + $originalProcessed += $line.Replace("`t", " ").TrimEnd() + } + $originalFinalContent = $originalProcessed -Join "$OSEOL" + # Only write the file if there are actual changes - if ($finalContent -ne $originalContent) { + if ($finalContent -ne $originalFinalContent) { try { Write-Message -Level Verbose "Formatting changes detected in $realPath" [System.IO.File]::WriteAllText($realPath, $finalContent, $Utf8NoBomEncoding) From 05eb89782d276dfefc75dcc0e5ae1becc20fe38c Mon Sep 17 00:00:00 2001 From: Chrissy LeMaire Date: Sat, 9 Aug 2025 08:42:53 +0200 Subject: [PATCH 05/14] Refactor Invoke-DbatoolsFormatter for improved formatting Simplifies the formatter by removing custom alignment-preserving settings and redundant code. Now uses a placeholder approach to preserve aligned assignments, streamlines file type checks, and only writes files if actual formatting changes are detected. Improves maintainability and reliability of the formatting process. --- public/Invoke-DbatoolsFormatter.ps1 | 150 +++++++--------------------- 1 file changed, 36 insertions(+), 114 deletions(-) diff --git a/public/Invoke-DbatoolsFormatter.ps1 b/public/Invoke-DbatoolsFormatter.ps1 index d2ad580c3766..2c724b63cb3a 100644 --- a/public/Invoke-DbatoolsFormatter.ps1 +++ b/public/Invoke-DbatoolsFormatter.ps1 @@ -5,8 +5,6 @@ function Invoke-DbatoolsFormatter { .DESCRIPTION Uses PSSA's Invoke-Formatter to format the target files and saves it without the BOM. - Preserves manually aligned hashtables and assignment operators. - Only writes files if formatting changes are detected. .PARAMETER Path The path to the ps1 file that needs to be formatted @@ -59,48 +57,6 @@ function Invoke-DbatoolsFormatter { $CBHRex = [regex]'(?smi)\s+\<\#[^#]*\#\>' $CBHStartRex = [regex]'(?[ ]+)\<\#' $CBHEndRex = [regex]'(?[ ]*)\#\>' - - # Create custom formatter settings that preserve alignment - $customSettings = @{ - IncludeRules = @( - 'PSPlaceOpenBrace', - 'PSPlaceCloseBrace', - 'PSUseConsistentIndentation', - 'PSUseConsistentWhitespace' - ) - Rules = @{ - PSPlaceOpenBrace = @{ - Enable = $true - OnSameLine = $true - NewLineAfter = $true - IgnoreOneLineBlock = $true - } - PSPlaceCloseBrace = @{ - Enable = $true - NewLineAfter = $false - IgnoreOneLineBlock = $true - NoEmptyLineBefore = $false - } - PSUseConsistentIndentation = @{ - Enable = $true - Kind = 'space' - PipelineIndentation = 'IncreaseIndentationForFirstPipeline' - IndentationSize = 4 - } - PSUseConsistentWhitespace = @{ - Enable = $true - CheckInnerBrace = $true - CheckOpenBrace = $true - CheckOpenParen = $true - CheckOperator = $false # This is key - don't mess with operator spacing - CheckPipe = $true - CheckPipeForRedundantWhitespace = $false - CheckSeparator = $true - CheckParameter = $false - } - } - } - $OSEOL = "`n" if ($psVersionTable.Platform -ne 'Unix') { $OSEOL = "`r`n" @@ -115,29 +71,13 @@ function Invoke-DbatoolsFormatter { Stop-Function -Message "Cannot find or resolve $p" -Continue } - # Skip directories and non-PowerShell files + # Skip directories if (Test-Path -Path $realPath -PathType Container) { Write-Message -Level Verbose "Skipping directory: $realPath" continue } - if ($realPath -notmatch '\.ps1$|\.psm1$|\.psd1$') { - Write-Message -Level Verbose "Skipping non-PowerShell file: $realPath" - continue - } - - try { - $originalContent = Get-Content -Path $realPath -Raw -Encoding UTF8 - } catch { - Stop-Function -Message "Unable to read file $realPath : $($_.Exception.Message)" -Continue - } - - # If Get-Content failed, originalContent might be null or empty - if (-not $originalContent) { - Write-Message -Level Verbose "Skipping empty or unreadable file: $realPath" - continue - } - + $originalContent = Get-Content -Path $realPath -Raw -Encoding UTF8 $content = $originalContent if ($OSEOL -eq "`r`n") { @@ -150,55 +90,48 @@ function Invoke-DbatoolsFormatter { } } - # Strip ending empty lines from both original and working content + #strip ending empty lines $content = $content -replace "(?s)$OSEOL\s*$" - $originalStripped = $originalContent -replace "(?s)$OSEOL\s*$" - try { - # Format the content - $content = Invoke-Formatter -ScriptDefinition $content -Settings $customSettings -ErrorAction Stop - # Also format the original to compare - $originalFormatted = Invoke-Formatter -ScriptDefinition $originalStripped -Settings $customSettings -ErrorAction Stop - } catch { - Write-Message -Level Warning "Unable to format $realPath : $($_.Exception.Message)" - continue + # Preserve aligned assignments before formatting + # Look for patterns with multiple spaces before OR after the = sign + $alignedPatterns = [regex]::Matches($content, '(?m)^\s*(\$\w+|\w+)\s{2,}=\s*.+$|^\s*(\$\w+|\w+)\s*=\s{2,}.+$') + $placeholders = @{} + + foreach ($match in $alignedPatterns) { + $placeholder = "___ALIGNMENT_PLACEHOLDER_$($placeholders.Count)___" + $placeholders[$placeholder] = $match.Value + $content = $content.Replace($match.Value, $placeholder) } - # Ensure both contents are strings before processing - if (-not $content -or $content -isnot [string]) { - Write-Message -Level Warning "Formatter returned unexpected content type for $realPath" - continue + try { + $formattedContent = Invoke-Formatter -ScriptDefinition $content -Settings CodeFormattingOTBS -ErrorAction Stop + if ($formattedContent) { + $content = $formattedContent + } + } catch { + # Just silently continue - the formatting might still work partially } - if (-not $originalFormatted -or $originalFormatted -isnot [string]) { - Write-Message -Level Warning "Formatter returned unexpected content type for original in $realPath" - continue + # Restore the aligned patterns + foreach ($key in $placeholders.Keys) { + $content = $content.Replace($key, $placeholders[$key]) } - # Apply CBH fix to formatted content + #match the ending indentation of CBH with the starting one, see #4373 $CBH = $CBHRex.Match($content).Value if ($CBH) { + #get starting spaces $startSpaces = $CBHStartRex.Match($CBH).Groups['spaces'] if ($startSpaces) { + #get end $newCBH = $CBHEndRex.Replace($CBH, "$startSpaces#>") if ($newCBH) { + #replace the CBH $content = $content.Replace($CBH, $newCBH) } } } - - # Apply CBH fix to original formatted content - $originalCBH = $CBHRex.Match($originalFormatted).Value - if ($originalCBH) { - $startSpaces = $CBHStartRex.Match($originalCBH).Groups['spaces'] - if ($startSpaces) { - $newOriginalCBH = $CBHEndRex.Replace($originalCBH, "$startSpaces#>") - if ($newOriginalCBH) { - $originalFormatted = $originalFormatted.Replace($originalCBH, $newOriginalCBH) - } - } - } - $Utf8NoBomEncoding = New-Object System.Text.UTF8Encoding $False $correctCase = @( 'DbaInstanceParameter' @@ -206,37 +139,26 @@ function Invoke-DbatoolsFormatter { 'PSCustomObject' 'PSItem' ) - - # Process the formatted content $realContent = @() foreach ($line in $content.Split("`n")) { foreach ($item in $correctCase) { $line = $line -replace $item, $item } + #trim whitespace lines $realContent += $line.Replace("`t", " ").TrimEnd() } - $finalContent = $realContent -Join "$OSEOL" - # Process the original formatted content the same way - $originalProcessed = @() - foreach ($line in $originalFormatted.Split("`n")) { - foreach ($item in $correctCase) { - $line = $line -replace $item, $item - } - $originalProcessed += $line.Replace("`t", " ").TrimEnd() - } - $originalFinalContent = $originalProcessed -Join "$OSEOL" + $newContent = $realContent -Join "$OSEOL" - # Only write the file if there are actual changes - if ($finalContent -ne $originalFinalContent) { - try { - Write-Message -Level Verbose "Formatting changes detected in $realPath" - [System.IO.File]::WriteAllText($realPath, $finalContent, $Utf8NoBomEncoding) - } catch { - Stop-Function -Message "Unable to write file $realPath : $($_.Exception.Message)" -Continue - } + # Compare without empty lines to detect real changes + $originalNonEmpty = ($originalContent -split "[\r\n]+" | Where-Object { $_.Trim() }) -join "" + $newNonEmpty = ($newContent -split "[\r\n]+" | Where-Object { $_.Trim() }) -join "" + + if ($originalNonEmpty -ne $newNonEmpty) { + [System.IO.File]::WriteAllText($realPath, $newContent, $Utf8NoBomEncoding) + Write-Message -Level Verbose "Updated: $realPath" } else { - Write-Message -Level Verbose "No formatting changes needed for $realPath" + Write-Message -Level Verbose "No changes needed: $realPath" } } } From 21da25c076867558a2a75d35f08af8c500f7c2d2 Mon Sep 17 00:00:00 2001 From: Chrissy LeMaire Date: Sat, 9 Aug 2025 08:44:39 +0200 Subject: [PATCH 06/14] Add progress reporting to Invoke-DbatoolsFormatter Enhanced Invoke-DbatoolsFormatter to display progress when formatting multiple files, including status updates for each file, error handling, and a summary of processed and updated files. This improves user feedback during batch operations. --- public/Invoke-DbatoolsFormatter.ps1 | 40 ++++++++++++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/public/Invoke-DbatoolsFormatter.ps1 b/public/Invoke-DbatoolsFormatter.ps1 index 2c724b63cb3a..4380d83ad538 100644 --- a/public/Invoke-DbatoolsFormatter.ps1 +++ b/public/Invoke-DbatoolsFormatter.ps1 @@ -29,6 +29,11 @@ function Invoke-DbatoolsFormatter { PS C:\> Invoke-DbatoolsFormatter -Path C:\dbatools\public\Get-DbaDatabase.ps1 Reformats C:\dbatools\public\Get-DbaDatabase.ps1 to dbatools' standards + + .EXAMPLE + PS C:\> Get-ChildItem *.ps1 | Invoke-DbatoolsFormatter + + Reformats all .ps1 files in the current directory, showing progress for the batch operation #> [CmdletBinding()] param ( @@ -61,22 +66,44 @@ function Invoke-DbatoolsFormatter { if ($psVersionTable.Platform -ne 'Unix') { $OSEOL = "`r`n" } + + # Collect all paths for progress tracking + $allPaths = @() } process { if (Test-FunctionInterrupt) { return } - foreach ($p in $Path) { + # Collect all paths from pipeline + $allPaths += $Path + } + end { + if (Test-FunctionInterrupt) { return } + + $totalFiles = $allPaths.Count + $currentFile = 0 + $processedFiles = 0 + $updatedFiles = 0 + + foreach ($p in $allPaths) { + $currentFile++ + try { $realPath = (Resolve-Path -Path $p -ErrorAction Stop).Path } catch { + Write-Progress -Activity "Formatting PowerShell files" -Status "Error resolving path: $p" -PercentComplete (($currentFile / $totalFiles) * 100) -CurrentOperation "File $currentFile of $totalFiles" Stop-Function -Message "Cannot find or resolve $p" -Continue + continue } # Skip directories if (Test-Path -Path $realPath -PathType Container) { + Write-Progress -Activity "Formatting PowerShell files" -Status "Skipping directory: $realPath" -PercentComplete (($currentFile / $totalFiles) * 100) -CurrentOperation "File $currentFile of $totalFiles" Write-Message -Level Verbose "Skipping directory: $realPath" continue } + $fileName = Split-Path -Leaf $realPath + Write-Progress -Activity "Formatting PowerShell files" -Status "Processing: $fileName" -PercentComplete (($currentFile / $totalFiles) * 100) -CurrentOperation "File $currentFile of $totalFiles" + $originalContent = Get-Content -Path $realPath -Raw -Encoding UTF8 $content = $originalContent @@ -157,9 +184,20 @@ function Invoke-DbatoolsFormatter { if ($originalNonEmpty -ne $newNonEmpty) { [System.IO.File]::WriteAllText($realPath, $newContent, $Utf8NoBomEncoding) Write-Message -Level Verbose "Updated: $realPath" + $updatedFiles++ } else { Write-Message -Level Verbose "No changes needed: $realPath" } + + $processedFiles++ } + + # Complete the progress bar + Write-Progress -Activity "Formatting PowerShell files" -Status "Complete" -PercentComplete 100 -CurrentOperation "Processed $processedFiles files, updated $updatedFiles" + Start-Sleep -Milliseconds 500 # Brief pause to show completion + Write-Progress -Activity "Formatting PowerShell files" -Completed + + # Summary message + Write-Message -Level Verbose "Formatting complete: Processed $processedFiles files, updated $updatedFiles files" } } \ No newline at end of file From 1027a6cc2e18916bcf176809190e35a557f13f4a Mon Sep 17 00:00:00 2001 From: Chrissy LeMaire Date: Sat, 9 Aug 2025 08:47:03 +0200 Subject: [PATCH 07/14] Fix whitespace and formatting in test scripts This commit corrects minor whitespace and formatting inconsistencies in several test files, including removal of trailing spaces and standardizing indentation. No functional changes were made. --- tests/Find-DbaDatabase.Tests.ps1 | 4 ++-- tests/Find-DbaOrphanedFile.Tests.ps1 | 4 ++-- tests/Format-DbaBackupInformation.Tests.ps1 | 2 +- tests/Get-DbaBackupInformation.Tests.ps1 | 4 ++-- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/tests/Find-DbaDatabase.Tests.ps1 b/tests/Find-DbaDatabase.Tests.ps1 index 4074672f5d9d..d574fa4393b1 100644 --- a/tests/Find-DbaDatabase.Tests.ps1 +++ b/tests/Find-DbaDatabase.Tests.ps1 @@ -21,7 +21,7 @@ Describe $CommandName -Tag UnitTests { $expectedParameters = $TestConfig.CommonParameters $expectedParameters += @( "SqlInstance", - "SqlCredential", + "SqlCredential", "Property", "Pattern", "Exact", @@ -44,7 +44,7 @@ Describe $CommandName -Tag IntegrationTests { It "Should return correct properties" { $expectedProps = @( "ComputerName", - "InstanceName", + "InstanceName", "SqlInstance", "Name", "Id", diff --git a/tests/Find-DbaOrphanedFile.Tests.ps1 b/tests/Find-DbaOrphanedFile.Tests.ps1 index 0545f9edffd0..1143f404fdde 100644 --- a/tests/Find-DbaOrphanedFile.Tests.ps1 +++ b/tests/Find-DbaOrphanedFile.Tests.ps1 @@ -55,7 +55,7 @@ Describe $CommandName -Tag IntegrationTests { $tmpdir2 = "c:\temp\orphan_$(Get-Random)" $tmpdirInner2 = Join-Path $tmpdir2 "inner" $tmpBackupPath2 = Join-Path $tmpdirInner2 "backup" - + # Create the objects. $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 $db1 = New-DbaDatabase -SqlInstance $server -Name $dbname @@ -111,7 +111,7 @@ Describe $CommandName -Tag IntegrationTests { $results = @(Find-DbaOrphanedFile -SqlInstance $TestConfig.instance2) $ExpectedStdProps = @( "ComputerName", - "InstanceName", + "InstanceName", "SqlInstance", "Filename", "RemoteFilename" diff --git a/tests/Format-DbaBackupInformation.Tests.ps1 b/tests/Format-DbaBackupInformation.Tests.ps1 index 69b19d3056f6..fd20bcead4af 100644 --- a/tests/Format-DbaBackupInformation.Tests.ps1 +++ b/tests/Format-DbaBackupInformation.Tests.ps1 @@ -231,7 +231,7 @@ Describe $CommandName -Tag IntegrationTests { } It "Should have changed the path separator as instructed" { - $result = $outputLinux | Select-Object -ExpandProperty FullName | ForEach-Object { + $result = $outputLinux | Select-Object -ExpandProperty FullName | ForEach-Object { $all = $PSItem.Split("/") $all[0..($all.Length - 2)] -Join "/" } diff --git a/tests/Get-DbaBackupInformation.Tests.ps1 b/tests/Get-DbaBackupInformation.Tests.ps1 index fc983d9ab3e7..8ff1790662ef 100644 --- a/tests/Get-DbaBackupInformation.Tests.ps1 +++ b/tests/Get-DbaBackupInformation.Tests.ps1 @@ -15,7 +15,7 @@ Describe $CommandName -Tag UnitTests { $expectedParameters = $TestConfig.CommonParameters $expectedParameters += @( "Path", - "SqlInstance", + "SqlInstance", "SqlCredential", "DatabaseName", "SourceInstance", @@ -54,7 +54,7 @@ Describe $CommandName -Tag IntegrationTests { } else { Remove-Item $DestBackupDir\* } - + $random = Get-Random $dbname = "dbatoolsci_Backuphistory_$random" $null = Get-DbaDatabase -SqlInstance $TestConfig.instance1 -Database $dbname | Remove-DbaDatabase -Confirm:$false From a1609b747b50aacae2d13c5ef9bcb32e592b9bf3 Mon Sep 17 00:00:00 2001 From: Chrissy LeMaire Date: Sat, 9 Aug 2025 09:52:24 +0200 Subject: [PATCH 08/14] Normalize whitespace and formatting in test scripts This commit standardizes whitespace, indentation, and formatting across multiple test files for consistency. No functional changes were made; only formatting and minor style adjustments were applied. --- tests/Export-DbaXESessionTemplate.Tests.ps1 | 2 +- tests/Find-DbaAgentJob.Tests.ps1 | 4 ++-- tests/Find-DbaDbDuplicateIndex.Tests.ps1 | 2 +- tests/Find-DbaDbUnusedIndex.Tests.ps1 | 6 +++--- tests/Find-DbaInstance.Tests.ps1 | 2 +- tests/Find-DbaLoginInGroup.Tests.ps1 | 6 +++--- tests/Find-DbaSimilarTable.Tests.ps1 | 4 ++-- tests/Find-DbaView.Tests.ps1 | 12 ++++++------ tests/Format-DbaBackupInformation.Tests.ps1 | 4 ++-- tests/Get-DbaAgDatabase.Tests.ps1 | 4 ++-- tests/Get-DbaAgentAlertCategory.Tests.ps1 | 12 ++++++------ tests/Get-DbaAgentSchedule.Tests.ps1 | 2 +- tests/Get-DbaAvailableCollation.Tests.ps1 | 2 +- tests/Get-DbaBackupDevice.Tests.ps1 | 16 ++++++++-------- tests/Get-DbaBinaryFileTable.Tests.ps1 | 8 ++++---- 15 files changed, 43 insertions(+), 43 deletions(-) diff --git a/tests/Export-DbaXESessionTemplate.Tests.ps1 b/tests/Export-DbaXESessionTemplate.Tests.ps1 index 6aadaa787d72..91530c8bcc5e 100644 --- a/tests/Export-DbaXESessionTemplate.Tests.ps1 +++ b/tests/Export-DbaXESessionTemplate.Tests.ps1 @@ -45,7 +45,7 @@ Describe $CommandName -Tag IntegrationTests { # 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 diff --git a/tests/Find-DbaAgentJob.Tests.ps1 b/tests/Find-DbaAgentJob.Tests.ps1 index f60569038002..120611a200c2 100644 --- a/tests/Find-DbaAgentJob.Tests.ps1 +++ b/tests/Find-DbaAgentJob.Tests.ps1 @@ -120,8 +120,8 @@ Describe $CommandName -Tag IntegrationTests { $results | Should -Not -BeNullOrEmpty } It "Should work with multiple wildcard passed in (see #9572)" { - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job *dbatoolsci*,*dbatoolsregr* -ExcludeJobName dbatoolsci_testjob_disabled + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job *dbatoolsci*, *dbatoolsregr* -ExcludeJobName dbatoolsci_testjob_disabled @($results).Count | Should -Be 2 } } -} +} \ No newline at end of file diff --git a/tests/Find-DbaDbDuplicateIndex.Tests.ps1 b/tests/Find-DbaDbDuplicateIndex.Tests.ps1 index 85f62c65841d..b819266aed38 100644 --- a/tests/Find-DbaDbDuplicateIndex.Tests.ps1 +++ b/tests/Find-DbaDbDuplicateIndex.Tests.ps1 @@ -98,4 +98,4 @@ Describe $CommandName -Tag IntegrationTests { $results.Status.Count | Should -BeGreaterOrEqual 2 } } -} +} \ No newline at end of file diff --git a/tests/Find-DbaDbUnusedIndex.Tests.ps1 b/tests/Find-DbaDbUnusedIndex.Tests.ps1 index 202df31e18c9..9ae184310938 100644 --- a/tests/Find-DbaDbUnusedIndex.Tests.ps1 +++ b/tests/Find-DbaDbUnusedIndex.Tests.ps1 @@ -33,9 +33,9 @@ Describe $CommandName -Tag UnitTests { } } # - 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. #> diff --git a/tests/Find-DbaInstance.Tests.ps1 b/tests/Find-DbaInstance.Tests.ps1 index 8031fb81a175..ed776b58a25d 100644 --- a/tests/Find-DbaInstance.Tests.ps1 +++ b/tests/Find-DbaInstance.Tests.ps1 @@ -1,7 +1,7 @@ #Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } param( $ModuleName = "dbatools", - $CommandName = "Find-DbaInstance", # Static command name for dbatools + $CommandName = "Find-DbaInstance", # Static command name for dbatools $PSDefaultParameterValues = $TestConfig.Defaults ) diff --git a/tests/Find-DbaLoginInGroup.Tests.ps1 b/tests/Find-DbaLoginInGroup.Tests.ps1 index a2a53bb13d34..38b7a1c11249 100644 --- a/tests/Find-DbaLoginInGroup.Tests.ps1 +++ b/tests/Find-DbaLoginInGroup.Tests.ps1 @@ -27,7 +27,7 @@ Describe $CommandName -Tag UnitTests { } } # - 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. # \ No newline at end of file diff --git a/tests/Find-DbaSimilarTable.Tests.ps1 b/tests/Find-DbaSimilarTable.Tests.ps1 index ac300bb135e2..1e14a657ff09 100644 --- a/tests/Find-DbaSimilarTable.Tests.ps1 +++ b/tests/Find-DbaSimilarTable.Tests.ps1 @@ -61,7 +61,7 @@ Describe $CommandName -Tag IntegrationTests { 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 - + $results.Status.Count -ge 2 | Should -Be $true $results.OriginalDatabaseId | Should -Be $db.ID, $db.ID $results.MatchingDatabaseId | Should -Be $db.ID, $db.ID @@ -69,7 +69,7 @@ Describe $CommandName -Tag IntegrationTests { 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 } diff --git a/tests/Find-DbaView.Tests.ps1 b/tests/Find-DbaView.Tests.ps1 index 3294ca141e27..4f11d299e50d 100644 --- a/tests/Find-DbaView.Tests.ps1 +++ b/tests/Find-DbaView.Tests.ps1 @@ -43,7 +43,7 @@ AS "@ $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 @@ -56,13 +56,13 @@ AS It "Should find a specific View named v_dbatoolsci_sysadmin" { $results.Name | Should -Be "v_dbatoolsci_sysadmin" } - + It "Should find v_dbatoolsci_sysadmin in 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" @@ -74,7 +74,7 @@ AS "@ $null = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Database "dbatoolsci_viewdb" -Query $DatabaseView } - + AfterAll { $null = Remove-DbaDatabase -SqlInstance $TestConfig.instance2 -Database "dbatoolsci_viewdb" -Confirm:$false } @@ -83,13 +83,13 @@ AS $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 = 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 } - + It "Should find no results when Excluding dbatoolsci_viewdb" { $results = Find-DbaView -SqlInstance $TestConfig.instance2 -Pattern dbatools* -ExcludeDatabase "dbatoolsci_viewdb" $results | Should -BeNullOrEmpty diff --git a/tests/Format-DbaBackupInformation.Tests.ps1 b/tests/Format-DbaBackupInformation.Tests.ps1 index fd20bcead4af..606fc80bb11b 100644 --- a/tests/Format-DbaBackupInformation.Tests.ps1 +++ b/tests/Format-DbaBackupInformation.Tests.ps1 @@ -74,7 +74,7 @@ Describe $CommandName -Tag IntegrationTests { $History += Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\RestoreTimeClean.xml $splatFormat = @{ BackupHistory = $History - ReplaceDatabaseName = @{"ContinuePointTest" = "Spiggy"; "RestoreTimeClean" = "Eldritch"} + ReplaceDatabaseName = @{"ContinuePointTest" = "Spiggy"; "RestoreTimeClean" = "Eldritch" } } $output = Format-DbaBackupInformation @splatFormat } @@ -108,7 +108,7 @@ Describe $CommandName -Tag IntegrationTests { $History += Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\RestoreTimeClean.xml $splatRename = @{ BackupHistory = $History - ReplaceDatabaseName = @{"ContinuePointTest" = "Alice"} + ReplaceDatabaseName = @{"ContinuePointTest" = "Alice" } } $output = Format-DbaBackupInformation @splatRename } diff --git a/tests/Get-DbaAgDatabase.Tests.ps1 b/tests/Get-DbaAgDatabase.Tests.ps1 index 361a9c8c2e94..5c894702d7a5 100644 --- a/tests/Get-DbaAgDatabase.Tests.ps1 +++ b/tests/Get-DbaAgDatabase.Tests.ps1 @@ -49,7 +49,7 @@ Describe $CommandName -Tag IntegrationTests { $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 @@ -86,4 +86,4 @@ Describe $CommandName -Tag IntegrationTests { $results.LocalReplicaRole | Should -Not -BeNullOrEmpty } } -} #$TestConfig.instance2 for appveyor +} #$TestConfig.instance2 for appveyor \ No newline at end of file diff --git a/tests/Get-DbaAgentAlertCategory.Tests.ps1 b/tests/Get-DbaAgentAlertCategory.Tests.ps1 index 178c62942d4b..f3e9a8587436 100644 --- a/tests/Get-DbaAgentAlertCategory.Tests.ps1 +++ b/tests/Get-DbaAgentAlertCategory.Tests.ps1 @@ -31,23 +31,23 @@ 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 } - + It "Should get at least 2 categories" { $results = Get-DbaAgentAlertCategory -SqlInstance $TestConfig.instance2 | Where-Object Name -match "dbatoolsci" $results.Count | Should -BeGreaterThan 1 } - + It "Should get the dbatoolsci_testcategory category" { $results = Get-DbaAgentAlertCategory -SqlInstance $TestConfig.instance2 -Category dbatoolsci_testcategory | Where-Object Name -match "dbatoolsci" $results.Count | Should -BeExactly 1 diff --git a/tests/Get-DbaAgentSchedule.Tests.ps1 b/tests/Get-DbaAgentSchedule.Tests.ps1 index 1573a26dca93..3e47a60c579e 100644 --- a/tests/Get-DbaAgentSchedule.Tests.ps1 +++ b/tests/Get-DbaAgentSchedule.Tests.ps1 @@ -43,7 +43,7 @@ Describe $CommandName -Tag IntegrationTests { $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.instance3 -Schedule dbatoolsci_MonthlyTest -FrequencyType Monthly -FrequencyInterval 10 -FrequencyRecurrenceFactor 1 -Force - + $splatScheduleOnce = @{ SqlInstance = $TestConfig.instance2 Schedule = "Issue_6636_Once" diff --git a/tests/Get-DbaAvailableCollation.Tests.ps1 b/tests/Get-DbaAvailableCollation.Tests.ps1 index 19a88d755e24..afbc340b3b80 100644 --- a/tests/Get-DbaAvailableCollation.Tests.ps1 +++ b/tests/Get-DbaAvailableCollation.Tests.ps1 @@ -36,4 +36,4 @@ Describe $CommandName -Tag IntegrationTests { ($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 41a8189ed057..1ab73461946b 100644 --- a/tests/Get-DbaBackupDevice.Tests.ps1 +++ b/tests/Get-DbaBackupDevice.Tests.ps1 @@ -29,17 +29,17 @@ Describe $CommandName -Tag UnitTests { 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 { $PSDefaultParameterValues['*-Dba*:EnableException'] = $true - + $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 $sql = "EXEC sp_dropdevice 'dbatoolsci_tape';" $server.Query($sql) @@ -49,19 +49,19 @@ Describe $CommandName -Tag IntegrationTests { BeforeAll { $results = Get-DbaBackupDevice -SqlInstance $TestConfig.instance2 } - + It "Results are not empty" { $results | Should -Not -BeNullOrEmpty } - + It "Should have the name dbatoolsci_tape" { $results.Name | Should -Be "dbatoolsci_tape" } - + It "Should have a BackupDeviceType of Tape" { $results.BackupDeviceType | Should -Be "Tape" } - + It "Should have a PhysicalLocation of \\.\Tape0" { $results.PhysicalLocation | Should -Be "\\.\Tape0" } diff --git a/tests/Get-DbaBinaryFileTable.Tests.ps1 b/tests/Get-DbaBinaryFileTable.Tests.ps1 index 32e27507274b..d0f0ec20abc2 100644 --- a/tests/Get-DbaBinaryFileTable.Tests.ps1 +++ b/tests/Get-DbaBinaryFileTable.Tests.ps1 @@ -46,11 +46,11 @@ Describe $CommandName -Tag IntegrationTests { # 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 @@ -58,7 +58,7 @@ Describe $CommandName -Tag IntegrationTests { 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. @@ -88,4 +88,4 @@ Describe $CommandName -Tag IntegrationTests { $results = Get-DbaDbTable -SqlInstance $TestConfig.instance2 -Database tempdb | Get-DbaBinaryFileTable $results.Name.Count | Should -BeGreaterOrEqual 1 } -} +} \ No newline at end of file From 8781bdef1e44ba286857cf9b4eba2ad552851830 Mon Sep 17 00:00:00 2001 From: Chrissy LeMaire Date: Sun, 10 Aug 2025 23:50:32 +0200 Subject: [PATCH 09/14] Refactor and improve Pester test scripts Refactored test scripts for Find-DbaAgentJob, Find-DbaOrphanedFile, Format-DbaBackupInformation, and Get-DbaAgentJobHistory to improve readability, consistency, and maintainability. Changes include using splatting for parameters, removing unnecessary global variables and Write-Host statements, updating variable naming for clarity, consolidating repeated code, and aligning test assertions for accuracy. Also updated context descriptions and streamlined setup/cleanup logic in integration tests. --- tests/Find-DbaAgentJob.Tests.ps1 | 162 ++++++++++++++----- tests/Find-DbaOrphanedFile.Tests.ps1 | 116 ++++++------- tests/Format-DbaBackupInformation.Tests.ps1 | 171 +++++++++++--------- tests/Get-DbaAgentJobHistory.Tests.ps1 | 66 ++++---- tests/Get-DbaAgentJobOutputFile.Tests.ps1 | 161 ++++++++++-------- tests/Get-DbaAgentLog.Tests.ps1 | 30 ++-- tests/Get-DbaAgentServer.Tests.ps1 | 12 +- tests/Get-DbaAvailabilityGroup.Tests.ps1 | 7 +- tests/Get-DbaBackupInformation.Tests.ps1 | 154 ++++++++++++------ 9 files changed, 514 insertions(+), 365 deletions(-) diff --git a/tests/Find-DbaAgentJob.Tests.ps1 b/tests/Find-DbaAgentJob.Tests.ps1 index 120611a200c2..694e510e42ee 100644 --- a/tests/Find-DbaAgentJob.Tests.ps1 +++ b/tests/Find-DbaAgentJob.Tests.ps1 @@ -1,13 +1,10 @@ #Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } param( - $ModuleName = "dbatools", + $ModuleName = "dbatools", $CommandName = "Find-DbaAgentJob", $PSDefaultParameterValues = $TestConfig.Defaults ) -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig - Describe $CommandName -Tag UnitTests { Context "Parameter validation" { BeforeAll { @@ -46,14 +43,84 @@ Describe $CommandName -Tag IntegrationTests { # the typical error would be WARNING: [17:19:26][New-DbaAgentJobStep] Something went wrong creating the job step | The specified '@server' is #invalid (valid values are returned by sp_helpserver). $srvName = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Query "select @@servername as sn" -as PSObject - $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job "dbatoolsci_testjob" -OwnerLogin "sa" - $null = New-DbaAgentJobStep -SqlInstance $TestConfig.instance2 -Job "dbatoolsci_testjob" -StepId 1 -StepName "dbatoolsci Failed" -Subsystem TransactSql -SubsystemServer $srvName.sn -Command "RAISERROR (15600,-1,-1, 'dbatools_error');" -CmdExecSuccessCode 0 -OnSuccessAction QuitWithSuccess -OnFailAction QuitWithFailure -Database master -RetryAttempts 1 -RetryInterval 2 + + # Create test jobs + $splatTestJob = @{ + SqlInstance = $TestConfig.instance2 + Job = "dbatoolsci_testjob" + OwnerLogin = "sa" + } + $null = New-DbaAgentJob @splatTestJob + + $splatTestJobStep = @{ + SqlInstance = $TestConfig.instance2 + Job = "dbatoolsci_testjob" + StepId = 1 + StepName = "dbatoolsci Failed" + Subsystem = "TransactSql" + SubsystemServer = $srvName.sn + Command = "RAISERROR (15600,-1,-1, 'dbatools_error');" + CmdExecSuccessCode = 0 + OnSuccessAction = "QuitWithSuccess" + OnFailAction = "QuitWithFailure" + Database = "master" + RetryAttempts = 1 + RetryInterval = 2 + } + $null = New-DbaAgentJobStep @splatTestJobStep + $null = Start-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job "dbatoolsci_testjob" - $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job "dbatoolsregr_testjob" -OwnerLogin "sa" - $null = New-DbaAgentJobStep -SqlInstance $TestConfig.instance2 -Job "dbatoolsregr_testjob" -StepId 1 -StepName "dbatoolsci Failed" -Subsystem TransactSql -SubsystemServer $srvName.sn -Command "RAISERROR (15600,-1,-1, 'dbatools_error');" -CmdExecSuccessCode 0 -OnSuccessAction QuitWithSuccess -OnFailAction QuitWithFailure -Database master -RetryAttempts 1 -RetryInterval 2 + + $splatRegrJob = @{ + SqlInstance = $TestConfig.instance2 + Job = "dbatoolsregr_testjob" + OwnerLogin = "sa" + } + $null = New-DbaAgentJob @splatRegrJob + + $splatRegrJobStep = @{ + SqlInstance = $TestConfig.instance2 + Job = "dbatoolsregr_testjob" + StepId = 1 + StepName = "dbatoolsci Failed" + Subsystem = "TransactSql" + SubsystemServer = $srvName.sn + Command = "RAISERROR (15600,-1,-1, 'dbatools_error');" + CmdExecSuccessCode = 0 + OnSuccessAction = "QuitWithSuccess" + OnFailAction = "QuitWithFailure" + Database = "master" + RetryAttempts = 1 + RetryInterval = 2 + } + $null = New-DbaAgentJobStep @splatRegrJobStep + $null = New-DbaAgentJobCategory -SqlInstance $TestConfig.instance2 -Category "dbatoolsci_job_category" -CategoryType LocalJob - $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job "dbatoolsci_testjob_disabled" -Category "dbatoolsci_job_category" -Disabled - $null = New-DbaAgentJobStep -SqlInstance $TestConfig.instance2 -Job "dbatoolsci_testjob_disabled" -StepId 1 -StepName "dbatoolsci Test Step" -Subsystem TransactSql -SubsystemServer $srvName.sn -Command "SELECT * FROM master.sys.all_columns" -CmdExecSuccessCode 0 -OnSuccessAction QuitWithSuccess -OnFailAction QuitWithFailure -Database master -RetryAttempts 1 -RetryInterval 2 + + $splatDisabledJob = @{ + SqlInstance = $TestConfig.instance2 + Job = "dbatoolsci_testjob_disabled" + Category = "dbatoolsci_job_category" + Disabled = $true + } + $null = New-DbaAgentJob @splatDisabledJob + + $splatDisabledJobStep = @{ + SqlInstance = $TestConfig.instance2 + Job = "dbatoolsci_testjob_disabled" + StepId = 1 + StepName = "dbatoolsci Test Step" + Subsystem = "TransactSql" + SubsystemServer = $srvName.sn + Command = "SELECT * FROM master.sys.all_columns" + CmdExecSuccessCode = 0 + OnSuccessAction = "QuitWithSuccess" + OnFailAction = "QuitWithFailure" + Database = "master" + RetryAttempts = 1 + RetryInterval = 2 + } + $null = New-DbaAgentJobStep @splatDisabledJobStep # 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') @@ -63,65 +130,84 @@ Describe $CommandName -Tag IntegrationTests { # 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-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob, dbatoolsregr_testjob, dbatoolsci_testjob_disabled - $null = Remove-DbaAgentJobCategory -SqlInstance $TestConfig.instance2 -Category "dbatoolsci_job_category" + $splatRemoveJobs = @{ + SqlInstance = $TestConfig.instance2 + Job = @("dbatoolsci_testjob", "dbatoolsregr_testjob", "dbatoolsci_testjob_disabled") + Confirm = $false + } + $null = Remove-DbaAgentJob @splatRemoveJobs + + $null = Remove-DbaAgentJobCategory -SqlInstance $TestConfig.instance2 -Category "dbatoolsci_job_category" -Confirm $false # As this is the last block we do not need to reset the $PSDefaultParameterValues. } Context "Command finds jobs using all parameters" { + BeforeAll { + $testJobResult = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob + $excludedJobResult = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job *dbatoolsci* -ExcludeJobName dbatoolsci_testjob_disabled + $stepNameResult = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -StepName "dbatoolsci Test Step" + $lastUsedResult = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -LastUsed 10 + $disabledResult = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsDisabled + $notScheduledResult = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsNotScheduled + $notScheduledWildcardResult = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsNotScheduled -Job *dbatoolsci* + $noEmailResult = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsNoEmailNotification + $categoryResult = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Category "dbatoolsci_job_category" + $ownerResult = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Owner "sa" + $failedResult = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsFailed -Since "2016-07-01 10:47:00" + $multiWildcardResult = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job *dbatoolsci*, *dbatoolsregr* -ExcludeJobName dbatoolsci_testjob_disabled + } It "Should find a specific job" { - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob - $results.name | Should -Be "dbatoolsci_testjob" + $testJobResult.name | Should -Be "dbatoolsci_testjob" } + It "Should find a specific job but not an excluded job" { - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job *dbatoolsci* -ExcludeJobName dbatoolsci_testjob_disabled - $results.name | Should -Not -Be "dbatoolsci_testjob_disabled" + $excludedJobResult.name | Should -Not -Be "dbatoolsci_testjob_disabled" } + It "Should find a specific job with a specific step" { - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -StepName "dbatoolsci Test Step" - $results.name | Should -Be "dbatoolsci_testjob_disabled" + $stepNameResult.name | Should -Be "dbatoolsci_testjob_disabled" } + It "Should find jobs not used in the last 10 days" { - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -LastUsed 10 - $results | Should -Not -BeNullOrEmpty + $lastUsedResult | Should -Not -BeNullOrEmpty } + It "Should find jobs disabled from running" { - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsDisabled - $results.name | Should -Be "dbatoolsci_testjob_disabled" + $disabledResult.name | Should -Be "dbatoolsci_testjob_disabled" } + It "Should find 1 job disabled from running" { - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsDisabled - @($results).Count | Should -Be 1 + $disabledResult.Status.Count | Should -Be 1 } + It "Should find jobs that have not been scheduled" { - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsNotScheduled - $results | Should -Not -BeNullOrEmpty + $notScheduledResult | Should -Not -BeNullOrEmpty } + It "Should find 2 jobs that have no schedule" { - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsNotScheduled -Job *dbatoolsci* - @($results).Count | Should -Be 2 + $notScheduledWildcardResult.Status.Count | Should -Be 2 } + It "Should find jobs that have no email notification" { - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsNoEmailNotification - $results | Should -Not -BeNullOrEmpty + $noEmailResult | Should -Not -BeNullOrEmpty } + It "Should find jobs that have a category of dbatoolsci_job_category" { - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Category "dbatoolsci_job_category" - $results.name | Should -Be "dbatoolsci_testjob_disabled" + $categoryResult.name | Should -Be "dbatoolsci_testjob_disabled" } + It "Should find jobs that are owned by sa" { - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Owner "sa" - $results | Should -Not -BeNullOrEmpty + $ownerResult | Should -Not -BeNullOrEmpty } + It "Should find jobs that have been failed since July of 2016" { - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsFailed -Since "2016-07-01 10:47:00" - $results | Should -Not -BeNullOrEmpty + $failedResult | Should -Not -BeNullOrEmpty } + It "Should work with multiple wildcard passed in (see #9572)" { - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job *dbatoolsci*, *dbatoolsregr* -ExcludeJobName dbatoolsci_testjob_disabled - @($results).Count | Should -Be 2 + $multiWildcardResult.Status.Count | Should -Be 2 } } } \ No newline at end of file diff --git a/tests/Find-DbaOrphanedFile.Tests.ps1 b/tests/Find-DbaOrphanedFile.Tests.ps1 index 1143f404fdde..0a10782fa751 100644 --- a/tests/Find-DbaOrphanedFile.Tests.ps1 +++ b/tests/Find-DbaOrphanedFile.Tests.ps1 @@ -1,6 +1,6 @@ #Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } param( - $ModuleName = "dbatools", + $ModuleName = "dbatools", $CommandName = "Find-DbaOrphanedFile", $PSDefaultParameterValues = $TestConfig.Defaults ) @@ -9,7 +9,7 @@ Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig Describe $CommandName -Tag UnitTests { - Context "Parameter validation" { + Context "Validate parameters" { BeforeAll { $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } $expectedParameters = $TestConfig.CommonParameters @@ -37,134 +37,108 @@ Describe $CommandName -Tag IntegrationTests { # 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 orphaned file detection, we need databases that can be detached to create orphaned files, - # and backup files to test recursive searching and file type filtering. - - # Set variables. They are available in all the It blocks. - $dbname = "dbatoolsci_orphanedfile_$(Get-Random)" - $dbname2 = "dbatoolsci_orphanedfile_$(Get-Random)" - $tmpdir = "c:\temp\orphan_$(Get-Random)" - $tmpdirInner = Join-Path $tmpdir "inner" - $tmpBackupPath = Join-Path $tmpdirInner "backup" - $tmpdir2 = "c:\temp\orphan_$(Get-Random)" - $tmpdirInner2 = Join-Path $tmpdir2 "inner" - $tmpBackupPath2 = Join-Path $tmpdirInner2 "backup" - - # Create the objects. + # Set up test databases + $dbname = "dbatoolsci_orphanedfile_$(Get-Random)" $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 $db1 = New-DbaDatabase -SqlInstance $server -Name $dbname + + $dbname2 = "dbatoolsci_orphanedfile_$(Get-Random)" $db2 = New-DbaDatabase -SqlInstance $server -Name $dbname2 + # Create test directories + $tmpdir = "c:\temp\orphan_$(Get-Random)" if (-not(Test-Path $tmpdir)) { - $null = New-Item -Path $tmpdir -ItemType Container + $null = New-Item -Path $tmpdir -Type Container } - $null = New-Item -Path $tmpdirInner -ItemType Container - $null = New-Item -Path $tmpBackupPath -ItemType Container + $tmpdirInner = Join-Path $tmpdir "inner" + $null = New-Item -Path $tmpdirInner -Type Container + $tmpBackupPath = Join-Path $tmpdirInner "backup" + $null = New-Item -Path $tmpBackupPath -Type Container + $tmpdir2 = "c:\temp\orphan_$(Get-Random)" if (-not(Test-Path $tmpdir2)) { - $null = New-Item -Path $tmpdir2 -ItemType Container + $null = New-Item -Path $tmpdir2 -Type Container } - $null = New-Item -Path $tmpdirInner2 -ItemType Container - $null = New-Item -Path $tmpBackupPath2 -ItemType Container + $tmpdirInner2 = Join-Path $tmpdir2 "inner" + $null = New-Item -Path $tmpdirInner2 -Type Container + $tmpBackupPath2 = Join-Path $tmpdirInner2 "backup" + $null = New-Item -Path $tmpBackupPath2 -Type Container + # Verify setup $result = Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname if ($result.Count -eq 0) { - throw "Setup failed - database $dbname was not created" + throw "Test setup failed - database not created" } + # Create backups $backupFile = Backup-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname -Path $tmpBackupPath -Type Full $backupFile2 = Backup-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname2 -Path $tmpBackupPath2 -Type Full Copy-Item -Path $backupFile.BackupPath -Destination "C:\" -Confirm:$false $tmpBackupPath3 = Join-Path (Get-SqlDefaultPaths $server data) "dbatoolsci_$(Get-Random)" - $null = New-Item -Path $tmpBackupPath3 -ItemType Container + $null = New-Item -Path $tmpBackupPath3 -Type Container # 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 - # Cleanup all created objects. - Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname, $dbname2 -ErrorAction SilentlyContinue | Remove-DbaDatabase -Confirm:$false + # Cleanup all created objects + 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 - # 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 "Has the correct properties" { - $null = Detach-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname -Force - $results = @(Find-DbaOrphanedFile -SqlInstance $TestConfig.instance2) - $ExpectedStdProps = @( - "ComputerName", - "InstanceName", - "SqlInstance", - "Filename", - "RemoteFilename" - ) + $null = Dismount-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname -Force + $results = Find-DbaOrphanedFile -SqlInstance $TestConfig.instance2 + $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" - ) + $ExpectedProps = "ComputerName,InstanceName,SqlInstance,Filename,RemoteFilename,Server".Split(",") ($results[0].PsObject.Properties.Name | Sort-Object) | Should -Be ($ExpectedProps | Sort-Object) } + It "Finds two files" { - $results = @(Find-DbaOrphanedFile -SqlInstance $TestConfig.instance2) - $results.Status.Count | Should -Be 2 + $results = Find-DbaOrphanedFile -SqlInstance $TestConfig.instance2 + @($results.Filename).Count | Should -Be 2 } It "Finds zero files after cleaning up" { - $results = @(Find-DbaOrphanedFile -SqlInstance $TestConfig.instance2) + $results = Find-DbaOrphanedFile -SqlInstance $TestConfig.instance2 $results.FileName | Remove-Item - $results = @(Find-DbaOrphanedFile -SqlInstance $TestConfig.instance2) - $results.Status.Count | Should -Be 0 + $results = Find-DbaOrphanedFile -SqlInstance $TestConfig.instance2 + @($results.Filename).Count | Should -Be 0 } - It "works with -Recurse" { "a" | Out-File (Join-Path $tmpdir "out.mdf") - $results = @(Find-DbaOrphanedFile -SqlInstance $TestConfig.instance2 -Path $tmpdir) - $results.Status.Count | Should -Be 1 + $results = Find-DbaOrphanedFile -SqlInstance $TestConfig.instance2 -Path $tmpdir + @($results.Filename).Count | Should -Be 1 Move-Item "$tmpdir\out.mdf" -Destination $tmpdirInner - $results = @(Find-DbaOrphanedFile -SqlInstance $TestConfig.instance2 -Path $tmpdir) - $results.Status.Count | Should -Be 0 - $results = @(Find-DbaOrphanedFile -SqlInstance $TestConfig.instance2 -Path $tmpdir -Recurse) - $results.Status.Count | Should -Be 1 + $results = Find-DbaOrphanedFile -SqlInstance $TestConfig.instance2 -Path $tmpdir + @($results.Filename).Count | Should -Be 0 + $results = Find-DbaOrphanedFile -SqlInstance $TestConfig.instance2 -Path $tmpdir -Recurse + @($results.Filename).Count | Should -Be 1 Copy-Item -Path "$tmpdirInner\out.mdf" -Destination $tmpBackupPath3 -Confirm:$false - $results = @(Find-DbaOrphanedFile -SqlInstance $TestConfig.instance2 -Path $tmpdir, $tmpdir2 -Recurse -FileType bak) + $results = Find-DbaOrphanedFile -SqlInstance $TestConfig.instance2 -Path $tmpdir, $tmpdir2 -Recurse -FileType bak $results.Filename | Should -Contain $backupFile.BackupPath $results.Filename | Should -Contain $backupFile2.BackupPath $results.Filename | Should -Contain "$tmpdirInner\out.mdf" $results.Filename | Should -Contain "$tmpBackupPath3\out.mdf" - $results.Count | Should -Be 4 + @($results).Count | Should -Be 4 - $results = @(Find-DbaOrphanedFile -SqlInstance $TestConfig.instance2 -Recurse) + $results = Find-DbaOrphanedFile -SqlInstance $TestConfig.instance2 -Recurse $results.Filename | Should -Be "$tmpBackupPath3\out.mdf" } - It "works with -Path" { - $results = @(Find-DbaOrphanedFile -SqlInstance $TestConfig.instance2 -Path "C:" -FileType bak) + $results = Find-DbaOrphanedFile -SqlInstance $TestConfig.instance2 -Path "C:" -FileType bak $results.Filename | Should -Contain "C:\$($backupFile.BackupFile)" } } diff --git a/tests/Format-DbaBackupInformation.Tests.ps1 b/tests/Format-DbaBackupInformation.Tests.ps1 index 606fc80bb11b..466af0d361ab 100644 --- a/tests/Format-DbaBackupInformation.Tests.ps1 +++ b/tests/Format-DbaBackupInformation.Tests.ps1 @@ -1,13 +1,10 @@ #Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } param( - $ModuleName = "dbatools", + $ModuleName = "dbatools", $CommandName = "Format-DbaBackupInformation", $PSDefaultParameterValues = $TestConfig.Defaults ) -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig - Describe $CommandName -Tag UnitTests { Context "Parameter validation" { BeforeAll { @@ -38,10 +35,11 @@ Describe $CommandName -Tag UnitTests { } Describe $CommandName -Tag IntegrationTests { + Context "Rename a Database" { BeforeAll { - $History = Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\ContinuePointTest.xml - $output = $History | Format-DbaBackupInformation -ReplaceDatabaseName "Pester" + $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" { @@ -55,8 +53,8 @@ Describe $CommandName -Tag IntegrationTests { Context "Test it works as a parameter as well" { BeforeAll { - $History = Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\ContinuePointTest.xml - $output = Format-DbaBackupInformation -BackupHistory $History -ReplaceDatabaseName "Pester" + $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" { @@ -64,19 +62,22 @@ Describe $CommandName -Tag IntegrationTests { } It "Should have renamed datafiles as well" { - ($output | Select-Object -ExpandProperty filelist | Where-Object { $PSItem.PhysicalName -like "*ContinuePointTest*" }).Count | Should -BeExactly 0 + ($output | Select-Object -ExpandProperty filelist | Where-Object { $PSItem.PhysicalName -like "ContinuePointTest" }).Count | Should -BeExactly 0 } } Context "Rename 2 dbs using a hash" { BeforeAll { - $History = Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\ContinuePointTest.xml - $History += Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\RestoreTimeClean.xml - $splatFormat = @{ - BackupHistory = $History - ReplaceDatabaseName = @{"ContinuePointTest" = "Spiggy"; "RestoreTimeClean" = "Eldritch" } + $history = Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\ContinuePointTest.xml + $history += Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\RestoreTimeClean.xml + $splatReplaceName = @{ + BackupHistory = $history + ReplaceDatabaseName = @{ + "ContinuePointTest" = "Spiggy" + "RestoreTimeClean" = "Eldritch" + } } - $output = Format-DbaBackupInformation @splatFormat + $output = Format-DbaBackupInformation @splatReplaceName } It "Should have no databases other than spiggy and eldritch" { @@ -84,33 +85,39 @@ Describe $CommandName -Tag IntegrationTests { } It "Should have renamed all RestoreTimeCleans to Eldritch" { - ($output | Where-Object { $PSItem.OriginalDatabase -eq "RestoreTimeClean" } | Where-Object { $PSItem.Database -ne "Eldritch" }).Count | Should -BeExactly 0 + $restoreTimeResults = $output | Where-Object { $PSItem.OriginalDatabase -eq "RestoreTimeClean" } + ($restoreTimeResults | Where-Object { $PSItem.Database -ne "Eldritch" }).Count | Should -BeExactly 0 } It "Should have renamed all the RestoreTimeClean files to Eldritch" { - ($output | Where-Object { $PSItem.OriginalDatabase -eq "RestoreTimeClean" } | Select-Object -ExpandProperty filelist | Where-Object { $PSItem.PhysicalName -like "*RestoreTimeClean*" }).Count | Should -BeExactly 0 - ($output | Where-Object { $PSItem.OriginalDatabase -eq "RestoreTimeClean" } | Select-Object -ExpandProperty filelist | Where-Object { $PSItem.PhysicalName -like "*eldritch*" }).Count | Should -BeExactly ($output | Where-Object { $PSItem.OriginalDatabase -eq "RestoreTimeClean" } | Select-Object -ExpandProperty filelist).Count + $restoreTimeResults = $output | Where-Object { $PSItem.OriginalDatabase -eq "RestoreTimeClean" } + $restoreTimeFileList = $restoreTimeResults | Select-Object -ExpandProperty filelist + ($restoreTimeFileList | Where-Object { $PSItem.PhysicalName -like "RestoreTimeClean" }).Count | Should -BeExactly 0 + ($restoreTimeFileList | Where-Object { $PSItem.PhysicalName -like "eldritch" }).Count | Should -BeExactly $restoreTimeFileList.Count } It "Should have renamed all ContinuePointTest to Spiggy" { - ($output | Where-Object { $PSItem.OriginalDatabase -eq "ContinuePointTest" } | Where-Object { $PSItem.Database -ne "Spiggy" }).Count | Should -BeExactly 0 + $continuePointResults = $output | Where-Object { $PSItem.OriginalDatabase -eq "ContinuePointTest" } + ($continuePointResults | Where-Object { $PSItem.Database -ne "Spiggy" }).Count | Should -BeExactly 0 } It "Should have renamed all the ContinuePointTest files to Spiggy" { - ($output | Where-Object { $PSItem.OriginalDatabase -eq "ContinuePointTest" } | Select-Object -ExpandProperty filelist | Where-Object { $PSItem.PhysicalName -like "*ContinuePointTest*" }).Count | Should -BeExactly 0 - ($output | Where-Object { $PSItem.OriginalDatabase -eq "ContinuePointTest" } | Select-Object -ExpandProperty filelist | Where-Object { $PSItem.PhysicalName -like "*spiggy*" }).Count | Should -BeExactly ($output | Where-Object { $PSItem.OriginalDatabase -eq "ContinuePointTest" } | Select-Object -ExpandProperty filelist).Count + $continuePointResults = $output | Where-Object { $PSItem.OriginalDatabase -eq "ContinuePointTest" } + $continuePointFileList = $continuePointResults | Select-Object -ExpandProperty filelist + ($continuePointFileList | Where-Object { $PSItem.PhysicalName -like "ContinuePointTest" }).Count | Should -BeExactly 0 + ($continuePointFileList | Where-Object { $PSItem.PhysicalName -like "spiggy" }).Count | Should -BeExactly $continuePointFileList.Count } } Context "Rename 1 dbs using a hash" { BeforeAll { - $History = Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\ContinuePointTest.xml - $History += Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\RestoreTimeClean.xml - $splatRename = @{ - BackupHistory = $History - ReplaceDatabaseName = @{"ContinuePointTest" = "Alice" } + $history = Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\ContinuePointTest.xml + $history += Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\RestoreTimeClean.xml + $splatSingleRename = @{ + BackupHistory = $history + ReplaceDatabaseName = @{ "ContinuePointTest" = "Alice" } } - $output = Format-DbaBackupInformation @splatRename + $output = Format-DbaBackupInformation @splatSingleRename } It "Should have no databases other than RestoreTimeClean and Alice" { @@ -118,23 +125,27 @@ Describe $CommandName -Tag IntegrationTests { } It "Should have left RestoreTimeClean alone" { - ($output | Where-Object { $PSItem.OriginalDatabase -eq "RestoreTimeClean" } | Where-Object { $PSItem.Database -ne "RestoreTimeClean" }).Count | Should -BeExactly 0 + $restoreTimeResults = $output | Where-Object { $PSItem.OriginalDatabase -eq "RestoreTimeClean" } + ($restoreTimeResults | Where-Object { $PSItem.Database -ne "RestoreTimeClean" }).Count | Should -BeExactly 0 } It "Should have renamed all ContinuePointTest to Alice" { - ($output | Where-Object { $PSItem.OriginalDatabase -eq "ContinuePointTest" } | Where-Object { $PSItem.Database -ne "Alice" }).Count | Should -BeExactly 0 + $continuePointResults = $output | Where-Object { $PSItem.OriginalDatabase -eq "ContinuePointTest" } + ($continuePointResults | Where-Object { $PSItem.Database -ne "Alice" }).Count | Should -BeExactly 0 } It "Should have renamed all the ContinuePointTest files to Alice" { - ($output | Where-Object { $PSItem.OriginalDatabase -eq "ContinuePointTest" } | Select-Object -ExpandProperty filelist | Where-Object { $PSItem.PhysicalName -like "*ContinuePointTest*" }).Count | Should -BeExactly 0 - ($output | Where-Object { $PSItem.OriginalDatabase -eq "ContinuePointTest" } | Select-Object -ExpandProperty filelist | Where-Object { $PSItem.PhysicalName -like "*alice*" }).Count | Should -BeExactly ($output | Where-Object { $PSItem.OriginalDatabase -eq "ContinuePointTest" } | Select-Object -ExpandProperty filelist).Count + $continuePointResults = $output | Where-Object { $PSItem.OriginalDatabase -eq "ContinuePointTest" } + $continuePointFileList = $continuePointResults | Select-Object -ExpandProperty filelist + ($continuePointFileList | Where-Object { $PSItem.PhysicalName -like "ContinuePointTest" }).Count | Should -BeExactly 0 + ($continuePointFileList | Where-Object { $PSItem.PhysicalName -like "alice" }).Count | Should -BeExactly $continuePointFileList.Count } } Context "Check DB Name prefix and suffix" { BeforeAll { - $History = Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\ContinuePointTest.xml - $output = $History | Format-DbaBackupInformation -DatabaseNamePrefix PREFIX + $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" { @@ -144,111 +155,121 @@ Describe $CommandName -Tag IntegrationTests { Context "Check DataFileDirectory moves all files" { BeforeAll { - $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 -DataFileDirectory c:\restores + $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 -DataFileDirectory "c:\restores" } It "Should have move ALL files to c:\restores\" { - (($output | Select-Object -ExpandProperty Filelist).PhysicalName | Split-Path | Where-Object { $PSItem -ne "c:\restores" }).Count | Should -BeExactly 0 + $allFiles = $output | Select-Object -ExpandProperty Filelist + ($allFiles.PhysicalName | Split-Path | Where-Object { $PSItem -ne "c:\restores" }).Count | Should -BeExactly 0 } } Context "Check DataFileDirectory and LogFileDirectory work independently" { BeforeAll { - $History = Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\ContinuePointTest.xml - $History += Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\RestoreTimeClean.xml + $history = Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\ContinuePointTest.xml + $history += Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\RestoreTimeClean.xml $splatDirectories = @{ - BackupHistory = $History + BackupHistory = $history DataFileDirectory = "c:\restores\" LogFileDirectory = "c:\logs" } $output = Format-DbaBackupInformation @splatDirectories } - It "Should have moved all data files to c:\restores\" { - (($output | Select-Object -ExpandProperty Filelist | Where-Object { $PSItem.Type -eq "D" }).PhysicalName | Split-Path | Where-Object { $PSItem -ne "c:\restores" }).Count | Should -BeExactly 0 + It "Should have moved all data files to c:\restores\" { + $dataFiles = $output | Select-Object -ExpandProperty Filelist | Where-Object { $PSItem.Type -eq "D" } + ($dataFiles.PhysicalName | Split-Path | Where-Object { $PSItem -ne "c:\restores" }).Count | Should -BeExactly 0 } It "Should have moved all log files to c:\logs\" { - (($output | Select-Object -ExpandProperty Filelist | Where-Object { $PSItem.Type -eq "L" }).PhysicalName | Split-Path | Where-Object { $PSItem -ne "c:\logs" }).Count | Should -BeExactly 0 + $logFiles = $output | Select-Object -ExpandProperty Filelist | Where-Object { $PSItem.Type -eq "L" } + ($logFiles.PhysicalName | Split-Path | Where-Object { $PSItem -ne "c:\logs" }).Count | Should -BeExactly 0 } } Context "Check LogFileDirectory works for just logfiles" { BeforeAll { - $History = Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\ContinuePointTest.xml - $History += Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\RestoreTimeClean.xml - $splatLogFiles = @{ - BackupHistory = $History + $history = Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\ContinuePointTest.xml + $history += Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\RestoreTimeClean.xml + $splatLogDirectory = @{ + BackupHistory = $history DataFileDirectory = "c:\restores\" LogFileDirectory = "c:\logs" } - $output = Format-DbaBackupInformation @splatLogFiles + $output = Format-DbaBackupInformation @splatLogDirectory } - It "Should not have moved all data files to c:\logs\" { - (($output | Select-Object -ExpandProperty Filelist | Where-Object { $PSItem.Type -eq "D" }).PhysicalName | Split-Path | Where-Object { $PSItem -eq "c:\logs" }).Count | Should -BeExactly 0 + It "Should not have moved data files to c:\logs\" { + $dataFiles = $output | Select-Object -ExpandProperty Filelist | Where-Object { $PSItem.Type -eq "D" } + ($dataFiles.PhysicalName | Split-Path | Where-Object { $PSItem -eq "c:\logs" }).Count | Should -BeExactly 0 } It "Should have moved all log files to c:\logs\" { - (($output | Select-Object -ExpandProperty Filelist | Where-Object { $PSItem.Type -eq "L" }).PhysicalName | Split-Path | Where-Object { $PSItem -ne "c:\logs" }).Count | Should -BeExactly 0 + $logFiles = $output | Select-Object -ExpandProperty Filelist | Where-Object { $PSItem.Type -eq "L" } + ($logFiles.PhysicalName | Split-Path | Where-Object { $PSItem -ne "c:\logs" }).Count | Should -BeExactly 0 } } Context "Test RebaseBackupFolder" { BeforeAll { - $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 -RebaseBackupFolder c:\backups\ + $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 -RebaseBackupFolder "c:\backups\" } It "Should have moved all backup files to c:\backups" { - ($output | Select-Object -ExpandProperty FullName | Split-Path | Where-Object { $PSItem -eq "c:\backups" }).Count | Should -BeExactly $History.Count + ($output | Select-Object -ExpandProperty FullName | Split-Path | Where-Object { $PSItem -eq "c:\backups" }).Count | Should -BeExactly $history.Count } } Context "Test PathSep" { BeforeAll { - $History = Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\ContinuePointTest.xml - $History += Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\RestoreTimeClean.xml - $outputDefault = Format-DbaBackupInformation -BackupHistory $History -RebaseBackupFolder "c:\backups" - $outputExplicit = Format-DbaBackupInformation -BackupHistory $History -RebaseBackupFolder "c:\backups" -PathSep "\" - $splatLinux = @{ - BackupHistory = $History - RebaseBackupFolder = "/opt/mssql/backups" - PathSep = "/" - } - $outputLinux = Format-DbaBackupInformation @splatLinux + $history = Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\ContinuePointTest.xml + $history += Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\RestoreTimeClean.xml } It "Should not have changed the default path separator" { - ($outputDefault | Select-Object -ExpandProperty FullName | Split-Path | Where-Object { $PSItem -eq "c:\backups" }).Count | Should -BeExactly $History.Count + $output = Format-DbaBackupInformation -BackupHistory $history -RebaseBackupFolder "c:\backups" + ($output | Select-Object -ExpandProperty FullName | Split-Path | Where-Object { $PSItem -eq "c:\backups" }).Count | Should -BeExactly $history.Count } It "Should not have changed the default path separator even when passed explicitly" { - ($outputExplicit | Select-Object -ExpandProperty FullName | Split-Path | Where-Object { $PSItem -eq "c:\backups" }).Count | Should -BeExactly $History.Count + $splatDefaultSep = @{ + BackupHistory = $history + RebaseBackupFolder = "c:\backups" + PathSep = "\" + } + $output = Format-DbaBackupInformation @splatDefaultSep + ($output | Select-Object -ExpandProperty FullName | Split-Path | Where-Object { $PSItem -eq "c:\backups" }).Count | Should -BeExactly $history.Count } It "Should have changed the path separator as instructed" { - $result = $outputLinux | Select-Object -ExpandProperty FullName | ForEach-Object { + $splatLinuxSep = @{ + BackupHistory = $history + RebaseBackupFolder = "/opt/mssql/backups" + PathSep = "/" + } + $output = Format-DbaBackupInformation @splatLinuxSep + $result = $output | Select-Object -ExpandProperty FullName | ForEach-Object { $all = $PSItem.Split("/") $all[0..($all.Length - 2)] -Join "/" } - ($result | Where-Object { $PSItem -eq "/opt/mssql/backups" }).Count | Should -BeExactly $History.Count + ($result | Where-Object { $PSItem -eq "/opt/mssql/backups" }).Count | Should -BeExactly $history.Count } } Context "Test everything all at once" { BeforeAll { - $History = Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\ContinuePointTest.xml + $history = Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\ContinuePointTest.xml $splatEverything = @{ ReplaceDatabaseName = "Pester" DataFileDirectory = "c:\restores" LogFileDirectory = "c:\logs\" RebaseBackupFolder = "c:\backups\" } - $output = $History | Format-DbaBackupInformation @splatEverything + $output = $history | Format-DbaBackupInformation @splatEverything } It "Should have a database name of Pester" { @@ -260,15 +281,17 @@ Describe $CommandName -Tag IntegrationTests { } It "Should have moved all data files to c:\restores\" { - (($output | Select-Object -ExpandProperty Filelist | Where-Object { $PSItem.Type -eq "D" }).PhysicalName | Split-Path | Where-Object { $PSItem -ne "c:\restores" }).Count | Should -BeExactly 0 + $dataFiles = $output | Select-Object -ExpandProperty Filelist | Where-Object { $PSItem.Type -eq "D" } + ($dataFiles.PhysicalName | Split-Path | Where-Object { $PSItem -ne "c:\restores" }).Count | Should -BeExactly 0 } It "Should have moved all log files to c:\logs\" { - (($output | Select-Object -ExpandProperty Filelist | Where-Object { $PSItem.Type -eq "L" }).PhysicalName | Split-Path | Where-Object { $PSItem -ne "c:\logs" }).Count | Should -BeExactly 0 + $logFiles = $output | Select-Object -ExpandProperty Filelist | Where-Object { $PSItem.Type -eq "L" } + ($logFiles.PhysicalName | Split-Path | Where-Object { $PSItem -ne "c:\logs" }).Count | Should -BeExactly 0 } It "Should have moved all backup files to c:\backups" { - ($output | Select-Object -ExpandProperty FullName | Split-Path | Where-Object { $PSItem -eq "c:\backups" }).Count | Should -BeExactly $History.Count + ($output | Select-Object -ExpandProperty FullName | Split-Path | Where-Object { $PSItem -eq "c:\backups" }).Count | Should -BeExactly $history.Count } } } \ No newline at end of file diff --git a/tests/Get-DbaAgentJobHistory.Tests.ps1 b/tests/Get-DbaAgentJobHistory.Tests.ps1 index 612c5669b25a..f9b2cad73f3d 100644 --- a/tests/Get-DbaAgentJobHistory.Tests.ps1 +++ b/tests/Get-DbaAgentJobHistory.Tests.ps1 @@ -1,6 +1,6 @@ #Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } param( - $ModuleName = "dbatools", + $ModuleName = "dbatools", $CommandName = "Get-DbaAgentJobHistory", $PSDefaultParameterValues = $TestConfig.Defaults ) @@ -35,9 +35,9 @@ Describe $CommandName -Tag UnitTests { } -Describe "$CommandName Unittests" -Tag UnitTests { +Describe $CommandName -Tag UnitTests { BeforeAll { - InModuleScope "dbatools" { + InModuleScope dbatools { Mock Connect-DbaInstance -MockWith { # Thanks @Fred $obj = [PSCustomObject]@{ @@ -51,7 +51,7 @@ Describe "$CommandName Unittests" -Tag UnitTests { JobServer = New-Object PSObject ConnectionContext = New-Object PSObject } - Add-Member -InputObject $obj.ConnectionContext -Name ConnectionString -MemberType NoteProperty -Value "put=an=equal=in=it" + Add-Member -InputObject $obj.ConnectionContext -Name ConnectionString -MemberType NoteProperty -Value "put=an=equal=in=it" Add-Member -InputObject $obj.JobServer -Name EnumJobHistory -MemberType ScriptMethod -Value { param ($filter) return @( @@ -120,7 +120,7 @@ Describe "$CommandName Unittests" -Tag UnitTests { Context "Return values" { BeforeAll { - InModuleScope "dbatools" { + InModuleScope dbatools { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ @@ -144,29 +144,29 @@ Describe "$CommandName Unittests" -Tag UnitTests { } It "Throws when ExcludeJobSteps and WithOutputFile" { - InModuleScope "dbatools" { + InModuleScope dbatools { { Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -ExcludeJobSteps -WithOutputFile -EnableException } | Should -Throw } } It "Returns full history by default" { - InModuleScope "dbatools" { + InModuleScope dbatools { $Results = @() $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" - $Results.Count | Should -BeExactly 6 + $Results.Status.Count | Should -Be 6 } } It "Returns only runs with no steps with ExcludeJobSteps" { - InModuleScope "dbatools" { + InModuleScope dbatools { $Results = @() $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -ExcludeJobSteps - $Results.Count | Should -BeExactly 2 + $Results.Status.Count | Should -Be 2 } } It "Returns our own 'augmented' properties, too" { - InModuleScope "dbatools" { + InModuleScope dbatools { $Results = @() $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -ExcludeJobSteps $Results[0].psobject.properties.Name | Should -Contain "StartDate" @@ -176,25 +176,25 @@ Describe "$CommandName Unittests" -Tag UnitTests { } It "Returns 'augmented' properties that are correct" { - InModuleScope "dbatools" { + InModuleScope dbatools { $Results = @() $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -ExcludeJobSteps $Results[0].StartDate | Should -Be $Results[0].RunDate - $Results[0].RunDuration | Should -BeExactly 112 - $Results[0].Duration.TotalSeconds | Should -BeExactly 72 + $Results[0].RunDuration | Should -Be 112 + $Results[0].Duration.TotalSeconds | Should -Be 72 $Results[0].EndDate | Should -Be ($Results[0].StartDate.AddSeconds($Results[0].Duration.TotalSeconds)) } } It "Figures out plain outputfiles" { - InModuleScope "dbatools" { + InModuleScope dbatools { $Results = @() $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile # no output for outcomes - ($Results | Where-Object StepID -eq 0).Count | Should -BeExactly 2 + ($Results | Where-Object StepID -eq 0).Status.Count | Should -Be 2 ($Results | Where-Object StepID -eq 0).OutputFileName -Join "" | Should -Be "" # correct output for job1 - ($Results | Where-Object StepID -ne 0 | Where-Object JobName -eq "Job1").OutputFileName | Should -Match "Job1Output[12]" + ($Results | Where-Object { $PSItem.StepID -ne 0 } | Where-Object JobName -eq "Job1").OutputFileName | Should -Match "Job1Output[12]" # correct output for job2 ($Results | Where-Object StepID -eq 2 | Where-Object JobName -eq "Job2").OutputFileName | Should -Match "Job2Output1" ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job2").OutputFileName | Should -Be "" @@ -204,7 +204,7 @@ Describe "$CommandName Unittests" -Tag UnitTests { Context "SQL Agent Tokens" { It "Handles INST" { - InModuleScope "dbatools" { + InModuleScope dbatools { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ @@ -222,7 +222,7 @@ Describe "$CommandName Unittests" -Tag UnitTests { } It "Handles MACH" { - InModuleScope "dbatools" { + InModuleScope dbatools { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ @@ -240,7 +240,7 @@ Describe "$CommandName Unittests" -Tag UnitTests { } It "Handles SQLDIR" { - InModuleScope "dbatools" { + InModuleScope dbatools { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ @@ -258,7 +258,7 @@ Describe "$CommandName Unittests" -Tag UnitTests { } It "Handles SQLLOGDIR" { - InModuleScope "dbatools" { + InModuleScope dbatools { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ @@ -276,7 +276,7 @@ Describe "$CommandName Unittests" -Tag UnitTests { } It "Handles SRVR" { - InModuleScope "dbatools" { + InModuleScope dbatools { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ @@ -294,7 +294,7 @@ Describe "$CommandName Unittests" -Tag UnitTests { } It "Handles STEPID" { - InModuleScope "dbatools" { + InModuleScope dbatools { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ @@ -311,7 +311,7 @@ Describe "$CommandName Unittests" -Tag UnitTests { } It "Handles JOBID" { - InModuleScope "dbatools" { + InModuleScope dbatools { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ @@ -329,7 +329,7 @@ Describe "$CommandName Unittests" -Tag UnitTests { } It "Handles STRTDT" { - InModuleScope "dbatools" { + InModuleScope dbatools { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ @@ -346,7 +346,7 @@ Describe "$CommandName Unittests" -Tag UnitTests { } It "Handles STRTTM" { - InModuleScope "dbatools" { + InModuleScope dbatools { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ @@ -363,7 +363,7 @@ Describe "$CommandName Unittests" -Tag UnitTests { } It "Handles DATE" { - InModuleScope "dbatools" { + InModuleScope dbatools { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ @@ -380,7 +380,7 @@ Describe "$CommandName Unittests" -Tag UnitTests { } It "Handles TIME" { - InModuleScope "dbatools" { + InModuleScope dbatools { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ @@ -399,7 +399,7 @@ Describe "$CommandName Unittests" -Tag UnitTests { Context "SQL Agent escape sequences" { It "Handles ESCAPE_NONE" { - InModuleScope "dbatools" { + InModuleScope dbatools { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ @@ -417,7 +417,7 @@ Describe "$CommandName Unittests" -Tag UnitTests { } It "Handles ESCAPE_SQUOTE" { - InModuleScope "dbatools" { + InModuleScope dbatools { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ @@ -430,12 +430,12 @@ Describe "$CommandName Unittests" -Tag UnitTests { $Results = @() $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile - ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "BASEErrorLog_''''_""_]_Path__Job1Output1" + ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "BASEErrorLog_''_""_]_Path__Job1Output1" } } It "Handles ESCAPE_DQUOTE" { - InModuleScope "dbatools" { + InModuleScope dbatools { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ @@ -453,7 +453,7 @@ Describe "$CommandName Unittests" -Tag UnitTests { } It "Handles ESCAPE_RBRACKET" { - InModuleScope "dbatools" { + InModuleScope dbatools { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ diff --git a/tests/Get-DbaAgentJobOutputFile.Tests.ps1 b/tests/Get-DbaAgentJobOutputFile.Tests.ps1 index 37a0d89025d7..6276f1ec1cfe 100644 --- a/tests/Get-DbaAgentJobOutputFile.Tests.ps1 +++ b/tests/Get-DbaAgentJobOutputFile.Tests.ps1 @@ -1,12 +1,15 @@ #Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } param( - $ModuleName = "dbatools", + $ModuleName = "dbatools", $CommandName = "Get-DbaAgentJobOutputFile", $PSDefaultParameterValues = $TestConfig.Defaults ) +Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan +$global:TestConfig = Get-TestConfig + Describe $CommandName -Tag UnitTests { - Context "Parameter validation" { + Context "Validate parameters" { BeforeAll { $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } $expectedParameters = $TestConfig.CommonParameters @@ -23,90 +26,106 @@ Describe $CommandName -Tag UnitTests { Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } +} +Describe $CommandName -Tag UnitTests { Context "Return values" { BeforeAll { - 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 + 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" { - $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]" + InModuleScope "dbatools" { + $Results = @() + $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" { - $results = @(Get-DbaAgentJobOutputFile -SqlInstance "SQLServerName" -Job "Job1") - $results.Job | Should -Match "Job1" - $results.JobStep | Should -Match "Job1Step[12]" - $results.OutputFileName | Should -Match "Job1Output[12]" + 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]" + } } It "Honors the ExcludeJob parameter" { - $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 + InModuleScope "dbatools" { + $Results = @() + $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" { - $results = @(Get-DbaAgentJobOutputFile -SqlInstance "SQLServerName" -Job "Job3") - $results.Count | Should -BeExactly 0 + InModuleScope "dbatools" { + $Results = @() + $Results += Get-DbaAgentJobOutputFile -SqlInstance "SQLServerName" -Job "Job3" + $Results.Count | Should -BeExactly 0 + } } } } \ No newline at end of file diff --git a/tests/Get-DbaAgentLog.Tests.ps1 b/tests/Get-DbaAgentLog.Tests.ps1 index da812b7dc8ef..3702dc9afb6a 100644 --- a/tests/Get-DbaAgentLog.Tests.ps1 +++ b/tests/Get-DbaAgentLog.Tests.ps1 @@ -1,6 +1,6 @@ #Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } param( - $ModuleName = "dbatools", + $ModuleName = "dbatools", $CommandName = "Get-DbaAgentLog", $PSDefaultParameterValues = $TestConfig.Defaults ) @@ -28,35 +28,31 @@ Describe $CommandName -Tag 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 - - # Get the agent log for testing - $agentLogResults = Get-DbaAgentLog -SqlInstance $TestConfig.instance2 - $currentLogResults = Get-DbaAgentLog -SqlInstance $TestConfig.instance2 -LogNumber 0 - - # 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') - } - Context "Command gets agent log" { + BeforeAll { + $results = Get-DbaAgentLog -SqlInstance $TestConfig.instance2 + } + It "Results are not empty" { - $agentLogResults | Should -Not -BeNullOrEmpty + $results | Should -Not -BeNullOrEmpty } It "Results contain SQLServerAgent version" { - $agentLogResults.text -like "`[100`] Microsoft SQLServerAgent version*" | Should -Be $true + $results.text -like "`[100`] Microsoft SQLServerAgent version*" | Should -Be $true } It "LogDate is a DateTime type" { - $agentLogResults[0].LogDate | Should -BeOfType DateTime + $($results | Select-Object -First 1).LogDate | Should -BeOfType DateTime } } Context "Command gets current agent log using LogNumber parameter" { + BeforeAll { + $results = Get-DbaAgentLog -SqlInstance $TestConfig.instance2 -LogNumber 0 + } + It "Results are not empty" { - $currentLogResults | Should -Not -BeNullOrEmpty + $results | Should -Not -BeNullOrEmpty } } } \ No newline at end of file diff --git a/tests/Get-DbaAgentServer.Tests.ps1 b/tests/Get-DbaAgentServer.Tests.ps1 index 8858ae1f9de8..06071ed41582 100644 --- a/tests/Get-DbaAgentServer.Tests.ps1 +++ b/tests/Get-DbaAgentServer.Tests.ps1 @@ -1,6 +1,6 @@ #Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } param( - $ModuleName = "dbatools", + $ModuleName = "dbatools", $CommandName = "Get-DbaAgentServer", $PSDefaultParameterValues = $TestConfig.Defaults ) @@ -9,7 +9,7 @@ Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig Describe $CommandName -Tag UnitTests { - Context "Validate parameters" { + Context "Parameter validation" { BeforeAll { $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } $expectedParameters = $TestConfig.CommonParameters @@ -20,20 +20,20 @@ Describe $CommandName -Tag UnitTests { ) } - It "Should only contain our specific parameters" { + It "Should have the expected parameters" { Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } Describe $CommandName -Tag IntegrationTests { - Context "Command gets server agent" { + Context "When getting server agent" { BeforeAll { - $results = @(Get-DbaAgentServer -SqlInstance $TestConfig.instance2) + $agentResults = Get-DbaAgentServer -SqlInstance $TestConfig.instance2 } It "Should get 1 agent server" { - $results.Status.Count | Should -BeExactly 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 cedf6c372714..041ca2ba7b1b 100644 --- a/tests/Get-DbaAvailabilityGroup.Tests.ps1 +++ b/tests/Get-DbaAvailabilityGroup.Tests.ps1 @@ -1,6 +1,6 @@ #Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } param( - $ModuleName = "dbatools", + $ModuleName = "dbatools", $CommandName = "Get-DbaAvailabilityGroup", $PSDefaultParameterValues = $TestConfig.Defaults ) @@ -33,6 +33,9 @@ Describe $CommandName -Tag IntegrationTests { # 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 + # Explain what needs to be set up for the test: + # We need to create an availability group to test the Get-DbaAvailabilityGroup command. + # Set variables. They are available in all the It blocks. $agName = "dbatoolsci_agroup" @@ -68,7 +71,7 @@ Describe $CommandName -Tag IntegrationTests { $results.AvailabilityGroup | Should -Contain $agName } - It "Returns a single result for specific AG" { + It "Returns a single result" { $results = Get-DbaAvailabilityGroup -SqlInstance $TestConfig.instance3 -AvailabilityGroup $agName $results.AvailabilityGroup | Should -Be $agName } diff --git a/tests/Get-DbaBackupInformation.Tests.ps1 b/tests/Get-DbaBackupInformation.Tests.ps1 index 8ff1790662ef..c987b16a7871 100644 --- a/tests/Get-DbaBackupInformation.Tests.ps1 +++ b/tests/Get-DbaBackupInformation.Tests.ps1 @@ -1,15 +1,12 @@ #Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } param( - $ModuleName = "dbatools", + $ModuleName = "dbatools", $CommandName = "Get-DbaBackupInformation", $PSDefaultParameterValues = $TestConfig.Defaults ) -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig - Describe $CommandName -Tag UnitTests { - Context "Parameter validation" { + Context "Validate parameters" { BeforeAll { $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } $expectedParameters = $TestConfig.CommonParameters @@ -20,7 +17,6 @@ Describe $CommandName -Tag UnitTests { "DatabaseName", "SourceInstance", "NoXpDirTree", - "NoXpDirRecurse", "DirectoryRecurse", "EnableException", "MaintenanceSolution", @@ -31,7 +27,8 @@ Describe $CommandName -Tag UnitTests { "Import", "Anonymise", "NoClobber", - "PassThru" + "PassThru", + "NoXpDirRecurse" ) } @@ -46,23 +43,20 @@ Describe $CommandName -Tag IntegrationTests { # 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. $DestBackupDir = "C:\Temp\GetBackups" if (-Not(Test-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 = Get-DbaDatabase -SqlInstance $TestConfig.instance1 -Database $dbname | Remove-DbaDatabase $splatRestore1 = @{ - SqlInstance = $TestConfig.instance1 - Path = "$($TestConfig.appveyorlabrepo)\singlerestore\singlerestore.bak" - DatabaseName = $dbname - DestinationFilePrefix = $dbname + 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 @@ -71,12 +65,12 @@ Describe $CommandName -Tag IntegrationTests { $db | Backup-DbaDatabase -Type Log -BackupDirectory $DestBackupDir $dbname2 = "dbatoolsci_Backuphistory2_$random" - $null = Get-DbaDatabase -SqlInstance $TestConfig.instance1 -Database $dbname2 | Remove-DbaDatabase -Confirm:$false + $null = Get-DbaDatabase -SqlInstance $TestConfig.instance1 -Database $dbname2 | Remove-DbaDatabase $splatRestore2 = @{ - SqlInstance = $TestConfig.instance1 - Path = "$($TestConfig.appveyorlabrepo)\singlerestore\singlerestore.bak" - DatabaseName = $dbname2 - DestinationFilePrefix = $dbname2 + 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 @@ -97,12 +91,12 @@ Describe $CommandName -Tag IntegrationTests { } $dbname3 = "dbatoolsci_BackuphistoryOla_$random" - $null = Get-DbaDatabase -SqlInstance $TestConfig.instance1 -Database $dbname3 | Remove-DbaDatabase -Confirm:$false + $null = Get-DbaDatabase -SqlInstance $TestConfig.instance1 -Database $dbname3 | Remove-DbaDatabase $splatRestore3 = @{ - SqlInstance = $TestConfig.instance1 - Path = "$($TestConfig.appveyorlabrepo)\singlerestore\singlerestore.bak" - DatabaseName = $dbname3 - DestinationFilePrefix = $dbname3 + 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 @@ -118,108 +112,162 @@ Describe $CommandName -Tag IntegrationTests { # 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 object. - $null = Get-DbaDatabase -SqlInstance $TestConfig.instance1 -Database $dbname, $dbname2, $dbname3 | Remove-DbaDatabase -Confirm:$false - Remove-Item -Path $DestBackupDir, $DestBackupDirOla -Recurse -Confirm:$false -ErrorAction SilentlyContinue + $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" { BeforeAll { - $allDbResults = Get-DbaBackupInformation -SqlInstance $TestConfig.instance1 -Path $DestBackupDir + $splatAllBackups = @{ + SqlInstance = $TestConfig.instance1 + Path = $DestBackupDir + } + $results = Get-DbaBackupInformation @splatAllBackups } It "Should be 6 backups returned" { - $allDbResults.Status.Count | Should -BeExactly 6 + $results.Count | Should -BeExactly 6 } It "Should return 2 full backups" { - ($allDbResults | Where-Object Type -eq "Database").Status.Count | Should -BeExactly 2 + ($results | Where-Object Type -eq "Database").Count | Should -BeExactly 2 } It "Should return 2 log backups" { - ($allDbResults | Where-Object Type -eq "Transaction Log").Status.Count | Should -BeExactly 2 + ($results | Where-Object Type -eq "Transaction Log").Count | Should -BeExactly 2 } } Context "Get history for one database" { BeforeAll { - $singleDbResults = Get-DbaBackupInformation -SqlInstance $TestConfig.instance1 -Path $DestBackupDir -DatabaseName $dbname2 + $splatOneDatabase = @{ + SqlInstance = $TestConfig.instance1 + Path = $DestBackupDir + DatabaseName = $dbname2 + } + $results = Get-DbaBackupInformation @splatOneDatabase } It "Should be 3 backups returned" { - $singleDbResults.Status.Count | Should -BeExactly 3 + $results.Count | Should -BeExactly 3 } It "Should Be 1 full backup" { - ($singleDbResults | Where-Object Type -eq "Database").Status.Count | Should -BeExactly 1 + ($results | Where-Object Type -eq "Database").Count | Should -BeExactly 1 } It "Should be 1 log backups" { - ($singleDbResults | Where-Object Type -eq "Transaction Log").Status.Count | Should -BeExactly 1 + ($results | Where-Object Type -eq "Transaction Log").Count | Should -BeExactly 1 } It "Should only be backups of $dbname2" { - ($singleDbResults | Where-Object Database -ne $dbname2).Status.Count | Should -BeExactly 0 + ($results | Where-Object Database -ne $dbname2).Count | Should -BeExactly 0 } } Context "Check the export/import of backup history" { BeforeAll { # This one used to cause all sorts of red - $exportResults = Get-DbaBackupInformation -SqlInstance $TestConfig.instance1 -Path $DestBackupDir -DatabaseName $dbname2 -ExportPath "$DestBackupDir\history.xml" + $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 } It "Should restore cleanly" { - ($exportResults | Where-Object RestoreComplete -eq $false).Status.Count | Should -BeExactly 0 + ($results | Where-Object RestoreComplete -eq $false).Count | Should -BeExactly 0 } } Context "Test Maintenance solution options" { BeforeAll { - $olaResults = Get-DbaBackupInformation -SqlInstance $TestConfig.instance1 -Path $DestBackupDirOla -MaintenanceSolution - $olaResultsSanLog = Get-DbaBackupInformation -SqlInstance $TestConfig.instance1 -Path $DestBackupDirOla -MaintenanceSolution -IgnoreLogBackup - $olaResultsWarnTest = Get-DbaBackupInformation -SqlInstance $TestConfig.instance1 -Path $DestBackupDirOla -IgnoreLogBackup -WarningVariable warnvar -WarningAction SilentlyContinue 3> $null + $splatMaintenance = @{ + SqlInstance = $TestConfig.instance1 + Path = $DestBackupDirOla + MaintenanceSolution = $true + } + $results = Get-DbaBackupInformation @splatMaintenance } It "Should be 3 backups returned" { - $olaResults.Status.Count | Should -BeExactly 3 + $results.Count | Should -BeExactly 3 } It "Should Be 1 full backup" { - ($olaResults | Where-Object Type -eq "Database").Status.Count | Should -BeExactly 1 + ($results | Where-Object Type -eq "Database").Count | Should -BeExactly 1 } It "Should be 1 log backups" { - ($olaResults | Where-Object Type -eq "Transaction Log").Status.Count | Should -BeExactly 1 + ($results | Where-Object Type -eq "Transaction Log").Count | Should -BeExactly 1 } It "Should only be backups of $dbname3" { - ($olaResults | Where-Object Database -ne $dbname3).Status.Count | Should -BeExactly 0 + ($results | Where-Object Database -ne $dbname3).Count | Should -BeExactly 0 } - It "Should be 2 backups returned" { - $olaResultsSanLog.Status.Count | Should -BeExactly 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" { - ($olaResultsSanLog | Where-Object Type -eq "Database").Status.Count | Should -BeExactly 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" { - ($olaResultsSanLog | Where-Object Type -eq "Transaction Log").Status.Count | Should -BeExactly 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 } 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" { - $olaResultsWarnTest.Status.Count | Should -BeExactly 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 From e68c4a8b51ff511e7861f70ce9a520d9e374e6f6 Mon Sep 17 00:00:00 2001 From: Chrissy LeMaire Date: Mon, 11 Aug 2025 00:25:06 +0200 Subject: [PATCH 10/14] Add Pattern parameter to filter test files Introduces a new 'Pattern' parameter to Repair-PullRequestTest, allowing users to filter test files by name using wildcards. Updates logic to apply this filter when processing failed tests and enhances verbose output to reflect the applied pattern. --- .aitools/module/Repair-PullRequestTest.ps1 | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/.aitools/module/Repair-PullRequestTest.ps1 b/.aitools/module/Repair-PullRequestTest.ps1 index 9b796a517681..9cdb2ea316b1 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" From ebfd2980b00d0bffc221ba88ed7d775697983777 Mon Sep 17 00:00:00 2001 From: Chrissy LeMaire Date: Mon, 11 Aug 2025 00:31:29 +0200 Subject: [PATCH 11/14] Refactor and clean up test scripts for consistency Standardized variable naming, improved parameter usage, and removed redundant or unnecessary code in test scripts. Updated test assertions for clarity and consistency, and simplified setup/teardown logic. These changes improve readability and maintainability of the test suite. --- tests/Find-DbaAgentJob.Tests.ps1 | 254 ++++++++++---------- tests/Find-DbaOrphanedFile.Tests.ps1 | 37 ++- tests/Format-DbaBackupInformation.Tests.ps1 | 168 +++++-------- tests/Get-DbaAgentJob.Tests.ps1 | 18 +- tests/Get-DbaAgentJobHistory.Tests.ps1 | 139 +++++------ tests/Get-DbaAgentLog.Tests.ps1 | 6 +- tests/Get-DbaAvailabilityGroup.Tests.ps1 | 13 +- 7 files changed, 265 insertions(+), 370 deletions(-) diff --git a/tests/Find-DbaAgentJob.Tests.ps1 b/tests/Find-DbaAgentJob.Tests.ps1 index 694e510e42ee..2ae0c565569a 100644 --- a/tests/Find-DbaAgentJob.Tests.ps1 +++ b/tests/Find-DbaAgentJob.Tests.ps1 @@ -35,179 +35,169 @@ Describe $CommandName -Tag 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 - - #subsystemServer needs the real underlying name, and it doesn't work if targeting something like localhost\namedinstance - # the typical error would be WARNING: [17:19:26][New-DbaAgentJobStep] Something went wrong creating the job step | The specified '@server' is - #invalid (valid values are returned by sp_helpserver). - $srvName = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Query "select @@servername as sn" -as PSObject - - # Create test jobs - $splatTestJob = @{ - SqlInstance = $TestConfig.instance2 - Job = "dbatoolsci_testjob" - OwnerLogin = "sa" - } - $null = New-DbaAgentJob @splatTestJob - - $splatTestJobStep = @{ - SqlInstance = $TestConfig.instance2 - Job = "dbatoolsci_testjob" - StepId = 1 - StepName = "dbatoolsci Failed" - Subsystem = "TransactSql" - SubsystemServer = $srvName.sn - Command = "RAISERROR (15600,-1,-1, 'dbatools_error');" - CmdExecSuccessCode = 0 - OnSuccessAction = "QuitWithSuccess" - OnFailAction = "QuitWithFailure" - Database = "master" - RetryAttempts = 1 - RetryInterval = 2 - } - $null = New-DbaAgentJobStep @splatTestJobStep - - $null = Start-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job "dbatoolsci_testjob" - - $splatRegrJob = @{ - SqlInstance = $TestConfig.instance2 - Job = "dbatoolsregr_testjob" - OwnerLogin = "sa" - } - $null = New-DbaAgentJob @splatRegrJob - - $splatRegrJobStep = @{ - SqlInstance = $TestConfig.instance2 - Job = "dbatoolsregr_testjob" - StepId = 1 - StepName = "dbatoolsci Failed" - Subsystem = "TransactSql" - SubsystemServer = $srvName.sn - Command = "RAISERROR (15600,-1,-1, 'dbatools_error');" - CmdExecSuccessCode = 0 - OnSuccessAction = "QuitWithSuccess" - OnFailAction = "QuitWithFailure" - Database = "master" - RetryAttempts = 1 - RetryInterval = 2 - } - $null = New-DbaAgentJobStep @splatRegrJobStep - - $null = New-DbaAgentJobCategory -SqlInstance $TestConfig.instance2 -Category "dbatoolsci_job_category" -CategoryType LocalJob - - $splatDisabledJob = @{ - SqlInstance = $TestConfig.instance2 - Job = "dbatoolsci_testjob_disabled" - Category = "dbatoolsci_job_category" - Disabled = $true - } - $null = New-DbaAgentJob @splatDisabledJob - - $splatDisabledJobStep = @{ - SqlInstance = $TestConfig.instance2 - Job = "dbatoolsci_testjob_disabled" - StepId = 1 - StepName = "dbatoolsci Test Step" - Subsystem = "TransactSql" - SubsystemServer = $srvName.sn - Command = "SELECT * FROM master.sys.all_columns" - CmdExecSuccessCode = 0 - OnSuccessAction = "QuitWithSuccess" - OnFailAction = "QuitWithFailure" - Database = "master" - RetryAttempts = 1 - RetryInterval = 2 - } - $null = New-DbaAgentJobStep @splatDisabledJobStep - - # 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 - - $splatRemoveJobs = @{ - SqlInstance = $TestConfig.instance2 - Job = @("dbatoolsci_testjob", "dbatoolsregr_testjob", "dbatoolsci_testjob_disabled") - Confirm = $false - } - $null = Remove-DbaAgentJob @splatRemoveJobs - - $null = Remove-DbaAgentJobCategory -SqlInstance $TestConfig.instance2 -Category "dbatoolsci_job_category" -Confirm $false - - # As this is the last block we do not need to reset the $PSDefaultParameterValues. - } - Context "Command finds jobs using all parameters" { BeforeAll { - $testJobResult = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob - $excludedJobResult = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job *dbatoolsci* -ExcludeJobName dbatoolsci_testjob_disabled - $stepNameResult = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -StepName "dbatoolsci Test Step" - $lastUsedResult = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -LastUsed 10 - $disabledResult = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsDisabled - $notScheduledResult = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsNotScheduled - $notScheduledWildcardResult = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsNotScheduled -Job *dbatoolsci* - $noEmailResult = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsNoEmailNotification - $categoryResult = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Category "dbatoolsci_job_category" - $ownerResult = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Owner "sa" - $failedResult = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsFailed -Since "2016-07-01 10:47:00" - $multiWildcardResult = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job *dbatoolsci*, *dbatoolsregr* -ExcludeJobName dbatoolsci_testjob_disabled + # 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 + + #subsystemServer needs the real underlying name, and it doesn't work if targeting something like localhost\namedinstance + # the typical error would be WARNING: [17:19:26][New-DbaAgentJobStep] Something went wrong creating the job step | The specified '@server' is + #invalid (valid values are returned by sp_helpserver). + $srvName = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Query "select @@servername as sn" -as PSObject + + $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job "dbatoolsci_testjob" -OwnerLogin "sa" + + $splatJobStep1 = @{ + SqlInstance = $TestConfig.instance2 + Job = "dbatoolsci_testjob" + StepId = 1 + StepName = "dbatoolsci Failed" + Subsystem = "TransactSql" + SubsystemServer = $srvName.sn + Command = "RAISERROR (15600,-1,-1, 'dbatools_error');" + CmdExecSuccessCode = 0 + OnSuccessAction = "QuitWithSuccess" + OnFailAction = "QuitWithFailure" + Database = "master" + RetryAttempts = 1 + RetryInterval = 2 + } + $null = New-DbaAgentJobStep @splatJobStep1 + + $null = Start-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job "dbatoolsci_testjob" + + $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job "dbatoolsregr_testjob" -OwnerLogin "sa" + + $splatJobStep2 = @{ + SqlInstance = $TestConfig.instance2 + Job = "dbatoolsregr_testjob" + StepId = 1 + StepName = "dbatoolsci Failed" + Subsystem = "TransactSql" + SubsystemServer = $srvName.sn + Command = "RAISERROR (15600,-1,-1, 'dbatools_error');" + CmdExecSuccessCode = 0 + OnSuccessAction = "QuitWithSuccess" + OnFailAction = "QuitWithFailure" + Database = "master" + RetryAttempts = 1 + RetryInterval = 2 + } + $null = New-DbaAgentJobStep @splatJobStep2 + + $null = New-DbaAgentJobCategory -SqlInstance $TestConfig.instance2 -Category "dbatoolsci_job_category" -CategoryType LocalJob + $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job "dbatoolsci_testjob_disabled" -Category "dbatoolsci_job_category" -Disabled + + $splatJobStep3 = @{ + SqlInstance = $TestConfig.instance2 + Job = "dbatoolsci_testjob_disabled" + StepId = 1 + StepName = "dbatoolsci Test Step" + Subsystem = "TransactSql" + SubsystemServer = $srvName.sn + Command = "SELECT * FROM master.sys.all_columns" + CmdExecSuccessCode = 0 + OnSuccessAction = "QuitWithSuccess" + OnFailAction = "QuitWithFailure" + Database = "master" + RetryAttempts = 1 + RetryInterval = 2 + } + $null = New-DbaAgentJobStep @splatJobStep3 + + # 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 + + $splatRemoveJob = @{ + SqlInstance = $TestConfig.instance2 + Job = @("dbatoolsci_testjob", "dbatoolsregr_testjob", "dbatoolsci_testjob_disabled") + Confirm = $false + } + $null = Remove-DbaAgentJob @splatRemoveJob + + $null = Remove-DbaAgentJobCategory -SqlInstance $TestConfig.instance2 -Category "dbatoolsci_job_category" -Confirm $false + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } It "Should find a specific job" { - $testJobResult.name | Should -Be "dbatoolsci_testjob" + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -JobName "dbatoolsci_testjob" + $results.name | Should -Be "dbatoolsci_testjob" } It "Should find a specific job but not an excluded job" { - $excludedJobResult.name | Should -Not -Be "dbatoolsci_testjob_disabled" + $splatFindExclude = @{ + SqlInstance = $TestConfig.instance2 + JobName = "*dbatoolsci*" + ExcludeJobName = "dbatoolsci_testjob_disabled" + } + $results = Find-DbaAgentJob @splatFindExclude + $results.name | Should -Not -Be "dbatoolsci_testjob_disabled" } It "Should find a specific job with a specific step" { - $stepNameResult.name | Should -Be "dbatoolsci_testjob_disabled" + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -StepName "dbatoolsci Test Step" + $results.name | Should -Be "dbatoolsci_testjob_disabled" } It "Should find jobs not used in the last 10 days" { - $lastUsedResult | Should -Not -BeNullOrEmpty + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -LastUsed 10 + $results | Should -Not -BeNullOrEmpty } It "Should find jobs disabled from running" { - $disabledResult.name | Should -Be "dbatoolsci_testjob_disabled" + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsDisabled + $results.name | Should -Be "dbatoolsci_testjob_disabled" } It "Should find 1 job disabled from running" { - $disabledResult.Status.Count | Should -Be 1 + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsDisabled + $results.Status.Count | Should -Be 1 } It "Should find jobs that have not been scheduled" { - $notScheduledResult | Should -Not -BeNullOrEmpty + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsNotScheduled + $results | Should -Not -BeNullOrEmpty } It "Should find 2 jobs that have no schedule" { - $notScheduledWildcardResult.Status.Count | Should -Be 2 + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsNotScheduled -JobName "*dbatoolsci*" + $results.Status.Count | Should -Be 2 } It "Should find jobs that have no email notification" { - $noEmailResult | Should -Not -BeNullOrEmpty + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsNoEmailNotification + $results | Should -Not -BeNullOrEmpty } It "Should find jobs that have a category of dbatoolsci_job_category" { - $categoryResult.name | Should -Be "dbatoolsci_testjob_disabled" + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Category "dbatoolsci_job_category" + $results.name | Should -Be "dbatoolsci_testjob_disabled" } It "Should find jobs that are owned by sa" { - $ownerResult | Should -Not -BeNullOrEmpty + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Owner "sa" + $results | Should -Not -BeNullOrEmpty } It "Should find jobs that have been failed since July of 2016" { - $failedResult | Should -Not -BeNullOrEmpty + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsFailed -Since "2016-07-01 10:47:00" + $results | Should -Not -BeNullOrEmpty } It "Should work with multiple wildcard passed in (see #9572)" { - $multiWildcardResult.Status.Count | Should -Be 2 + $splatMultiWildcard = @{ + SqlInstance = $TestConfig.instance2 + JobName = @("*dbatoolsci*", "*dbatoolsregr*") + ExcludeJobName = "dbatoolsci_testjob_disabled" + } + $results = Find-DbaAgentJob @splatMultiWildcard + $results.Status.Count | Should -Be 2 } } } \ No newline at end of file diff --git a/tests/Find-DbaOrphanedFile.Tests.ps1 b/tests/Find-DbaOrphanedFile.Tests.ps1 index 0a10782fa751..0232212af1ce 100644 --- a/tests/Find-DbaOrphanedFile.Tests.ps1 +++ b/tests/Find-DbaOrphanedFile.Tests.ps1 @@ -5,9 +5,6 @@ param( $PSDefaultParameterValues = $TestConfig.Defaults ) -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig - Describe $CommandName -Tag UnitTests { Context "Validate parameters" { BeforeAll { @@ -37,7 +34,6 @@ Describe $CommandName -Tag IntegrationTests { # 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 databases $dbname = "dbatoolsci_orphanedfile_$(Get-Random)" $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 $db1 = New-DbaDatabase -SqlInstance $server -Name $dbname @@ -45,38 +41,35 @@ Describe $CommandName -Tag IntegrationTests { $dbname2 = "dbatoolsci_orphanedfile_$(Get-Random)" $db2 = New-DbaDatabase -SqlInstance $server -Name $dbname2 - # Create test directories $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 - # Verify setup $result = Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname if ($result.Count -eq 0) { - throw "Test setup failed - database not created" + throw "Setup failed: database not created" } - # Create backups $backupFile = Backup-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname -Path $tmpBackupPath -Type Full $backupFile2 = Backup-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname2 -Path $tmpBackupPath2 -Type Full Copy-Item -Path $backupFile.BackupPath -Destination "C:\" -Confirm:$false $tmpBackupPath3 = Join-Path (Get-SqlDefaultPaths $server data) "dbatoolsci_$(Get-Random)" - $null = New-Item -Path $tmpBackupPath3 -Type Container + $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') @@ -84,8 +77,6 @@ Describe $CommandName -Tag IntegrationTests { 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 - - # Cleanup all created objects 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 @@ -106,24 +97,24 @@ Describe $CommandName -Tag IntegrationTests { It "Finds two files" { $results = Find-DbaOrphanedFile -SqlInstance $TestConfig.instance2 - @($results.Filename).Count | Should -Be 2 + $results.Filename.Count | Should -Be 2 } It "Finds zero files after cleaning up" { $results = Find-DbaOrphanedFile -SqlInstance $TestConfig.instance2 $results.FileName | Remove-Item $results = Find-DbaOrphanedFile -SqlInstance $TestConfig.instance2 - @($results.Filename).Count | Should -Be 0 + $results.Filename.Count | Should -Be 0 } It "works with -Recurse" { "a" | Out-File (Join-Path $tmpdir "out.mdf") $results = Find-DbaOrphanedFile -SqlInstance $TestConfig.instance2 -Path $tmpdir - @($results.Filename).Count | Should -Be 1 + $results.Filename.Count | Should -Be 1 Move-Item "$tmpdir\out.mdf" -Destination $tmpdirInner $results = Find-DbaOrphanedFile -SqlInstance $TestConfig.instance2 -Path $tmpdir - @($results.Filename).Count | Should -Be 0 + $results.Filename.Count | Should -Be 0 $results = Find-DbaOrphanedFile -SqlInstance $TestConfig.instance2 -Path $tmpdir -Recurse - @($results.Filename).Count | Should -Be 1 + $results.Filename.Count | Should -Be 1 Copy-Item -Path "$tmpdirInner\out.mdf" -Destination $tmpBackupPath3 -Confirm:$false @@ -132,7 +123,7 @@ Describe $CommandName -Tag IntegrationTests { $results.Filename | Should -Contain $backupFile2.BackupPath $results.Filename | Should -Contain "$tmpdirInner\out.mdf" $results.Filename | Should -Contain "$tmpBackupPath3\out.mdf" - @($results).Count | Should -Be 4 + $results.Count | Should -Be 4 $results = Find-DbaOrphanedFile -SqlInstance $TestConfig.instance2 -Recurse $results.Filename | Should -Be "$tmpBackupPath3\out.mdf" diff --git a/tests/Format-DbaBackupInformation.Tests.ps1 b/tests/Format-DbaBackupInformation.Tests.ps1 index 466af0d361ab..e2fd3929915d 100644 --- a/tests/Format-DbaBackupInformation.Tests.ps1 +++ b/tests/Format-DbaBackupInformation.Tests.ps1 @@ -5,6 +5,9 @@ param( $PSDefaultParameterValues = $TestConfig.Defaults ) +Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan +$global:TestConfig = Get-TestConfig + Describe $CommandName -Tag UnitTests { Context "Parameter validation" { BeforeAll { @@ -35,11 +38,10 @@ Describe $CommandName -Tag UnitTests { } Describe $CommandName -Tag IntegrationTests { - Context "Rename a Database" { BeforeAll { - $history = Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\ContinuePointTest.xml - $output = $history | Format-DbaBackupInformation -ReplaceDatabaseName "Pester" + $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" { @@ -53,8 +55,8 @@ Describe $CommandName -Tag IntegrationTests { Context "Test it works as a parameter as well" { BeforeAll { - $history = Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\ContinuePointTest.xml - $output = Format-DbaBackupInformation -BackupHistory $history -ReplaceDatabaseName "Pester" + $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" { @@ -62,22 +64,15 @@ Describe $CommandName -Tag IntegrationTests { } It "Should have renamed datafiles as well" { - ($output | Select-Object -ExpandProperty filelist | Where-Object { $PSItem.PhysicalName -like "ContinuePointTest" }).Count | Should -BeExactly 0 + ($output | Select-Object -ExpandProperty filelist | Where-Object { $PSItem.PhysicalName -like "*ContinuePointTest*" }).Count | Should -BeExactly 0 } } Context "Rename 2 dbs using a hash" { BeforeAll { - $history = Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\ContinuePointTest.xml - $history += Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\RestoreTimeClean.xml - $splatReplaceName = @{ - BackupHistory = $history - ReplaceDatabaseName = @{ - "ContinuePointTest" = "Spiggy" - "RestoreTimeClean" = "Eldritch" - } - } - $output = Format-DbaBackupInformation @splatReplaceName + $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" } } It "Should have no databases other than spiggy and eldritch" { @@ -85,39 +80,29 @@ Describe $CommandName -Tag IntegrationTests { } It "Should have renamed all RestoreTimeCleans to Eldritch" { - $restoreTimeResults = $output | Where-Object { $PSItem.OriginalDatabase -eq "RestoreTimeClean" } - ($restoreTimeResults | Where-Object { $PSItem.Database -ne "Eldritch" }).Count | Should -BeExactly 0 + ($output | Where-Object { $PSItem.OriginalDatabase -eq "RestoreTimeClean" } | Where-Object { $PSItem.Database -ne "Eldritch" }).Count | Should -BeExactly 0 } It "Should have renamed all the RestoreTimeClean files to Eldritch" { - $restoreTimeResults = $output | Where-Object { $PSItem.OriginalDatabase -eq "RestoreTimeClean" } - $restoreTimeFileList = $restoreTimeResults | Select-Object -ExpandProperty filelist - ($restoreTimeFileList | Where-Object { $PSItem.PhysicalName -like "RestoreTimeClean" }).Count | Should -BeExactly 0 - ($restoreTimeFileList | Where-Object { $PSItem.PhysicalName -like "eldritch" }).Count | Should -BeExactly $restoreTimeFileList.Count + ($output | Where-Object { $PSItem.OriginalDatabase -eq "RestoreTimeClean" } | Select-Object -ExpandProperty filelist | Where-Object { $PSItem.PhysicalName -like "*RestoreTimeClean*" }).Count | Should -BeExactly 0 + ($output | Where-Object { $PSItem.OriginalDatabase -eq "RestoreTimeClean" } | Select-Object -ExpandProperty filelist | Where-Object { $PSItem.PhysicalName -like "*eldritch*" }).Count | Should -BeExactly ($output | Where-Object { $PSItem.OriginalDatabase -eq "RestoreTimeClean" } | Select-Object -ExpandProperty filelist).Count } It "Should have renamed all ContinuePointTest to Spiggy" { - $continuePointResults = $output | Where-Object { $PSItem.OriginalDatabase -eq "ContinuePointTest" } - ($continuePointResults | Where-Object { $PSItem.Database -ne "Spiggy" }).Count | Should -BeExactly 0 + ($output | Where-Object { $PSItem.OriginalDatabase -eq "ContinuePointTest" } | Where-Object { $PSItem.Database -ne "Spiggy" }).Count | Should -BeExactly 0 } It "Should have renamed all the ContinuePointTest files to Spiggy" { - $continuePointResults = $output | Where-Object { $PSItem.OriginalDatabase -eq "ContinuePointTest" } - $continuePointFileList = $continuePointResults | Select-Object -ExpandProperty filelist - ($continuePointFileList | Where-Object { $PSItem.PhysicalName -like "ContinuePointTest" }).Count | Should -BeExactly 0 - ($continuePointFileList | Where-Object { $PSItem.PhysicalName -like "spiggy" }).Count | Should -BeExactly $continuePointFileList.Count + ($output | Where-Object { $PSItem.OriginalDatabase -eq "ContinuePointTest" } | Select-Object -ExpandProperty filelist | Where-Object { $PSItem.PhysicalName -like "*ContinuePointTest*" }).Count | Should -BeExactly 0 + ($output | Where-Object { $PSItem.OriginalDatabase -eq "ContinuePointTest" } | Select-Object -ExpandProperty filelist | Where-Object { $PSItem.PhysicalName -like "*spiggy*" }).Count | Should -BeExactly ($output | Where-Object { $PSItem.OriginalDatabase -eq "ContinuePointTest" } | Select-Object -ExpandProperty filelist).Count } } Context "Rename 1 dbs using a hash" { BeforeAll { - $history = Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\ContinuePointTest.xml - $history += Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\RestoreTimeClean.xml - $splatSingleRename = @{ - BackupHistory = $history - ReplaceDatabaseName = @{ "ContinuePointTest" = "Alice" } - } - $output = Format-DbaBackupInformation @splatSingleRename + $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" } } It "Should have no databases other than RestoreTimeClean and Alice" { @@ -125,27 +110,23 @@ Describe $CommandName -Tag IntegrationTests { } It "Should have left RestoreTimeClean alone" { - $restoreTimeResults = $output | Where-Object { $PSItem.OriginalDatabase -eq "RestoreTimeClean" } - ($restoreTimeResults | Where-Object { $PSItem.Database -ne "RestoreTimeClean" }).Count | Should -BeExactly 0 + ($output | Where-Object { $PSItem.OriginalDatabase -eq "RestoreTimeClean" } | Where-Object { $PSItem.Database -ne "RestoreTimeClean" }).Count | Should -BeExactly 0 } It "Should have renamed all ContinuePointTest to Alice" { - $continuePointResults = $output | Where-Object { $PSItem.OriginalDatabase -eq "ContinuePointTest" } - ($continuePointResults | Where-Object { $PSItem.Database -ne "Alice" }).Count | Should -BeExactly 0 + ($output | Where-Object { $PSItem.OriginalDatabase -eq "ContinuePointTest" } | Where-Object { $PSItem.Database -ne "Alice" }).Count | Should -BeExactly 0 } It "Should have renamed all the ContinuePointTest files to Alice" { - $continuePointResults = $output | Where-Object { $PSItem.OriginalDatabase -eq "ContinuePointTest" } - $continuePointFileList = $continuePointResults | Select-Object -ExpandProperty filelist - ($continuePointFileList | Where-Object { $PSItem.PhysicalName -like "ContinuePointTest" }).Count | Should -BeExactly 0 - ($continuePointFileList | Where-Object { $PSItem.PhysicalName -like "alice" }).Count | Should -BeExactly $continuePointFileList.Count + ($output | Where-Object { $PSItem.OriginalDatabase -eq "ContinuePointTest" } | Select-Object -ExpandProperty filelist | Where-Object { $PSItem.PhysicalName -like "*ContinuePointTest*" }).Count | Should -BeExactly 0 + ($output | Where-Object { $PSItem.OriginalDatabase -eq "ContinuePointTest" } | Select-Object -ExpandProperty filelist | Where-Object { $PSItem.PhysicalName -like "*alice*" }).Count | Should -BeExactly ($output | Where-Object { $PSItem.OriginalDatabase -eq "ContinuePointTest" } | Select-Object -ExpandProperty filelist).Count } } Context "Check DB Name prefix and suffix" { BeforeAll { - $history = Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\ContinuePointTest.xml - $output = $history | Format-DbaBackupInformation -DatabaseNamePrefix PREFIX + $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" { @@ -155,121 +136,90 @@ Describe $CommandName -Tag IntegrationTests { Context "Check DataFileDirectory moves all files" { BeforeAll { - $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 -DataFileDirectory "c:\restores" + $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 -DataFileDirectory c:\restores } It "Should have move ALL files to c:\restores\" { - $allFiles = $output | Select-Object -ExpandProperty Filelist - ($allFiles.PhysicalName | Split-Path | Where-Object { $PSItem -ne "c:\restores" }).Count | Should -BeExactly 0 + (($output | Select-Object -ExpandProperty Filelist).PhysicalName | Split-Path | Where-Object { $PSItem -ne "c:\restores" }).Count | Should -BeExactly 0 } } Context "Check DataFileDirectory and LogFileDirectory work independently" { BeforeAll { - $history = Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\ContinuePointTest.xml - $history += Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\RestoreTimeClean.xml - $splatDirectories = @{ - BackupHistory = $history - DataFileDirectory = "c:\restores\" - LogFileDirectory = "c:\logs" - } - $output = Format-DbaBackupInformation @splatDirectories + $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 -DataFileDirectory c:\restores\ -LogFileDirectory c:\logs } It "Should have moved all data files to c:\restores\" { - $dataFiles = $output | Select-Object -ExpandProperty Filelist | Where-Object { $PSItem.Type -eq "D" } - ($dataFiles.PhysicalName | Split-Path | Where-Object { $PSItem -ne "c:\restores" }).Count | Should -BeExactly 0 + (($output | Select-Object -ExpandProperty Filelist | Where-Object { $PSItem.Type -eq "D" }).PhysicalName | Split-Path | Where-Object { $PSItem -ne "c:\restores" }).Count | Should -BeExactly 0 } It "Should have moved all log files to c:\logs\" { - $logFiles = $output | Select-Object -ExpandProperty Filelist | Where-Object { $PSItem.Type -eq "L" } - ($logFiles.PhysicalName | Split-Path | Where-Object { $PSItem -ne "c:\logs" }).Count | Should -BeExactly 0 + (($output | Select-Object -ExpandProperty Filelist | Where-Object { $PSItem.Type -eq "L" }).PhysicalName | Split-Path | Where-Object { $PSItem -ne "c:\logs" }).Count | Should -BeExactly 0 } } Context "Check LogFileDirectory works for just logfiles" { BeforeAll { - $history = Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\ContinuePointTest.xml - $history += Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\RestoreTimeClean.xml - $splatLogDirectory = @{ - BackupHistory = $history - DataFileDirectory = "c:\restores\" - LogFileDirectory = "c:\logs" - } - $output = Format-DbaBackupInformation @splatLogDirectory + $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 -DataFileDirectory c:\restores\ -LogFileDirectory c:\logs } - It "Should not have moved data files to c:\logs\" { - $dataFiles = $output | Select-Object -ExpandProperty Filelist | Where-Object { $PSItem.Type -eq "D" } - ($dataFiles.PhysicalName | Split-Path | Where-Object { $PSItem -eq "c:\logs" }).Count | Should -BeExactly 0 + It "Should not have moved all data files to c:\logs\" { + (($output | Select-Object -ExpandProperty Filelist | Where-Object { $PSItem.Type -eq "D" }).PhysicalName | Split-Path | Where-Object { $PSItem -eq "c:\logs" }).Count | Should -BeExactly 0 } It "Should have moved all log files to c:\logs\" { - $logFiles = $output | Select-Object -ExpandProperty Filelist | Where-Object { $PSItem.Type -eq "L" } - ($logFiles.PhysicalName | Split-Path | Where-Object { $PSItem -ne "c:\logs" }).Count | Should -BeExactly 0 + (($output | Select-Object -ExpandProperty Filelist | Where-Object { $PSItem.Type -eq "L" }).PhysicalName | Split-Path | Where-Object { $PSItem -ne "c:\logs" }).Count | Should -BeExactly 0 } } Context "Test RebaseBackupFolder" { BeforeAll { - $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 -RebaseBackupFolder "c:\backups\" + $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 -RebaseBackupFolder c:\backups\ } It "Should have moved all backup files to c:\backups" { - ($output | Select-Object -ExpandProperty FullName | Split-Path | Where-Object { $PSItem -eq "c:\backups" }).Count | Should -BeExactly $history.Count + ($output | Select-Object -ExpandProperty FullName | Split-Path | Where-Object { $PSItem -eq "c:\backups" }).Count | Should -BeExactly $History.Count } } Context "Test PathSep" { BeforeAll { - $history = Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\ContinuePointTest.xml - $history += Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\RestoreTimeClean.xml + $History = Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\ContinuePointTest.xml + $History += Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\RestoreTimeClean.xml } It "Should not have changed the default path separator" { - $output = Format-DbaBackupInformation -BackupHistory $history -RebaseBackupFolder "c:\backups" - ($output | Select-Object -ExpandProperty FullName | Split-Path | Where-Object { $PSItem -eq "c:\backups" }).Count | Should -BeExactly $history.Count + $output = Format-DbaBackupInformation -BackupHistory $History -RebaseBackupFolder "c:\backups" + ($output | Select-Object -ExpandProperty FullName | Split-Path | Where-Object { $PSItem -eq "c:\backups" }).Count | Should -BeExactly $History.Count } It "Should not have changed the default path separator even when passed explicitly" { - $splatDefaultSep = @{ - BackupHistory = $history - RebaseBackupFolder = "c:\backups" - PathSep = "\" - } - $output = Format-DbaBackupInformation @splatDefaultSep - ($output | Select-Object -ExpandProperty FullName | Split-Path | Where-Object { $PSItem -eq "c:\backups" }).Count | Should -BeExactly $history.Count + $output = Format-DbaBackupInformation -BackupHistory $History -RebaseBackupFolder "c:\backups" -PathSep "\" + ($output | Select-Object -ExpandProperty FullName | Split-Path | Where-Object { $PSItem -eq "c:\backups" }).Count | Should -BeExactly $History.Count } It "Should have changed the path separator as instructed" { - $splatLinuxSep = @{ - BackupHistory = $history - RebaseBackupFolder = "/opt/mssql/backups" - PathSep = "/" - } - $output = Format-DbaBackupInformation @splatLinuxSep + $output = Format-DbaBackupInformation -BackupHistory $History -RebaseBackupFolder "/opt/mssql/backups" -PathSep "/" $result = $output | Select-Object -ExpandProperty FullName | ForEach-Object { $all = $PSItem.Split("/") $all[0..($all.Length - 2)] -Join "/" } - ($result | Where-Object { $PSItem -eq "/opt/mssql/backups" }).Count | Should -BeExactly $history.Count + ($result | Where-Object { $PSItem -eq "/opt/mssql/backups" }).Count | Should -BeExactly $History.Count } } Context "Test everything all at once" { BeforeAll { - $history = Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\ContinuePointTest.xml - $splatEverything = @{ - ReplaceDatabaseName = "Pester" - DataFileDirectory = "c:\restores" - LogFileDirectory = "c:\logs\" - RebaseBackupFolder = "c:\backups\" - } - $output = $history | Format-DbaBackupInformation @splatEverything + $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" { @@ -281,17 +231,15 @@ Describe $CommandName -Tag IntegrationTests { } It "Should have moved all data files to c:\restores\" { - $dataFiles = $output | Select-Object -ExpandProperty Filelist | Where-Object { $PSItem.Type -eq "D" } - ($dataFiles.PhysicalName | Split-Path | Where-Object { $PSItem -ne "c:\restores" }).Count | Should -BeExactly 0 + (($output | Select-Object -ExpandProperty Filelist | Where-Object { $PSItem.Type -eq "D" }).PhysicalName | Split-Path | Where-Object { $PSItem -ne "c:\restores" }).Count | Should -BeExactly 0 } It "Should have moved all log files to c:\logs\" { - $logFiles = $output | Select-Object -ExpandProperty Filelist | Where-Object { $PSItem.Type -eq "L" } - ($logFiles.PhysicalName | Split-Path | Where-Object { $PSItem -ne "c:\logs" }).Count | Should -BeExactly 0 + (($output | Select-Object -ExpandProperty Filelist | Where-Object { $PSItem.Type -eq "L" }).PhysicalName | Split-Path | Where-Object { $PSItem -ne "c:\logs" }).Count | Should -BeExactly 0 } It "Should have moved all backup files to c:\backups" { - ($output | Select-Object -ExpandProperty FullName | Split-Path | Where-Object { $PSItem -eq "c:\backups" }).Count | Should -BeExactly $history.Count + ($output | Select-Object -ExpandProperty FullName | Split-Path | Where-Object { $PSItem -eq "c:\backups" }).Count | Should -BeExactly $History.Count } } } \ No newline at end of file diff --git a/tests/Get-DbaAgentJob.Tests.ps1 b/tests/Get-DbaAgentJob.Tests.ps1 index c5d6fcbdfe33..1c65972c259e 100644 --- a/tests/Get-DbaAgentJob.Tests.ps1 +++ b/tests/Get-DbaAgentJob.Tests.ps1 @@ -1,11 +1,11 @@ #Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } param( - $ModuleName = "dbatools", + $ModuleName = "dbatools", $CommandName = "Get-DbaAgentJob", $PSDefaultParameterValues = $TestConfig.Defaults ) -Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan +Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig Describe $CommandName -Tag UnitTests { @@ -20,11 +20,11 @@ Describe $CommandName -Tag UnitTests { "ExcludeJob", "Database", "Category", - "ExcludeCategory", "ExcludeDisabledJobs", + "EnableException", + "ExcludeCategory", "IncludeExecution", - "Type", - "EnableException" + "Type" ) } @@ -46,7 +46,7 @@ Describe $CommandName -Tag IntegrationTests { } It "Should get 2 dbatoolsci jobs" { - $results = Get-DbaAgentJob -SqlInstance $TestConfig.instance2 | Where-Object Name -match "dbatoolsci_testjob" + $results = Get-DbaAgentJob -SqlInstance $TestConfig.instance2 | Where-Object { $PSItem.Name -match "dbatoolsci_testjob" } $results.Count | Should -Be 2 } @@ -67,7 +67,7 @@ Describe $CommandName -Tag IntegrationTests { } It "Should return only enabled jobs" { - $results = Get-DbaAgentJob -SqlInstance $TestConfig.instance2 -ExcludeDisabledJobs | Where-Object Name -match "dbatoolsci_testjob" + $results = Get-DbaAgentJob -SqlInstance $TestConfig.instance2 -ExcludeDisabledJobs | Where-Object { $PSItem.Name -match "dbatoolsci_testjob" } $results.Enabled -contains $false | Should -Be $false } } @@ -83,7 +83,7 @@ Describe $CommandName -Tag IntegrationTests { } It "Should not return excluded job" { - $results = Get-DbaAgentJob -SqlInstance $TestConfig.instance2 -ExcludeJob dbatoolsci_testjob | Where-Object Name -match "dbatoolsci_testjob" + $results = Get-DbaAgentJob -SqlInstance $TestConfig.instance2 -ExcludeJob dbatoolsci_testjob | Where-Object { $PSItem.Name -match "dbatoolsci_testjob" } $results.Name -contains "dbatoolsci_testjob" | Should -Be $false } } @@ -104,7 +104,7 @@ Describe $CommandName -Tag IntegrationTests { } It "Should not return excluded job" { - $results = Get-DbaAgentJob -SqlInstance $TestConfig.instance2 -ExcludeCategory "Cat2" | Where-Object Name -match "dbatoolsci_testjob" + $results = Get-DbaAgentJob -SqlInstance $TestConfig.instance2 -ExcludeCategory "Cat2" | Where-Object { $PSItem.Name -match "dbatoolsci_testjob" } $results.Name -contains "dbatoolsci_testjob_cat2" | Should -Be $false } } diff --git a/tests/Get-DbaAgentJobHistory.Tests.ps1 b/tests/Get-DbaAgentJobHistory.Tests.ps1 index f9b2cad73f3d..da206a75b814 100644 --- a/tests/Get-DbaAgentJobHistory.Tests.ps1 +++ b/tests/Get-DbaAgentJobHistory.Tests.ps1 @@ -9,7 +9,7 @@ Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig Describe $CommandName -Tag UnitTests { - Context "Validate parameters" { + Context "Parameter validation" { BeforeAll { $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } $expectedParameters = $TestConfig.CommonParameters @@ -34,10 +34,9 @@ Describe $CommandName -Tag UnitTests { } } - Describe $CommandName -Tag UnitTests { BeforeAll { - InModuleScope dbatools { + InModuleScope "dbatools" { Mock Connect-DbaInstance -MockWith { # Thanks @Fred $obj = [PSCustomObject]@{ @@ -120,7 +119,7 @@ Describe $CommandName -Tag UnitTests { Context "Return values" { BeforeAll { - InModuleScope dbatools { + InModuleScope "dbatools" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ @@ -144,31 +143,28 @@ Describe $CommandName -Tag UnitTests { } It "Throws when ExcludeJobSteps and WithOutputFile" { - InModuleScope dbatools { + InModuleScope "dbatools" { { Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -ExcludeJobSteps -WithOutputFile -EnableException } | Should -Throw } } It "Returns full history by default" { - InModuleScope dbatools { - $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" - $Results.Status.Count | Should -Be 6 + InModuleScope "dbatools" { + $Results = @(Get-DbaAgentJobHistory -SqlInstance "SQLServerName") + $Results.Count | Should -Be 6 } } It "Returns only runs with no steps with ExcludeJobSteps" { - InModuleScope dbatools { - $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -ExcludeJobSteps - $Results.Status.Count | Should -Be 2 + InModuleScope "dbatools" { + $Results = @(Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -ExcludeJobSteps) + $Results.Count | Should -Be 2 } } It "Returns our own 'augmented' properties, too" { - InModuleScope dbatools { - $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -ExcludeJobSteps + InModuleScope "dbatools" { + $Results = @(Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -ExcludeJobSteps) $Results[0].psobject.properties.Name | Should -Contain "StartDate" $Results[0].psobject.properties.Name | Should -Contain "EndDate" $Results[0].psobject.properties.Name | Should -Contain "Duration" @@ -176,9 +172,8 @@ Describe $CommandName -Tag UnitTests { } It "Returns 'augmented' properties that are correct" { - InModuleScope dbatools { - $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -ExcludeJobSteps + InModuleScope "dbatools" { + $Results = @(Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -ExcludeJobSteps) $Results[0].StartDate | Should -Be $Results[0].RunDate $Results[0].RunDuration | Should -Be 112 $Results[0].Duration.TotalSeconds | Should -Be 72 @@ -187,14 +182,13 @@ Describe $CommandName -Tag UnitTests { } It "Figures out plain outputfiles" { - InModuleScope dbatools { - $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile + InModuleScope "dbatools" { + $Results = @(Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile) # no output for outcomes - ($Results | Where-Object StepID -eq 0).Status.Count | Should -Be 2 + ($Results | Where-Object StepID -eq 0).Count | Should -Be 2 ($Results | Where-Object StepID -eq 0).OutputFileName -Join "" | Should -Be "" # correct output for job1 - ($Results | Where-Object { $PSItem.StepID -ne 0 } | Where-Object JobName -eq "Job1").OutputFileName | Should -Match "Job1Output[12]" + ($Results | Where-Object StepID -ne 0 | Where-Object JobName -eq "Job1").OutputFileName | Should -Match "Job1Output[12]" # correct output for job2 ($Results | Where-Object StepID -eq 2 | Where-Object JobName -eq "Job2").OutputFileName | Should -Match "Job2Output1" ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job2").OutputFileName | Should -Be "" @@ -204,7 +198,7 @@ Describe $CommandName -Tag UnitTests { Context "SQL Agent Tokens" { It "Handles INST" { - InModuleScope dbatools { + InModuleScope "dbatools" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ @@ -214,15 +208,13 @@ Describe $CommandName -Tag UnitTests { } ) } - $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile - + $Results = @(Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile) ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "BASEServiceName__Job1Output1" } } It "Handles MACH" { - InModuleScope dbatools { + InModuleScope "dbatools" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ @@ -232,15 +224,13 @@ Describe $CommandName -Tag UnitTests { } ) } - $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile - + $Results = @(Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile) ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "BASEComputerName__Job1Output1" } } It "Handles SQLDIR" { - InModuleScope dbatools { + InModuleScope "dbatools" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ @@ -250,15 +240,13 @@ Describe $CommandName -Tag UnitTests { } ) } - $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile - + $Results = @(Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile) ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "BASEInstallDataDirectory__Job1Output1" } } It "Handles SQLLOGDIR" { - InModuleScope dbatools { + InModuleScope "dbatools" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ @@ -268,15 +256,13 @@ Describe $CommandName -Tag UnitTests { } ) } - $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile - - ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "BASEErrorLog_'_""_]_Path__Job1Output1" + $Results = @(Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile) + ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "BASEErrorLog_''_""_]_Path__Job1Output1" } } It "Handles SRVR" { - InModuleScope dbatools { + InModuleScope "dbatools" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ @@ -286,15 +272,13 @@ Describe $CommandName -Tag UnitTests { } ) } - $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile - + $Results = @(Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile) ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "BASEDomainInstanceName__Job1Output1" } } It "Handles STEPID" { - InModuleScope dbatools { + InModuleScope "dbatools" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ @@ -304,14 +288,13 @@ Describe $CommandName -Tag UnitTests { } ) } - $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile + $Results = @(Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile) ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "1__Job1Output1" } } It "Handles JOBID" { - InModuleScope dbatools { + InModuleScope "dbatools" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ @@ -321,15 +304,13 @@ Describe $CommandName -Tag UnitTests { } ) } - $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile - + $Results = @(Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile) ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "0x848A71E7438BD0468F8D4FC4464F9FC5__Job1Output1" } } It "Handles STRTDT" { - InModuleScope dbatools { + InModuleScope "dbatools" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ @@ -339,14 +320,13 @@ Describe $CommandName -Tag UnitTests { } ) } - $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile + $Results = @(Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile) ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "20170926__Job1Output1" } } It "Handles STRTTM" { - InModuleScope dbatools { + InModuleScope "dbatools" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ @@ -356,31 +336,29 @@ Describe $CommandName -Tag UnitTests { } ) } - $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile + $Results = @(Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile) ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "130000__Job1Output1" } } It "Handles DATE" { - InModuleScope dbatools { + InModuleScope "dbatools" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ Job = "Job1" StepId = 1 - OutputFileName = "$(DATE)__Job1Output1" + OutputFileName = "$(Get-Date)__Job1Output1" } ) } - $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile + $Results = @(Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile) ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "20170926__Job1Output1" } } It "Handles TIME" { - InModuleScope dbatools { + InModuleScope "dbatools" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ @@ -390,8 +368,7 @@ Describe $CommandName -Tag UnitTests { } ) } - $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile + $Results = @(Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile) ($Results | Where-Object StepID -eq 2 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "130001__Job1Output1" } } @@ -399,7 +376,7 @@ Describe $CommandName -Tag UnitTests { Context "SQL Agent escape sequences" { It "Handles ESCAPE_NONE" { - InModuleScope dbatools { + InModuleScope "dbatools" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ @@ -409,15 +386,13 @@ Describe $CommandName -Tag UnitTests { } ) } - $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile - - ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "BASEErrorLog_'_""_]_Path__Job1Output1" + $Results = @(Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile) + ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "BASEErrorLog_''_""_]_Path__Job1Output1" } } It "Handles ESCAPE_SQUOTE" { - InModuleScope dbatools { + InModuleScope "dbatools" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ @@ -427,15 +402,13 @@ Describe $CommandName -Tag UnitTests { } ) } - $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile - - ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "BASEErrorLog_''_""_]_Path__Job1Output1" + $Results = @(Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile) + ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "BASEErrorLog_''''_""_]_Path__Job1Output1" } } It "Handles ESCAPE_DQUOTE" { - InModuleScope dbatools { + InModuleScope "dbatools" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ @@ -445,15 +418,13 @@ Describe $CommandName -Tag UnitTests { } ) } - $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile - - ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "BASEErrorLog_'_""""_]_Path__Job1Output1" + $Results = @(Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile) + ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "BASEErrorLog_''_""""_]_Path__Job1Output1" } } It "Handles ESCAPE_RBRACKET" { - InModuleScope dbatools { + InModuleScope "dbatools" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ @@ -463,10 +434,8 @@ Describe $CommandName -Tag UnitTests { } ) } - $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile - - ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "BASEErrorLog_'_""_]]_Path__Job1Output1" + $Results = @(Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile) + ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "BASEErrorLog_''_""_]]_Path__Job1Output1" } } } diff --git a/tests/Get-DbaAgentLog.Tests.ps1 b/tests/Get-DbaAgentLog.Tests.ps1 index 3702dc9afb6a..2ce1a7e3f18a 100644 --- a/tests/Get-DbaAgentLog.Tests.ps1 +++ b/tests/Get-DbaAgentLog.Tests.ps1 @@ -9,7 +9,7 @@ Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig Describe $CommandName -Tag UnitTests { - Context "Parameter validation" { + Context "Validate parameters" { BeforeAll { $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } $expectedParameters = $TestConfig.CommonParameters @@ -38,11 +38,11 @@ Describe $CommandName -Tag IntegrationTests { } It "Results contain SQLServerAgent version" { - $results.text -like "`[100`] Microsoft SQLServerAgent version*" | Should -Be $true + ($results.text -like "`[100`] Microsoft SQLServerAgent version*") | Should -BeTrue } It "LogDate is a DateTime type" { - $($results | Select-Object -First 1).LogDate | Should -BeOfType DateTime + ($results | Select-Object -First 1).LogDate | Should -BeOfType DateTime } } diff --git a/tests/Get-DbaAvailabilityGroup.Tests.ps1 b/tests/Get-DbaAvailabilityGroup.Tests.ps1 index 041ca2ba7b1b..647d3a3aa051 100644 --- a/tests/Get-DbaAvailabilityGroup.Tests.ps1 +++ b/tests/Get-DbaAvailabilityGroup.Tests.ps1 @@ -5,7 +5,7 @@ param( $PSDefaultParameterValues = $TestConfig.Defaults ) -Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan +Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig Describe $CommandName -Tag UnitTests { @@ -33,9 +33,6 @@ Describe $CommandName -Tag IntegrationTests { # 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 - # Explain what needs to be set up for the test: - # We need to create an availability group to test the Get-DbaAvailabilityGroup command. - # Set variables. They are available in all the It blocks. $agName = "dbatoolsci_agroup" @@ -59,19 +56,19 @@ Describe $CommandName -Tag IntegrationTests { $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 + $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 "When getting availability groups" { + Context "When retrieving availability groups" { It "Returns results with proper data" { $results = Get-DbaAvailabilityGroup -SqlInstance $TestConfig.instance3 $results.AvailabilityGroup | Should -Contain $agName } - It "Returns a single result" { + It "Returns a single result when specifying availability group name" { $results = Get-DbaAvailabilityGroup -SqlInstance $TestConfig.instance3 -AvailabilityGroup $agName $results.AvailabilityGroup | Should -Be $agName } From dc6ffb175d10a8ecf801795d57ba229e3e0ae4ee Mon Sep 17 00:00:00 2001 From: Chrissy LeMaire Date: Mon, 11 Aug 2025 06:54:04 +0200 Subject: [PATCH 12/14] These cant be auto converted Refactored multiple test scripts to remove parameter blocks and redundant setup, streamline parameter validation, and use more concise and modern Pester syntax. The changes improve readability and maintainability by reducing boilerplate and making test logic clearer. --- tests/Find-DbaAgentJob.Tests.ps1 | 212 ++------ tests/Format-DbaBackupInformation.Tests.ps1 | 236 +++------ tests/Get-DbaAgentJob.Tests.ps1 | 99 ++-- tests/Get-DbaAgentJobHistory.Tests.ps1 | 539 +++++++++----------- tests/Get-DbaAgentLog.Tests.ps1 | 53 +- 5 files changed, 428 insertions(+), 711 deletions(-) diff --git a/tests/Find-DbaAgentJob.Tests.ps1 b/tests/Find-DbaAgentJob.Tests.ps1 index 2ae0c565569a..b28e4a089dd9 100644 --- a/tests/Find-DbaAgentJob.Tests.ps1 +++ b/tests/Find-DbaAgentJob.Tests.ps1 @@ -1,203 +1,91 @@ -#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } -param( - $ModuleName = "dbatools", - $CommandName = "Find-DbaAgentJob", - $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", - "JobName", - "ExcludeJobName", - "StepName", - "LastUsed", - "IsDisabled", - "IsFailed", - "IsNotScheduled", - "IsNoEmailNotification", - "Category", - "Owner", - "Since", - "EnableException" - ) - } - - It "Should have the expected parameters" { - Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty +$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan +$global:TestConfig = Get-TestConfig + +Describe "$CommandName Unit Tests" -Tag 'UnitTests' { + Context "Validate parameters" { + [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} + [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'JobName', 'ExcludeJobName', 'StepName', 'LastUsed', 'IsDisabled', 'IsFailed', 'IsNotScheduled', 'IsNoEmailNotification', 'Category', 'Owner', 'Since', 'EnableException' + $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters + It "Should only contain our specific parameters" { + (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 } } } -Describe $CommandName -Tag IntegrationTests { +Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { + Context "Command finds jobs using all parameters" { 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 - #subsystemServer needs the real underlying name, and it doesn't work if targeting something like localhost\namedinstance # the typical error would be WARNING: [17:19:26][New-DbaAgentJobStep] Something went wrong creating the job step | The specified '@server' is #invalid (valid values are returned by sp_helpserver). $srvName = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Query "select @@servername as sn" -as PSObject - - $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job "dbatoolsci_testjob" -OwnerLogin "sa" - - $splatJobStep1 = @{ - SqlInstance = $TestConfig.instance2 - Job = "dbatoolsci_testjob" - StepId = 1 - StepName = "dbatoolsci Failed" - Subsystem = "TransactSql" - SubsystemServer = $srvName.sn - Command = "RAISERROR (15600,-1,-1, 'dbatools_error');" - CmdExecSuccessCode = 0 - OnSuccessAction = "QuitWithSuccess" - OnFailAction = "QuitWithFailure" - Database = "master" - RetryAttempts = 1 - RetryInterval = 2 - } - $null = New-DbaAgentJobStep @splatJobStep1 - - $null = Start-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job "dbatoolsci_testjob" - - $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job "dbatoolsregr_testjob" -OwnerLogin "sa" - - $splatJobStep2 = @{ - SqlInstance = $TestConfig.instance2 - Job = "dbatoolsregr_testjob" - StepId = 1 - StepName = "dbatoolsci Failed" - Subsystem = "TransactSql" - SubsystemServer = $srvName.sn - Command = "RAISERROR (15600,-1,-1, 'dbatools_error');" - CmdExecSuccessCode = 0 - OnSuccessAction = "QuitWithSuccess" - OnFailAction = "QuitWithFailure" - Database = "master" - RetryAttempts = 1 - RetryInterval = 2 - } - $null = New-DbaAgentJobStep @splatJobStep2 - - $null = New-DbaAgentJobCategory -SqlInstance $TestConfig.instance2 -Category "dbatoolsci_job_category" -CategoryType LocalJob - $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job "dbatoolsci_testjob_disabled" -Category "dbatoolsci_job_category" -Disabled - - $splatJobStep3 = @{ - SqlInstance = $TestConfig.instance2 - Job = "dbatoolsci_testjob_disabled" - StepId = 1 - StepName = "dbatoolsci Test Step" - Subsystem = "TransactSql" - SubsystemServer = $srvName.sn - Command = "SELECT * FROM master.sys.all_columns" - CmdExecSuccessCode = 0 - OnSuccessAction = "QuitWithSuccess" - OnFailAction = "QuitWithFailure" - Database = "master" - RetryAttempts = 1 - RetryInterval = 2 - } - $null = New-DbaAgentJobStep @splatJobStep3 - - # 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') + $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job 'dbatoolsci_testjob' -OwnerLogin 'sa' + $null = New-DbaAgentJobStep -SqlInstance $TestConfig.instance2 -Job 'dbatoolsci_testjob' -StepId 1 -StepName 'dbatoolsci Failed' -Subsystem TransactSql -SubsystemServer $srvName.sn -Command "RAISERROR (15600,-1,-1, 'dbatools_error');" -CmdExecSuccessCode 0 -OnSuccessAction QuitWithSuccess -OnFailAction QuitWithFailure -Database master -RetryAttempts 1 -RetryInterval 2 + $null = Start-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job 'dbatoolsci_testjob' + $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job 'dbatoolsregr_testjob' -OwnerLogin 'sa' + $null = New-DbaAgentJobStep -SqlInstance $TestConfig.instance2 -Job 'dbatoolsregr_testjob' -StepId 1 -StepName 'dbatoolsci Failed' -Subsystem TransactSql -SubsystemServer $srvName.sn -Command "RAISERROR (15600,-1,-1, 'dbatools_error');" -CmdExecSuccessCode 0 -OnSuccessAction QuitWithSuccess -OnFailAction QuitWithFailure -Database master -RetryAttempts 1 -RetryInterval 2 + $null = New-DbaAgentJobCategory -SqlInstance $TestConfig.instance2 -Category 'dbatoolsci_job_category' -CategoryType LocalJob + $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job 'dbatoolsci_testjob_disabled' -Category 'dbatoolsci_job_category' -Disabled + $null = New-DbaAgentJobStep -SqlInstance $TestConfig.instance2 -Job 'dbatoolsci_testjob_disabled' -StepId 1 -StepName 'dbatoolsci Test Step' -Subsystem TransactSql -SubsystemServer $srvName.sn -Command 'SELECT * FROM master.sys.all_columns' -CmdExecSuccessCode 0 -OnSuccessAction QuitWithSuccess -OnFailAction QuitWithFailure -Database master -RetryAttempts 1 -RetryInterval 2 } - 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 - - $splatRemoveJob = @{ - SqlInstance = $TestConfig.instance2 - Job = @("dbatoolsci_testjob", "dbatoolsregr_testjob", "dbatoolsci_testjob_disabled") - Confirm = $false - } - $null = Remove-DbaAgentJob @splatRemoveJob - - $null = Remove-DbaAgentJobCategory -SqlInstance $TestConfig.instance2 -Category "dbatoolsci_job_category" -Confirm $false - - # As this is the last block we do not need to reset the $PSDefaultParameterValues. + $null = Remove-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob, dbatoolsregr_testjob, dbatoolsci_testjob_disabled -Confirm:$false + $null = Remove-DbaAgentJobCategory -SqlInstance $TestConfig.instance2 -Category 'dbatoolsci_job_category' -Confirm:$false } + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob It "Should find a specific job" { - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -JobName "dbatoolsci_testjob" - $results.name | Should -Be "dbatoolsci_testjob" + $results.name | Should Be "dbatoolsci_testjob" } - + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job *dbatoolsci* -ExcludeJobName dbatoolsci_testjob_disabled It "Should find a specific job but not an excluded job" { - $splatFindExclude = @{ - SqlInstance = $TestConfig.instance2 - JobName = "*dbatoolsci*" - ExcludeJobName = "dbatoolsci_testjob_disabled" - } - $results = Find-DbaAgentJob @splatFindExclude - $results.name | Should -Not -Be "dbatoolsci_testjob_disabled" + $results.name | Should Not Be "dbatoolsci_testjob_disabled" } - + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -StepName 'dbatoolsci Test Step' It "Should find a specific job with a specific step" { - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -StepName "dbatoolsci Test Step" - $results.name | Should -Be "dbatoolsci_testjob_disabled" + $results.name | Should Be "dbatoolsci_testjob_disabled" } - + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -LastUsed 10 It "Should find jobs not used in the last 10 days" { - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -LastUsed 10 - $results | Should -Not -BeNullOrEmpty + $results | Should not be null } - + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsDisabled It "Should find jobs disabled from running" { - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsDisabled - $results.name | Should -Be "dbatoolsci_testjob_disabled" + $results.name | Should be "dbatoolsci_testjob_disabled" } - + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsDisabled It "Should find 1 job disabled from running" { - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsDisabled - $results.Status.Count | Should -Be 1 + $results.count | Should be 1 } - + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsNotScheduled It "Should find jobs that have not been scheduled" { - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsNotScheduled - $results | Should -Not -BeNullOrEmpty + $results | Should not be null } - + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsNotScheduled -Job *dbatoolsci* It "Should find 2 jobs that have no schedule" { - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsNotScheduled -JobName "*dbatoolsci*" - $results.Status.Count | Should -Be 2 + $results.count | Should be 2 } - + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsNoEmailNotification It "Should find jobs that have no email notification" { - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsNoEmailNotification - $results | Should -Not -BeNullOrEmpty + $results | Should not be null } - + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Category 'dbatoolsci_job_category' It "Should find jobs that have a category of dbatoolsci_job_category" { - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Category "dbatoolsci_job_category" - $results.name | Should -Be "dbatoolsci_testjob_disabled" + $results.name | Should be "dbatoolsci_testjob_disabled" } - + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Owner 'sa' It "Should find jobs that are owned by sa" { - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Owner "sa" - $results | Should -Not -BeNullOrEmpty + $results | Should not be null } - + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsFailed -Since '2016-07-01 10:47:00' It "Should find jobs that have been failed since July of 2016" { - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsFailed -Since "2016-07-01 10:47:00" - $results | Should -Not -BeNullOrEmpty + $results | Should not be null } - + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job *dbatoolsci*,*dbatoolsregr* -ExcludeJobName dbatoolsci_testjob_disabled It "Should work with multiple wildcard passed in (see #9572)" { - $splatMultiWildcard = @{ - SqlInstance = $TestConfig.instance2 - JobName = @("*dbatoolsci*", "*dbatoolsregr*") - ExcludeJobName = "dbatoolsci_testjob_disabled" - } - $results = Find-DbaAgentJob @splatMultiWildcard - $results.Status.Count | Should -Be 2 + $results.Count | Should -Be 2 } } -} \ No newline at end of file +} diff --git a/tests/Format-DbaBackupInformation.Tests.ps1 b/tests/Format-DbaBackupInformation.Tests.ps1 index e2fd3929915d..824d703e99bb 100644 --- a/tests/Format-DbaBackupInformation.Tests.ps1 +++ b/tests/Format-DbaBackupInformation.Tests.ps1 @@ -1,245 +1,179 @@ -#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } -param( - $ModuleName = "dbatools", - $CommandName = "Format-DbaBackupInformation", - $PSDefaultParameterValues = $TestConfig.Defaults -) - +$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -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 += @( - "BackupHistory", - "ReplaceDatabaseName", - "ReplaceDbNameInFile", - "DataFileDirectory", - "LogFileDirectory", - "DestinationFileStreamDirectory", - "DatabaseNamePrefix", - "DatabaseFilePrefix", - "DatabaseFileSuffix", - "RebaseBackupFolder", - "Continue", - "FileMapping", - "PathSep", - "EnableException" - ) - } - - It "Should have the expected parameters" { - Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty +Describe "$CommandName Unit Tests" -Tag 'UnitTests' { + Context "Validate parameters" { + [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 } } } -Describe $CommandName -Tag IntegrationTests { - Context "Rename a Database" { - BeforeAll { - $History = Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\ContinuePointTest.xml - $output = $History | Format-DbaBackupInformation -ReplaceDatabaseName "Pester" - } +Describe "$CommandName Integration Tests" -Tags 'IntegrationTests' { + Context "Rename a Database" { + $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 { $PSItem.Database -ne "Pester" }).Count | Should -BeExactly 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 { $PSItem.PhysicalName -like "*ContinuePointTest*" }).Count | Should -BeExactly 0 + ($output | Select-Object -ExpandProperty filelist | Where-Object {$_.PhysicalName -like '*ContinuePointTest*'}).count } + } Context "Test it works as a parameter as well" { - BeforeAll { - $History = Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\ContinuePointTest.xml - $output = Format-DbaBackupInformation -BackupHistory $History -ReplaceDatabaseName "Pester" - } - + $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 { $PSItem.Database -ne "Pester" }).Count | Should -BeExactly 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 { $PSItem.PhysicalName -like "*ContinuePointTest*" }).Count | Should -BeExactly 0 + ($out | Select-Object -ExpandProperty filelist | Where-Object {$_.PhysicalName -like 'ContinuePointTest'}).count | Should Be 0 } } Context "Rename 2 dbs using a hash" { - BeforeAll { - $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" } - } - + $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'} It "Should have no databases other than spiggy and eldritch" { - ($output | Where-Object { $PSItem.Database -notin ("Spiggy", "Eldritch") }).Count | Should -BeExactly 0 + ($output | Where-Object {$_.Database -notin ('Spiggy', 'Eldritch')}).count | Should be 0 } - It "Should have renamed all RestoreTimeCleans to Eldritch" { - ($output | Where-Object { $PSItem.OriginalDatabase -eq "RestoreTimeClean" } | Where-Object { $PSItem.Database -ne "Eldritch" }).Count | Should -BeExactly 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" { - ($output | Where-Object { $PSItem.OriginalDatabase -eq "RestoreTimeClean" } | Select-Object -ExpandProperty filelist | Where-Object { $PSItem.PhysicalName -like "*RestoreTimeClean*" }).Count | Should -BeExactly 0 - ($output | Where-Object { $PSItem.OriginalDatabase -eq "RestoreTimeClean" } | Select-Object -ExpandProperty filelist | Where-Object { $PSItem.PhysicalName -like "*eldritch*" }).Count | Should -BeExactly ($output | Where-Object { $PSItem.OriginalDatabase -eq "RestoreTimeClean" } | 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 { $PSItem.OriginalDatabase -eq "ContinuePointTest" } | Where-Object { $PSItem.Database -ne "Spiggy" }).Count | Should -BeExactly 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" { - ($output | Where-Object { $PSItem.OriginalDatabase -eq "ContinuePointTest" } | Select-Object -ExpandProperty filelist | Where-Object { $PSItem.PhysicalName -like "*ContinuePointTest*" }).Count | Should -BeExactly 0 - ($output | Where-Object { $PSItem.OriginalDatabase -eq "ContinuePointTest" } | Select-Object -ExpandProperty filelist | Where-Object { $PSItem.PhysicalName -like "*spiggy*" }).Count | Should -BeExactly ($output | Where-Object { $PSItem.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 + } } Context "Rename 1 dbs using a hash" { - BeforeAll { - $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" } - } - - It "Should have no databases other than RestoreTimeClean and Alice" { - ($output | Where-Object { $PSItem.Database -notin ("RestoreTimeClean", "Alice") }).Count | Should -BeExactly 0 + $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'} + It "Should have no databases other than spiggy and eldritch" { + ($output | Where-Object {$_.Database -notin ('RestoreTimeClean', 'Alice')}).count | Should be 0 } - It "Should have left RestoreTimeClean alone" { - ($output | Where-Object { $PSItem.OriginalDatabase -eq "RestoreTimeClean" } | Where-Object { $PSItem.Database -ne "RestoreTimeClean" }).Count | Should -BeExactly 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 { $PSItem.OriginalDatabase -eq "ContinuePointTest" } | Where-Object { $PSItem.Database -ne "Alice" }).Count | Should -BeExactly 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 { $PSItem.OriginalDatabase -eq "ContinuePointTest" } | Select-Object -ExpandProperty filelist | Where-Object { $PSItem.PhysicalName -like "*ContinuePointTest*" }).Count | Should -BeExactly 0 - ($output | Where-Object { $PSItem.OriginalDatabase -eq "ContinuePointTest" } | Select-Object -ExpandProperty filelist | Where-Object { $PSItem.PhysicalName -like "*alice*" }).Count | Should -BeExactly ($output | Where-Object { $PSItem.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 } } Context "Check DB Name prefix and suffix" { - BeforeAll { - $History = Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\ContinuePointTest.xml - $output = $History | Format-DbaBackupInformation -DatabaseNamePrefix PREFIX - } - + $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 { $PSItem.Database -like "PREFIX*" }).Count | Should -BeExactly $output.Count + ($Output | Where-Object {$_.Database -like 'PREFIX*'}).count | Should be $output.count } + } Context "Check DataFileDirectory moves all files" { - BeforeAll { - $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 -DataFileDirectory c:\restores - } + $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 -DataFileDirectory c:\restores It "Should have move ALL files to c:\restores\" { - (($output | Select-Object -ExpandProperty Filelist).PhysicalName | Split-Path | Where-Object { $PSItem -ne "c:\restores" }).Count | Should -BeExactly 0 + (($Output | Select-Object -ExpandProperty Filelist).PhysicalName | split-path | Where-Object {$_ -ne 'c:\restores'}).count | Should Be 0 } } Context "Check DataFileDirectory and LogFileDirectory work independently" { - BeforeAll { - $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 -DataFileDirectory c:\restores\ -LogFileDirectory c:\logs - } + $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 -DataFileDirectory c:\restores\ -LogFileDirectory c:\logs - It "Should have moved all data files to c:\restores\" { - (($output | Select-Object -ExpandProperty Filelist | Where-Object { $PSItem.Type -eq "D" }).PhysicalName | Split-Path | Where-Object { $PSItem -ne "c:\restores" }).Count | Should -BeExactly 0 + 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 } - It "Should have moved all log files to c:\logs\" { - (($output | Select-Object -ExpandProperty Filelist | Where-Object { $PSItem.Type -eq "L" }).PhysicalName | Split-Path | Where-Object { $PSItem -ne "c:\logs" }).Count | Should -BeExactly 0 + (($Output | Select-Object -ExpandProperty Filelist | Where-Object {$_.Type -eq 'L'}).PhysicalName | split-path | Where-Object {$_ -ne 'c:\logs'}).count | Should Be 0 } } Context "Check LogFileDirectory works for just logfiles" { - BeforeAll { - $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 -DataFileDirectory c:\restores\ -LogFileDirectory c:\logs - } + $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 -DataFileDirectory c:\restores\ -LogFileDirectory c:\logs - It "Should not have moved all data files to c:\logs\" { - (($output | Select-Object -ExpandProperty Filelist | Where-Object { $PSItem.Type -eq "D" }).PhysicalName | Split-Path | Where-Object { $PSItem -eq "c:\logs" }).Count | Should -BeExactly 0 + 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 } - It "Should have moved all log files to c:\logs\" { - (($output | Select-Object -ExpandProperty Filelist | Where-Object { $PSItem.Type -eq "L" }).PhysicalName | Split-Path | Where-Object { $PSItem -ne "c:\logs" }).Count | Should -BeExactly 0 + (($Output | Select-Object -ExpandProperty Filelist | Where-Object {$_.Type -eq 'L'}).PhysicalName | split-path | Where-Object {$_ -ne 'c:\logs'}).count | Should Be 0 } } Context "Test RebaseBackupFolder" { - BeforeAll { - $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 -RebaseBackupFolder c:\backups\ - } + $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 -RebaseBackupFolder c:\backups\ - It "Should have moved all backup files to c:\backups" { - ($output | Select-Object -ExpandProperty FullName | Split-Path | Where-Object { $PSItem -eq "c:\backups" }).Count | Should -BeExactly $History.Count + 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 } + } Context "Test PathSep" { - BeforeAll { - $History = Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\ContinuePointTest.xml - $History += Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\RestoreTimeClean.xml - } - + $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 -RebaseBackupFolder 'c:\backups' It "Should not have changed the default path separator" { - $output = Format-DbaBackupInformation -BackupHistory $History -RebaseBackupFolder "c:\backups" - ($output | Select-Object -ExpandProperty FullName | Split-Path | Where-Object { $PSItem -eq "c:\backups" }).Count | Should -BeExactly $History.Count + ($Output | Select-Object -ExpandProperty FullName | split-path | Where-Object {$_ -eq 'c:\backups'}).count | Should Be $History.count } - - It "Should not have changed the default path separator even when passed explicitly" { - $output = Format-DbaBackupInformation -BackupHistory $History -RebaseBackupFolder "c:\backups" -PathSep "\" - ($output | Select-Object -ExpandProperty FullName | Split-Path | Where-Object { $PSItem -eq "c:\backups" }).Count | Should -BeExactly $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 = Format-DbaBackupInformation -BackupHistory $History -RebaseBackupFolder '/opt/mssql/backups' -PathSep '/' It "Should have changed the path separator as instructed" { - $output = Format-DbaBackupInformation -BackupHistory $History -RebaseBackupFolder "/opt/mssql/backups" -PathSep "/" - $result = $output | Select-Object -ExpandProperty FullName | ForEach-Object { - $all = $PSItem.Split("/") - $all[0..($all.Length - 2)] -Join "/" - } - ($result | Where-Object { $PSItem -eq "/opt/mssql/backups" }).Count | Should -BeExactly $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 } } Context "Test everything all at once" { - BeforeAll { - $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\ - } - + $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 { $PSItem.Database -ne "Pester" }).Count | Should -BeExactly 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 { $PSItem.PhysicalName -like "*ContinuePointTest*" }).Count | Should -BeExactly 0 + ($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 { $PSItem.Type -eq "D" }).PhysicalName | Split-Path | Where-Object { $PSItem -ne "c:\restores" }).Count | Should -BeExactly 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 { $PSItem.Type -eq "L" }).PhysicalName | Split-Path | Where-Object { $PSItem -ne "c:\logs" }).Count | Should -BeExactly 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 have moved all backup files to c:\backups" { - ($output | Select-Object -ExpandProperty FullName | Split-Path | Where-Object { $PSItem -eq "c:\backups" }).Count | Should -BeExactly $History.Count + 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 } + } } \ No newline at end of file diff --git a/tests/Get-DbaAgentJob.Tests.ps1 b/tests/Get-DbaAgentJob.Tests.ps1 index 1c65972c259e..d5c41b23cc61 100644 --- a/tests/Get-DbaAgentJob.Tests.ps1 +++ b/tests/Get-DbaAgentJob.Tests.ps1 @@ -1,114 +1,81 @@ -#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } -param( - $ModuleName = "dbatools", - $CommandName = "Get-DbaAgentJob", - $PSDefaultParameterValues = $TestConfig.Defaults -) - -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan +$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -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" - ) - } +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' - It "Should have the expected parameters" { - Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty + It "Should only contain our specific parameters" { + Compare-Object -ReferenceObject $knownParameters -DifferenceObject $params | Should -BeNullOrEmpty } } } -Describe $CommandName -Tag IntegrationTests { +Describe "$commandname Integration Tests" -Tags "IntegrationTests" { Context "Command gets jobs" { BeforeAll { $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob_disabled -Disabled } - AfterAll { $null = Remove-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob, dbatoolsci_testjob_disabled -Confirm:$false } - + $results = Get-DbaAgentJob -SqlInstance $TestConfig.instance2 | Where-Object { $_.Name -match "dbatoolsci_testjob" } It "Should get 2 dbatoolsci jobs" { - $results = Get-DbaAgentJob -SqlInstance $TestConfig.instance2 | Where-Object { $PSItem.Name -match "dbatoolsci_testjob" } - $results.Count | Should -Be 2 + $results.count | Should Be 2 } - + $results = Get-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob It "Should get a specific job" { - $results = Get-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob - $results.Name | Should -Be "dbatoolsci_testjob" + $results.name | Should Be "dbatoolsci_testjob" } - } + } Context "Command gets no disabled jobs" { BeforeAll { $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob_disabled -Disabled } - AfterAll { $null = Remove-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob, dbatoolsci_testjob_disabled -Confirm:$false } - + $results = Get-DbaAgentJob -SqlInstance $TestConfig.instance2 -ExcludeDisabledJobs | Where-Object { $_.Name -match "dbatoolsci_testjob" } It "Should return only enabled jobs" { - $results = Get-DbaAgentJob -SqlInstance $TestConfig.instance2 -ExcludeDisabledJobs | Where-Object { $PSItem.Name -match "dbatoolsci_testjob" } - $results.Enabled -contains $false | Should -Be $false + $results.enabled -contains $False | Should Be $False } } - Context "Command doesn't get excluded job" { BeforeAll { $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob_disabled -Disabled } - AfterAll { $null = Remove-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob, dbatoolsci_testjob_disabled -Confirm:$false } - + $results = Get-DbaAgentJob -SqlInstance $TestConfig.instance2 -ExcludeJob dbatoolsci_testjob | Where-Object { $_.Name -match "dbatoolsci_testjob" } It "Should not return excluded job" { - $results = Get-DbaAgentJob -SqlInstance $TestConfig.instance2 -ExcludeJob dbatoolsci_testjob | Where-Object { $PSItem.Name -match "dbatoolsci_testjob" } - $results.Name -contains "dbatoolsci_testjob" | Should -Be $false + $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 = Get-DbaAgentJob -SqlInstance $TestConfig.instance2 -ExcludeCategory "Cat2" | Where-Object { $PSItem.Name -match "dbatoolsci_testjob" } - $results.Name -contains "dbatoolsci_testjob_cat2" | Should -Be $false + $results.name -contains "dbatoolsci_testjob_cat2" | Should Be $False } } - Context "Command gets jobs when databases are specified" { BeforeAll { $jobName1 = "dbatoolsci_dbfilter_$(Get-Random)" @@ -123,29 +90,23 @@ Describe $CommandName -Tag IntegrationTests { $null = New-DbaAgentJobStep -SqlInstance $TestConfig.instance2 -Job $jobName2 -StepName "TSQL-y" -Subsystem TransactSql -Database "model" $null = New-DbaAgentJobStep -SqlInstance $TestConfig.instance2 -Job $jobName2 -StepName "TSQL-z" -Subsystem TransactSql -Database "master" } - AfterAll { $null = Remove-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job $jobName1, $jobName2 -Confirm:$false } - + $resultSingleDatabase = Get-DbaAgentJob -SqlInstance $TestConfig.instance2 -Database tempdb It "Returns result with single database" { - $resultSingleDatabase = Get-DbaAgentJob -SqlInstance $TestConfig.instance2 -Database tempdb $resultSingleDatabase.Count | Should -BeGreaterOrEqual 1 } - It "Returns job result for Database: tempdb" { - $resultSingleDatabase = Get-DbaAgentJob -SqlInstance $TestConfig.instance2 -Database tempdb - $resultSingleDatabase.Name -contains $jobName1 | Should -BeTrue + $resultSingleDatabase.name -contains $jobName1 | Should -BeTrue } + $resultMultipleDatabases = Get-DbaAgentJob -SqlInstance $TestConfig.instance2 -Database tempdb, model It "Returns both jobs with double database" { - $resultMultipleDatabases = Get-DbaAgentJob -SqlInstance $TestConfig.instance2 -Database tempdb, model $resultMultipleDatabases.Count | Should -BeGreaterOrEqual 2 } - It "Includes job result for Database: model" { - $resultMultipleDatabases = Get-DbaAgentJob -SqlInstance $TestConfig.instance2 -Database tempdb, model - $resultMultipleDatabases.Name -contains $jobName2 | Should -BeTrue + $resultMultipleDatabases.name -contains $jobName2 | Should -BeTrue } } -} \ No newline at end of file +} diff --git a/tests/Get-DbaAgentJobHistory.Tests.ps1 b/tests/Get-DbaAgentJobHistory.Tests.ps1 index da206a75b814..862a38dc0ff6 100644 --- a/tests/Get-DbaAgentJobHistory.Tests.ps1 +++ b/tests/Get-DbaAgentJobHistory.Tests.ps1 @@ -1,441 +1,398 @@ -#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } -param( - $ModuleName = "dbatools", - $CommandName = "Get-DbaAgentJobHistory", - $PSDefaultParameterValues = $TestConfig.Defaults -) - +$commandname = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -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", - "StartDate", - "EndDate", - "OutcomeType", - "ExcludeJobSteps", - "WithOutputFile", - "JobCollection", - "EnableException" - ) - } - - It "Should have the expected parameters" { - Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty +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', 'StartDate', 'EndDate', 'OutcomeType', 'ExcludeJobSteps', 'WithOutputFile', 'JobCollection', '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 { - BeforeAll { - InModuleScope "dbatools" { - Mock Connect-DbaInstance -MockWith { - # Thanks @Fred - $obj = [PSCustomObject]@{ - Name = "BASEName" - ComputerName = "BASEComputerName" - InstanceName = "BASEInstanceName" - DomainInstanceName = "BASEDomainInstanceName" - InstallDataDirectory = "BASEInstallDataDirectory" - ErrorLogPath = "BASEErrorLog_{0}_{1}_{2}_Path" -f "'", '"', ']' - ServiceName = "BASEServiceName" - JobServer = New-Object PSObject - ConnectionContext = New-Object PSObject - } - Add-Member -InputObject $obj.ConnectionContext -Name ConnectionString -MemberType NoteProperty -Value "put=an=equal=in=it" - Add-Member -InputObject $obj.JobServer -Name EnumJobHistory -MemberType ScriptMethod -Value { - param ($filter) - return @( - @{ - JobName = "Job1" - JobID = [guid]"E7718A84-8B43-46D0-8F8D-4FC4464F9FC5" - StepID = 0 - StepName = "(Job outcome)" - RunDate = [DateTime]::Parse("2017-09-26T13:00:00") - RunDuration = 112 - RunStatus = 0 - }, - @{ - JobName = "Job1" - JobID = [guid]"E7718A84-8B43-46D0-8F8D-4FC4464F9FC5" - StepID = 1 - StepName = "Job1Step1" - RunDate = [DateTime]::Parse("2017-09-26T13:00:00") - RunDuration = 1 - RunStatus = 0 - }, - @{ - JobName = "Job1" - JobID = [guid]"E7718A84-8B43-46D0-8F8D-4FC4464F9FC5" - StepID = 2 - StepName = "Job1Step2" - RunDate = [DateTime]::Parse("2017-09-26T13:00:01") - RunDuration = 1 - RunStatus = 0 - }, - @{ - JobName = "Job2" - JobID = [guid]"9C9A6819-58CE-451A-8DD7-6D17593F0DFA" - StepID = 0 - StepName = "(Job outcome)" - RunDate = [DateTime]::Parse("2017-09-26T01:00:00") - RunDuration = 2 - RunStatus = 0 - }, - @{ - JobName = "Job2" - JobID = [guid]"9C9A6819-58CE-451A-8DD7-6D17593F0DFA" - StepID = 1 - StepName = "Job2Step1" - RunDate = [DateTime]::Parse("2017-09-26T01:00:00") - RunDuration = 1 - RunStatus = 0 - }, - @{ - JobName = "Job2" - JobID = [guid]"9C9A6819-58CE-451A-8DD7-6D17593F0DFA" - StepID = 2 - StepName = "Job2Step2" - RunDate = [DateTime]::Parse("2017-09-26T01:00:01") - RunDuration = 1 - RunStatus = 0 - } - ) - } - $obj.PSObject.TypeNames.Clear() - $obj.PSObject.TypeNames.Add("Microsoft.SqlServer.Management.Smo.Server") - return $obj - } #mock Connect-DbaInstance - } - } - Context "Return values" { - BeforeAll { - InModuleScope "dbatools" { - Mock Get-DbaAgentJobOutputFile -MockWith { - @( - @{ - Job = "Job1" - StepId = 1 - OutputFileName = "Job1Output1" - }, - @{ - Job = "Job1" - StepId = 2 - OutputFileName = "Job1Output2" - }, - @{ - Job = "Job2" - StepId = 2 - OutputFileName = "Job2Output1" - } - ) - } +Describe "$CommandName Unittests" -Tag 'UnitTests' { + InModuleScope 'dbatools' { + Mock Connect-DbaInstance -MockWith { + # Thanks @Fred + $obj = [PSCustomObject]@{ + Name = 'BASEName' + ComputerName = 'BASEComputerName' + InstanceName = 'BASEInstanceName' + DomainInstanceName = 'BASEDomainInstanceName' + InstallDataDirectory = 'BASEInstallDataDirectory' + ErrorLogPath = 'BASEErrorLog_{0}_{1}_{2}_Path' -f "'", '"', ']' + ServiceName = 'BASEServiceName' + JobServer = New-Object PSObject + ConnectionContext = New-Object PSObject } - } - - It "Throws when ExcludeJobSteps and WithOutputFile" { - InModuleScope "dbatools" { - { Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -ExcludeJobSteps -WithOutputFile -EnableException } | Should -Throw + Add-Member -InputObject $obj.ConnectionContext -Name ConnectionString -MemberType NoteProperty -Value 'put=an=equal=in=it' + Add-Member -InputObject $obj.JobServer -Name EnumJobHistory -MemberType ScriptMethod -Value { + param ($filter) + return @( + @{ + JobName = 'Job1' + JobID = [guid]'E7718A84-8B43-46D0-8F8D-4FC4464F9FC5' + StepID = 0 + StepName = '(Job outcome)' + RunDate = [DateTime]::Parse('2017-09-26T13:00:00') + RunDuration = 112 + RunStatus = 0 + }, + @{ + JobName = 'Job1' + JobID = [guid]'E7718A84-8B43-46D0-8F8D-4FC4464F9FC5' + StepID = 1 + StepName = 'Job1Step1' + RunDate = [DateTime]::Parse('2017-09-26T13:00:00') + RunDuration = 1 + RunStatus = 0 + }, + @{ + JobName = 'Job1' + JobID = [guid]'E7718A84-8B43-46D0-8F8D-4FC4464F9FC5' + StepID = 2 + StepName = 'Job1Step2' + RunDate = [DateTime]::Parse('2017-09-26T13:00:01') + RunDuration = 1 + RunStatus = 0 + }, + @{ + JobName = 'Job2' + JobID = [guid]'9C9A6819-58CE-451A-8DD7-6D17593F0DFA' + StepID = 0 + StepName = '(Job outcome)' + RunDate = [DateTime]::Parse('2017-09-26T01:00:00') + RunDuration = 2 + RunStatus = 0 + }, + @{ + JobName = 'Job2' + JobID = [guid]'9C9A6819-58CE-451A-8DD7-6D17593F0DFA' + StepID = 1 + StepName = 'Job2Step1' + RunDate = [DateTime]::Parse('2017-09-26T01:00:00') + RunDuration = 1 + RunStatus = 0 + }, + @{ + JobName = 'Job2' + JobID = [guid]'9C9A6819-58CE-451A-8DD7-6D17593F0DFA' + StepID = 2 + StepName = 'Job2Step2' + RunDate = [DateTime]::Parse('2017-09-26T01:00:01') + RunDuration = 1 + RunStatus = 0 + } + ) } - } + $obj.PSObject.TypeNames.Clear() + $obj.PSObject.TypeNames.Add("Microsoft.SqlServer.Management.Smo.Server") + return $obj + } #mock Connect-DbaInstance + Context "Return values" { - It "Returns full history by default" { - InModuleScope "dbatools" { - $Results = @(Get-DbaAgentJobHistory -SqlInstance "SQLServerName") - $Results.Count | Should -Be 6 + Mock Get-DbaAgentJobOutputFile -MockWith { + @( + @{ + Job = 'Job1' + StepId = 1 + OutputFileName = 'Job1Output1' + }, + @{ + Job = 'Job1' + StepId = 2 + OutputFileName = 'Job1Output2' + }, + @{ + Job = 'Job2' + StepId = 2 + OutputFileName = 'Job2Output1' + } + ) } - } - - It "Returns only runs with no steps with ExcludeJobSteps" { - InModuleScope "dbatools" { - $Results = @(Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -ExcludeJobSteps) - $Results.Count | Should -Be 2 + It "Throws when ExcludeJobSteps and WithOutputFile" { + { Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -ExcludeJobSteps -WithOutputFile -EnableException } | Should Throw } - } - - It "Returns our own 'augmented' properties, too" { - InModuleScope "dbatools" { - $Results = @(Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -ExcludeJobSteps) - $Results[0].psobject.properties.Name | Should -Contain "StartDate" - $Results[0].psobject.properties.Name | Should -Contain "EndDate" - $Results[0].psobject.properties.Name | Should -Contain "Duration" + It "Returns full history by default" { + $Results = @() + $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' + $Results.Length | Should Be 6 } - } - - It "Returns 'augmented' properties that are correct" { - InModuleScope "dbatools" { - $Results = @(Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -ExcludeJobSteps) + It "Returns only runs with no steps with ExcludeJobSteps" { + $Results = @() + $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -ExcludeJobSteps + $Results.Length | Should Be 2 + } + It 'Returns our own "augmented" properties, too' { + $Results = @() + $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -ExcludeJobSteps + $Results[0].psobject.properties.Name | Should -Contain 'StartDate' + $Results[0].psobject.properties.Name | Should -Contain 'EndDate' + $Results[0].psobject.properties.Name | Should -Contain 'Duration' + } + It 'Returns "augmented" properties that are correct' { + $Results = @() + $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -ExcludeJobSteps $Results[0].StartDate | Should -Be $Results[0].RunDate $Results[0].RunDuration | Should -Be 112 $Results[0].Duration.TotalSeconds | Should -Be 72 $Results[0].EndDate | Should -Be ($Results[0].StartDate.AddSeconds($Results[0].Duration.TotalSeconds)) } - } - - It "Figures out plain outputfiles" { - InModuleScope "dbatools" { - $Results = @(Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile) + It "Figures out plain outputfiles" { + $Results = @() + $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -WithOutputFile # no output for outcomes - ($Results | Where-Object StepID -eq 0).Count | Should -Be 2 - ($Results | Where-Object StepID -eq 0).OutputFileName -Join "" | Should -Be "" + ($Results | Where-Object StepID -eq 0).Length | Should Be 2 + ($Results | Where-Object StepID -eq 0).OutputFileName -Join '' | Should Be '' # correct output for job1 - ($Results | Where-Object StepID -ne 0 | Where-Object JobName -eq "Job1").OutputFileName | Should -Match "Job1Output[12]" + ($Results | Where-Object StepID -ne 0 | Where-Object JobName -eq 'Job1').OutputFileName | Should Match 'Job1Output[12]' # correct output for job2 - ($Results | Where-Object StepID -eq 2 | Where-Object JobName -eq "Job2").OutputFileName | Should -Match "Job2Output1" - ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job2").OutputFileName | Should -Be "" + ($Results | Where-Object StepID -eq 2 | Where-Object JobName -eq 'Job2').OutputFileName | Should Match 'Job2Output1' + ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq 'Job2').OutputFileName | Should Be '' } } - } - - Context "SQL Agent Tokens" { - It "Handles INST" { - InModuleScope "dbatools" { + Context "SQL Agent Tokens" { + It "Handles INST" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ - Job = "Job1" + Job = 'Job1' StepId = 1 - OutputFileName = "$(INST)__Job1Output1" + OutputFileName = '$(INST)__Job1Output1' } ) } - $Results = @(Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile) - ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "BASEServiceName__Job1Output1" - } - } + $Results = @() + $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -WithOutputFile - It "Handles MACH" { - InModuleScope "dbatools" { + ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq 'Job1').OutputFileName | Should Be 'BASEServiceName__Job1Output1' + + } + It "Handles MACH" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ - Job = "Job1" + Job = 'Job1' StepId = 1 - OutputFileName = "$(MACH)__Job1Output1" + OutputFileName = '$(MACH)__Job1Output1' } ) } - $Results = @(Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile) - ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "BASEComputerName__Job1Output1" - } - } + $Results = @() + $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -WithOutputFile + + ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq 'Job1').OutputFileName | Should Be 'BASEComputerName__Job1Output1' - It "Handles SQLDIR" { - InModuleScope "dbatools" { + } + It "Handles SQLDIR" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ - Job = "Job1" + Job = 'Job1' StepId = 1 - OutputFileName = "$(SQLDIR)__Job1Output1" + OutputFileName = '$(SQLDIR)__Job1Output1' } ) } - $Results = @(Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile) - ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "BASEInstallDataDirectory__Job1Output1" - } - } + $Results = @() + $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -WithOutputFile - It "Handles SQLLOGDIR" { - InModuleScope "dbatools" { + ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq 'Job1').OutputFileName | Should Be 'BASEInstallDataDirectory__Job1Output1' + + } + It "Handles SQLLOGDIR" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ - Job = "Job1" + Job = 'Job1' StepId = 1 - OutputFileName = "$(SQLLOGDIR)__Job1Output1" + OutputFileName = '$(SQLLOGDIR)__Job1Output1' } ) } - $Results = @(Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile) - ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "BASEErrorLog_''_""_]_Path__Job1Output1" - } - } + $Results = @() + $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -WithOutputFile + + ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq 'Job1').OutputFileName | Should Be 'BASEErrorLog_''_"_]_Path__Job1Output1' - It "Handles SRVR" { - InModuleScope "dbatools" { + } + It "Handles SRVR" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ - Job = "Job1" + Job = 'Job1' StepId = 1 - OutputFileName = "$(SRVR)__Job1Output1" + OutputFileName = '$(SRVR)__Job1Output1' } ) } - $Results = @(Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile) - ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "BASEDomainInstanceName__Job1Output1" + $Results = @() + $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -WithOutputFile + + ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq 'Job1').OutputFileName | Should Be 'BASEDomainInstanceName__Job1Output1' + } - } - It "Handles STEPID" { - InModuleScope "dbatools" { + It "Handles STEPID" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ - Job = "Job1" + Job = 'Job1' StepId = 1 - OutputFileName = "$(STEPID)__Job1Output1" + OutputFileName = '$(STEPID)__Job1Output1' } ) } - $Results = @(Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile) - ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "1__Job1Output1" - } - } + $Results = @() + $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -WithOutputFile + ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq 'Job1').OutputFileName | Should Be '1__Job1Output1' - It "Handles JOBID" { - InModuleScope "dbatools" { + } + It "Handles JOBID" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ - Job = "Job1" + Job = 'Job1' StepId = 1 - OutputFileName = "$(JOBID)__Job1Output1" + OutputFileName = '$(JOBID)__Job1Output1' } ) } - $Results = @(Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile) - ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "0x848A71E7438BD0468F8D4FC4464F9FC5__Job1Output1" + $Results = @() + $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -WithOutputFile + + ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq 'Job1').OutputFileName | Should Be '0x848A71E7438BD0468F8D4FC4464F9FC5__Job1Output1' + } - } - It "Handles STRTDT" { - InModuleScope "dbatools" { + + It "Handles STRTDT" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ - Job = "Job1" + Job = 'Job1' StepId = 1 - OutputFileName = "$(STRTDT)__Job1Output1" + OutputFileName = '$(STRTDT)__Job1Output1' } ) } - $Results = @(Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile) - ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "20170926__Job1Output1" + $Results = @() + $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -WithOutputFile + ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq 'Job1').OutputFileName | Should Be '20170926__Job1Output1' } - } - - It "Handles STRTTM" { - InModuleScope "dbatools" { + It "Handles STRTTM" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ - Job = "Job1" + Job = 'Job1' StepId = 1 - OutputFileName = "$(STRTTM)__Job1Output1" + OutputFileName = '$(STRTTM)__Job1Output1' } ) } - $Results = @(Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile) - ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "130000__Job1Output1" + $Results = @() + $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -WithOutputFile + ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq 'Job1').OutputFileName | Should Be '130000__Job1Output1' } - } - - It "Handles DATE" { - InModuleScope "dbatools" { + It "Handles DATE" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ - Job = "Job1" + Job = 'Job1' StepId = 1 - OutputFileName = "$(Get-Date)__Job1Output1" + OutputFileName = '$(DATE)__Job1Output1' } ) } - $Results = @(Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile) - ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "20170926__Job1Output1" + $Results = @() + $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -WithOutputFile + ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq 'Job1').OutputFileName | Should Be '20170926__Job1Output1' } - } - It "Handles TIME" { - InModuleScope "dbatools" { + It "Handles TIME" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ - Job = "Job1" + Job = 'Job1' StepId = 2 - OutputFileName = "$(TIME)__Job1Output1" + OutputFileName = '$(TIME)__Job1Output1' } ) } - $Results = @(Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile) - ($Results | Where-Object StepID -eq 2 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "130001__Job1Output1" + $Results = @() + $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -WithOutputFile + ($Results | Where-Object StepID -eq 2 | Where-Object JobName -eq 'Job1').OutputFileName | Should Be '130001__Job1Output1' + } } - } - - Context "SQL Agent escape sequences" { - It "Handles ESCAPE_NONE" { - InModuleScope "dbatools" { + Context "SQL Agent escape sequences" { + It "Handles ESCAPE_NONE" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ - Job = "Job1" + Job = 'Job1' StepId = 1 - OutputFileName = "$(ESCAPE_NONE(SQLLOGDIR))__Job1Output1" + OutputFileName = '$(ESCAPE_NONE(SQLLOGDIR))__Job1Output1' } ) } - $Results = @(Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile) - ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "BASEErrorLog_''_""_]_Path__Job1Output1" - } - } + $Results = @() + $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -WithOutputFile + + ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq 'Job1').OutputFileName | Should Be 'BASEErrorLog_''_"_]_Path__Job1Output1' - It "Handles ESCAPE_SQUOTE" { - InModuleScope "dbatools" { + } + It "Handles ESCAPE_SQUOTE" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ - Job = "Job1" + Job = 'Job1' StepId = 1 - OutputFileName = "$(ESCAPE_SQUOTE(SQLLOGDIR))__Job1Output1" + OutputFileName = '$(ESCAPE_SQUOTE(SQLLOGDIR))__Job1Output1' } ) } - $Results = @(Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile) - ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "BASEErrorLog_''''_""_]_Path__Job1Output1" - } - } + $Results = @() + $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -WithOutputFile - It "Handles ESCAPE_DQUOTE" { - InModuleScope "dbatools" { + ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq 'Job1').OutputFileName | Should Be 'BASEErrorLog_''''_"_]_Path__Job1Output1' + + } + It "Handles ESCAPE_DQUOTE" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ - Job = "Job1" + Job = 'Job1' StepId = 1 - OutputFileName = "$(ESCAPE_DQUOTE(SQLLOGDIR))__Job1Output1" + OutputFileName = '$(ESCAPE_DQUOTE(SQLLOGDIR))__Job1Output1' } ) } - $Results = @(Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile) - ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "BASEErrorLog_''_""""_]_Path__Job1Output1" - } - } + $Results = @() + $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -WithOutputFile + + ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq 'Job1').OutputFileName | Should Be 'BASEErrorLog_''_""_]_Path__Job1Output1' - It "Handles ESCAPE_RBRACKET" { - InModuleScope "dbatools" { + } + It "Handles ESCAPE_RBRACKET" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ - Job = "Job1" + Job = 'Job1' StepId = 1 - OutputFileName = "$(ESCAPE_RBRACKET(SQLLOGDIR))__Job1Output1" + OutputFileName = '$(ESCAPE_RBRACKET(SQLLOGDIR))__Job1Output1' } ) } - $Results = @(Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile) - ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "BASEErrorLog_''_""_]]_Path__Job1Output1" + $Results = @() + $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -WithOutputFile + + ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq 'Job1').OutputFileName | Should Be 'BASEErrorLog_''_"_]]_Path__Job1Output1' + } } } diff --git a/tests/Get-DbaAgentLog.Tests.ps1 b/tests/Get-DbaAgentLog.Tests.ps1 index 2ce1a7e3f18a..1445215a9d62 100644 --- a/tests/Get-DbaAgentLog.Tests.ps1 +++ b/tests/Get-DbaAgentLog.Tests.ps1 @@ -1,58 +1,35 @@ -#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } -param( - $ModuleName = "dbatools", - $CommandName = "Get-DbaAgentLog", - $PSDefaultParameterValues = $TestConfig.Defaults -) - +$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe $CommandName -Tag UnitTests { +Describe "$CommandName Unit Tests" -Tag 'UnitTests' { Context "Validate parameters" { - BeforeAll { - $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } - $expectedParameters = $TestConfig.CommonParameters - $expectedParameters += @( - "SqlInstance", - "SqlCredential", - "LogNumber", - "EnableException" - ) - } - - It "Should have the expected parameters" { - Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty + [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} + [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'LogNumber', 'EnableException' + $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters + It "Should only contain our specific parameters" { + (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 } } } -Describe $CommandName -Tag IntegrationTests { +Describe "$commandname Integration Tests" -Tags "IntegrationTests" { Context "Command gets agent log" { - BeforeAll { - $results = Get-DbaAgentLog -SqlInstance $TestConfig.instance2 - } - + $results = Get-DbaAgentLog -SqlInstance $TestConfig.instance2 It "Results are not empty" { - $results | Should -Not -BeNullOrEmpty + $results | Should Not Be $Null } - It "Results contain SQLServerAgent version" { - ($results.text -like "`[100`] Microsoft SQLServerAgent version*") | Should -BeTrue + $results.text -like '`[100`] Microsoft SQLServerAgent version*' | Should Be $true } - It "LogDate is a DateTime type" { - ($results | Select-Object -First 1).LogDate | Should -BeOfType DateTime + $($results | Select-Object -first 1).LogDate | Should BeOfType DateTime } } - Context "Command gets current agent log using LogNumber parameter" { - BeforeAll { - $results = Get-DbaAgentLog -SqlInstance $TestConfig.instance2 -LogNumber 0 - } - + $results = Get-DbaAgentLog -SqlInstance $TestConfig.instance2 -LogNumber 0 It "Results are not empty" { - $results | Should -Not -BeNullOrEmpty + $results | Should Not Be $Null } } -} \ No newline at end of file +} From f5bc325231be761b78bb11cf1ba0427c9c757239 Mon Sep 17 00:00:00 2001 From: Chrissy LeMaire Date: Mon, 11 Aug 2025 07:30:19 +0200 Subject: [PATCH 13/14] With Sonnet Updated Pester test scripts for Find-DbaAgentJob, Get-DbaAgentJob, Get-DbaAgentJobHistory, and Format-DbaBackupInformation to use parameterized headers, improved parameter validation, and consistent formatting. Enhanced test reliability and maintainability by using BeforeAll/AfterAll blocks, explicit parameter lists, and modern Pester syntax. Improved code readability and alignment with current dbatools testing standards. --- tests/Find-DbaAgentJob.Tests.ps1 | 154 ++++--- tests/Format-DbaBackupInformation.Tests.ps1 | 72 ++-- tests/Get-DbaAgentJob.Tests.ps1 | 88 ++-- tests/Get-DbaAgentJobHistory.Tests.ps1 | 419 +++++++++++--------- tests/Get-DbaAgentLog.Tests.ps1 | 58 ++- tests/New-DbaDbTransfer.Tests.ps1 | 267 +++++++------ tests/Read-DbaAuditFile.Tests.ps1 | 81 ++-- 7 files changed, 647 insertions(+), 492 deletions(-) diff --git a/tests/Find-DbaAgentJob.Tests.ps1 b/tests/Find-DbaAgentJob.Tests.ps1 index b28e4a089dd9..6ca9cee80f43 100644 --- a/tests/Find-DbaAgentJob.Tests.ps1 +++ b/tests/Find-DbaAgentJob.Tests.ps1 @@ -1,91 +1,135 @@ -$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 = "Find-DbaAgentJob", + $PSDefaultParameterValues = $TestConfig.Defaults +) + $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'JobName', 'ExcludeJobName', 'StepName', 'LastUsed', 'IsDisabled', 'IsFailed', 'IsNotScheduled', 'IsNoEmailNotification', 'Category', 'Owner', 'Since', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +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", + "JobName", + "ExcludeJobName", + "StepName", + "LastUsed", + "IsDisabled", + "IsFailed", + "IsNotScheduled", + "IsNoEmailNotification", + "Category", + "Owner", + "Since", + "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 - Context "Command finds jobs using all parameters" { - BeforeAll { - #subsystemServer needs the real underlying name, and it doesn't work if targeting something like localhost\namedinstance - # the typical error would be WARNING: [17:19:26][New-DbaAgentJobStep] Something went wrong creating the job step | The specified '@server' is - #invalid (valid values are returned by sp_helpserver). - $srvName = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Query "select @@servername as sn" -as PSObject - $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job 'dbatoolsci_testjob' -OwnerLogin 'sa' - $null = New-DbaAgentJobStep -SqlInstance $TestConfig.instance2 -Job 'dbatoolsci_testjob' -StepId 1 -StepName 'dbatoolsci Failed' -Subsystem TransactSql -SubsystemServer $srvName.sn -Command "RAISERROR (15600,-1,-1, 'dbatools_error');" -CmdExecSuccessCode 0 -OnSuccessAction QuitWithSuccess -OnFailAction QuitWithFailure -Database master -RetryAttempts 1 -RetryInterval 2 - $null = Start-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job 'dbatoolsci_testjob' - $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job 'dbatoolsregr_testjob' -OwnerLogin 'sa' - $null = New-DbaAgentJobStep -SqlInstance $TestConfig.instance2 -Job 'dbatoolsregr_testjob' -StepId 1 -StepName 'dbatoolsci Failed' -Subsystem TransactSql -SubsystemServer $srvName.sn -Command "RAISERROR (15600,-1,-1, 'dbatools_error');" -CmdExecSuccessCode 0 -OnSuccessAction QuitWithSuccess -OnFailAction QuitWithFailure -Database master -RetryAttempts 1 -RetryInterval 2 - $null = New-DbaAgentJobCategory -SqlInstance $TestConfig.instance2 -Category 'dbatoolsci_job_category' -CategoryType LocalJob - $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job 'dbatoolsci_testjob_disabled' -Category 'dbatoolsci_job_category' -Disabled - $null = New-DbaAgentJobStep -SqlInstance $TestConfig.instance2 -Job 'dbatoolsci_testjob_disabled' -StepId 1 -StepName 'dbatoolsci Test Step' -Subsystem TransactSql -SubsystemServer $srvName.sn -Command 'SELECT * FROM master.sys.all_columns' -CmdExecSuccessCode 0 -OnSuccessAction QuitWithSuccess -OnFailAction QuitWithFailure -Database master -RetryAttempts 1 -RetryInterval 2 - } - AfterAll { - $null = Remove-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob, dbatoolsregr_testjob, dbatoolsci_testjob_disabled -Confirm:$false - $null = Remove-DbaAgentJobCategory -SqlInstance $TestConfig.instance2 -Category 'dbatoolsci_job_category' -Confirm:$false - } + #subsystemServer needs the real underlying name, and it doesn't work if targeting something like localhost\namedinstance + # the typical error would be WARNING: [17:19:26][New-DbaAgentJobStep] Something went wrong creating the job step | The specified '@server' is + #invalid (valid values are returned by sp_helpserver). + $srvName = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Query "select @@servername as sn" -as PSObject + $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job "dbatoolsci_testjob" -OwnerLogin "sa" + $null = New-DbaAgentJobStep -SqlInstance $TestConfig.instance2 -Job "dbatoolsci_testjob" -StepId 1 -StepName "dbatoolsci Failed" -Subsystem TransactSql -SubsystemServer $srvName.sn -Command "RAISERROR (15600,-1,-1, 'dbatools_error');" -CmdExecSuccessCode 0 -OnSuccessAction QuitWithSuccess -OnFailAction QuitWithFailure -Database master -RetryAttempts 1 -RetryInterval 2 + $null = Start-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job "dbatoolsci_testjob" + $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job "dbatoolsregr_testjob" -OwnerLogin "sa" + $null = New-DbaAgentJobStep -SqlInstance $TestConfig.instance2 -Job "dbatoolsregr_testjob" -StepId 1 -StepName "dbatoolsci Failed" -Subsystem TransactSql -SubsystemServer $srvName.sn -Command "RAISERROR (15600,-1,-1, 'dbatools_error');" -CmdExecSuccessCode 0 -OnSuccessAction QuitWithSuccess -OnFailAction QuitWithFailure -Database master -RetryAttempts 1 -RetryInterval 2 + $null = New-DbaAgentJobCategory -SqlInstance $TestConfig.instance2 -Category "dbatoolsci_job_category" -CategoryType LocalJob + $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job "dbatoolsci_testjob_disabled" -Category "dbatoolsci_job_category" -Disabled + $null = New-DbaAgentJobStep -SqlInstance $TestConfig.instance2 -Job "dbatoolsci_testjob_disabled" -StepId 1 -StepName "dbatoolsci Test Step" -Subsystem TransactSql -SubsystemServer $srvName.sn -Command "SELECT * FROM master.sys.all_columns" -CmdExecSuccessCode 0 -OnSuccessAction QuitWithSuccess -OnFailAction QuitWithFailure -Database master -RetryAttempts 1 -RetryInterval 2 + + # 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 - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob + $null = Remove-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob, dbatoolsregr_testjob, dbatoolsci_testjob_disabled -Confirm:$false + $null = Remove-DbaAgentJobCategory -SqlInstance $TestConfig.instance2 -Category "dbatoolsci_job_category" -Confirm:$false + } + + Context "Command finds jobs using all parameters" { It "Should find a specific job" { - $results.name | Should Be "dbatoolsci_testjob" + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob + $results.name | Should -Be "dbatoolsci_testjob" } - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job *dbatoolsci* -ExcludeJobName dbatoolsci_testjob_disabled + It "Should find a specific job but not an excluded job" { - $results.name | Should Not Be "dbatoolsci_testjob_disabled" + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job *dbatoolsci* -ExcludeJobName dbatoolsci_testjob_disabled + $results.name | Should -Not -Be "dbatoolsci_testjob_disabled" } - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -StepName 'dbatoolsci Test Step' + It "Should find a specific job with a specific step" { - $results.name | Should Be "dbatoolsci_testjob_disabled" + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -StepName "dbatoolsci Test Step" + $results.name | Should -Be "dbatoolsci_testjob_disabled" } - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -LastUsed 10 + It "Should find jobs not used in the last 10 days" { - $results | Should not be null + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -LastUsed 10 + $results | Should -Not -BeNullOrEmpty } - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsDisabled + It "Should find jobs disabled from running" { - $results.name | Should be "dbatoolsci_testjob_disabled" + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsDisabled + $results.name | Should -Be "dbatoolsci_testjob_disabled" } - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsDisabled + It "Should find 1 job disabled from running" { - $results.count | Should be 1 + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsDisabled + $results.count | Should -Be 1 } - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsNotScheduled + It "Should find jobs that have not been scheduled" { - $results | Should not be null + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsNotScheduled + $results | Should -Not -BeNullOrEmpty } - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsNotScheduled -Job *dbatoolsci* + It "Should find 2 jobs that have no schedule" { - $results.count | Should be 2 + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsNotScheduled -Job *dbatoolsci* + $results.count | Should -Be 2 } - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsNoEmailNotification + It "Should find jobs that have no email notification" { - $results | Should not be null + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsNoEmailNotification + $results | Should -Not -BeNullOrEmpty } - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Category 'dbatoolsci_job_category' + It "Should find jobs that have a category of dbatoolsci_job_category" { - $results.name | Should be "dbatoolsci_testjob_disabled" + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Category "dbatoolsci_job_category" + $results.name | Should -Be "dbatoolsci_testjob_disabled" } - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Owner 'sa' + It "Should find jobs that are owned by sa" { - $results | Should not be null + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Owner "sa" + $results | Should -Not -BeNullOrEmpty } - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsFailed -Since '2016-07-01 10:47:00' + It "Should find jobs that have been failed since July of 2016" { - $results | Should not be null + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsFailed -Since "2016-07-01 10:47:00" + $results | Should -Not -BeNullOrEmpty } - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job *dbatoolsci*,*dbatoolsregr* -ExcludeJobName dbatoolsci_testjob_disabled + It "Should work with multiple wildcard passed in (see #9572)" { + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job *dbatoolsci*, *dbatoolsregr* -ExcludeJobName dbatoolsci_testjob_disabled $results.Count | Should -Be 2 } } -} +} \ No newline at end of file diff --git a/tests/Format-DbaBackupInformation.Tests.ps1 b/tests/Format-DbaBackupInformation.Tests.ps1 index 824d703e99bb..44079eae93f9 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-DbaAgentJob.Tests.ps1 b/tests/Get-DbaAgentJob.Tests.ps1 index d5c41b23cc61..05a90c8f2bfd 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-DbaAgentJobHistory.Tests.ps1 b/tests/Get-DbaAgentJobHistory.Tests.ps1 index 862a38dc0ff6..2554bbd2e698 100644 --- a/tests/Get-DbaAgentJobHistory.Tests.ps1 +++ b/tests/Get-DbaAgentJobHistory.Tests.ps1 @@ -1,398 +1,427 @@ -$commandname = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaAgentJobHistory", + $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', 'StartDate', 'EndDate', 'OutcomeType', 'ExcludeJobSteps', 'WithOutputFile', 'JobCollection', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Job", + "ExcludeJob", + "StartDate", + "EndDate", + "OutcomeType", + "ExcludeJobSteps", + "WithOutputFile", + "JobCollection", + "EnableException" + ) + } + It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } +Describe $CommandName -Tag UnitTests { + InModuleScope "dbatools" { + BeforeAll { + Mock Connect-DbaInstance -MockWith { + # Thanks @Fred + $obj = [PSCustomObject]@{ + Name = "BASEName" + ComputerName = "BASEComputerName" + InstanceName = "BASEInstanceName" + DomainInstanceName = "BASEDomainInstanceName" + InstallDataDirectory = "BASEInstallDataDirectory" + ErrorLogPath = "BASEErrorLog_{0}_{1}_{2}_Path" -f "'", '"', "]" + ServiceName = "BASEServiceName" + JobServer = New-Object PSObject + ConnectionContext = New-Object PSObject + } + Add-Member -InputObject $obj.ConnectionContext -Name ConnectionString -MemberType NoteProperty -Value "put=an=equal=in=it" + Add-Member -InputObject $obj.JobServer -Name EnumJobHistory -MemberType ScriptMethod -Value { + param ($filter) + return @( + @{ + JobName = "Job1" + JobID = [guid]"E7718A84-8B43-46D0-8F8D-4FC4464F9FC5" + StepID = 0 + StepName = "(Job outcome)" + RunDate = [DateTime]::Parse("2017-09-26T13:00:00") + RunDuration = 112 + RunStatus = 0 + }, + @{ + JobName = "Job1" + JobID = [guid]"E7718A84-8B43-46D0-8F8D-4FC4464F9FC5" + StepID = 1 + StepName = "Job1Step1" + RunDate = [DateTime]::Parse("2017-09-26T13:00:00") + RunDuration = 1 + RunStatus = 0 + }, + @{ + JobName = "Job1" + JobID = [guid]"E7718A84-8B43-46D0-8F8D-4FC4464F9FC5" + StepID = 2 + StepName = "Job1Step2" + RunDate = [DateTime]::Parse("2017-09-26T13:00:01") + RunDuration = 1 + RunStatus = 0 + }, + @{ + JobName = "Job2" + JobID = [guid]"9C9A6819-58CE-451A-8DD7-6D17593F0DFA" + StepID = 0 + StepName = "(Job outcome)" + RunDate = [DateTime]::Parse("2017-09-26T01:00:00") + RunDuration = 2 + RunStatus = 0 + }, + @{ + JobName = "Job2" + JobID = [guid]"9C9A6819-58CE-451A-8DD7-6D17593F0DFA" + StepID = 1 + StepName = "Job2Step1" + RunDate = [DateTime]::Parse("2017-09-26T01:00:00") + RunDuration = 1 + RunStatus = 0 + }, + @{ + JobName = "Job2" + JobID = [guid]"9C9A6819-58CE-451A-8DD7-6D17593F0DFA" + StepID = 2 + StepName = "Job2Step2" + RunDate = [DateTime]::Parse("2017-09-26T01:00:01") + RunDuration = 1 + RunStatus = 0 + } + ) + } + $obj.PSObject.TypeNames.Clear() + $obj.PSObject.TypeNames.Add("Microsoft.SqlServer.Management.Smo.Server") + return $obj + } #mock Connect-DbaInstance + } -Describe "$CommandName Unittests" -Tag 'UnitTests' { - InModuleScope 'dbatools' { - Mock Connect-DbaInstance -MockWith { - # Thanks @Fred - $obj = [PSCustomObject]@{ - Name = 'BASEName' - ComputerName = 'BASEComputerName' - InstanceName = 'BASEInstanceName' - DomainInstanceName = 'BASEDomainInstanceName' - InstallDataDirectory = 'BASEInstallDataDirectory' - ErrorLogPath = 'BASEErrorLog_{0}_{1}_{2}_Path' -f "'", '"', ']' - ServiceName = 'BASEServiceName' - JobServer = New-Object PSObject - ConnectionContext = New-Object PSObject - } - Add-Member -InputObject $obj.ConnectionContext -Name ConnectionString -MemberType NoteProperty -Value 'put=an=equal=in=it' - Add-Member -InputObject $obj.JobServer -Name EnumJobHistory -MemberType ScriptMethod -Value { - param ($filter) - return @( - @{ - JobName = 'Job1' - JobID = [guid]'E7718A84-8B43-46D0-8F8D-4FC4464F9FC5' - StepID = 0 - StepName = '(Job outcome)' - RunDate = [DateTime]::Parse('2017-09-26T13:00:00') - RunDuration = 112 - RunStatus = 0 - }, - @{ - JobName = 'Job1' - JobID = [guid]'E7718A84-8B43-46D0-8F8D-4FC4464F9FC5' - StepID = 1 - StepName = 'Job1Step1' - RunDate = [DateTime]::Parse('2017-09-26T13:00:00') - RunDuration = 1 - RunStatus = 0 - }, - @{ - JobName = 'Job1' - JobID = [guid]'E7718A84-8B43-46D0-8F8D-4FC4464F9FC5' - StepID = 2 - StepName = 'Job1Step2' - RunDate = [DateTime]::Parse('2017-09-26T13:00:01') - RunDuration = 1 - RunStatus = 0 - }, - @{ - JobName = 'Job2' - JobID = [guid]'9C9A6819-58CE-451A-8DD7-6D17593F0DFA' - StepID = 0 - StepName = '(Job outcome)' - RunDate = [DateTime]::Parse('2017-09-26T01:00:00') - RunDuration = 2 - RunStatus = 0 - }, - @{ - JobName = 'Job2' - JobID = [guid]'9C9A6819-58CE-451A-8DD7-6D17593F0DFA' - StepID = 1 - StepName = 'Job2Step1' - RunDate = [DateTime]::Parse('2017-09-26T01:00:00') - RunDuration = 1 - RunStatus = 0 - }, - @{ - JobName = 'Job2' - JobID = [guid]'9C9A6819-58CE-451A-8DD7-6D17593F0DFA' - StepID = 2 - StepName = 'Job2Step2' - RunDate = [DateTime]::Parse('2017-09-26T01:00:01') - RunDuration = 1 - RunStatus = 0 - } - ) - } - $obj.PSObject.TypeNames.Clear() - $obj.PSObject.TypeNames.Add("Microsoft.SqlServer.Management.Smo.Server") - return $obj - } #mock Connect-DbaInstance Context "Return values" { - - Mock Get-DbaAgentJobOutputFile -MockWith { - @( - @{ - Job = 'Job1' - StepId = 1 - OutputFileName = 'Job1Output1' - }, - @{ - Job = 'Job1' - StepId = 2 - OutputFileName = 'Job1Output2' - }, - @{ - Job = 'Job2' - StepId = 2 - OutputFileName = 'Job2Output1' - } - ) + BeforeAll { + Mock Get-DbaAgentJobOutputFile -MockWith { + @( + @{ + Job = "Job1" + StepId = 1 + OutputFileName = "Job1Output1" + }, + @{ + Job = "Job1" + StepId = 2 + OutputFileName = "Job1Output2" + }, + @{ + Job = "Job2" + StepId = 2 + OutputFileName = "Job2Output1" + } + ) + } } + It "Throws when ExcludeJobSteps and WithOutputFile" { - { Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -ExcludeJobSteps -WithOutputFile -EnableException } | Should Throw + { Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -ExcludeJobSteps -WithOutputFile -EnableException } | Should -Throw } + It "Returns full history by default" { $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' - $Results.Length | Should Be 6 + $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" + $Results.Length | Should -Be 6 } + It "Returns only runs with no steps with ExcludeJobSteps" { $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -ExcludeJobSteps - $Results.Length | Should Be 2 + $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -ExcludeJobSteps + $Results.Length | Should -Be 2 } - It 'Returns our own "augmented" properties, too' { + + It "Returns our own ""augmented"" properties, too" { $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -ExcludeJobSteps - $Results[0].psobject.properties.Name | Should -Contain 'StartDate' - $Results[0].psobject.properties.Name | Should -Contain 'EndDate' - $Results[0].psobject.properties.Name | Should -Contain 'Duration' + $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -ExcludeJobSteps + $Results[0].psobject.properties.Name | Should -Contain "StartDate" + $Results[0].psobject.properties.Name | Should -Contain "EndDate" + $Results[0].psobject.properties.Name | Should -Contain "Duration" } - It 'Returns "augmented" properties that are correct' { + + It "Returns ""augmented"" properties that are correct" { $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -ExcludeJobSteps + $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -ExcludeJobSteps $Results[0].StartDate | Should -Be $Results[0].RunDate $Results[0].RunDuration | Should -Be 112 $Results[0].Duration.TotalSeconds | Should -Be 72 $Results[0].EndDate | Should -Be ($Results[0].StartDate.AddSeconds($Results[0].Duration.TotalSeconds)) } + It "Figures out plain outputfiles" { $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -WithOutputFile + $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile # no output for outcomes - ($Results | Where-Object StepID -eq 0).Length | Should Be 2 - ($Results | Where-Object StepID -eq 0).OutputFileName -Join '' | Should Be '' + ($Results | Where-Object StepID -eq 0).Length | Should -Be 2 + ($Results | Where-Object StepID -eq 0).OutputFileName -Join "" | Should -Be "" # correct output for job1 - ($Results | Where-Object StepID -ne 0 | Where-Object JobName -eq 'Job1').OutputFileName | Should Match 'Job1Output[12]' + ($Results | Where-Object StepID -ne 0 | Where-Object JobName -eq "Job1").OutputFileName | Should -Match "Job1Output[12]" # correct output for job2 - ($Results | Where-Object StepID -eq 2 | Where-Object JobName -eq 'Job2').OutputFileName | Should Match 'Job2Output1' - ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq 'Job2').OutputFileName | Should Be '' + ($Results | Where-Object StepID -eq 2 | Where-Object JobName -eq "Job2").OutputFileName | Should -Match "Job2Output1" + ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job2").OutputFileName | Should -Be "" } } + Context "SQL Agent Tokens" { It "Handles INST" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ - Job = 'Job1' + Job = "Job1" StepId = 1 - OutputFileName = '$(INST)__Job1Output1' + OutputFileName = "`$(INST)__Job1Output1" } ) } $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -WithOutputFile - - ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq 'Job1').OutputFileName | Should Be 'BASEServiceName__Job1Output1' + $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile + ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "BASEServiceName__Job1Output1" } + It "Handles MACH" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ - Job = 'Job1' + Job = "Job1" StepId = 1 - OutputFileName = '$(MACH)__Job1Output1' + OutputFileName = "`$(MACH)__Job1Output1" } ) } $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -WithOutputFile - - ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq 'Job1').OutputFileName | Should Be 'BASEComputerName__Job1Output1' + $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile + ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "BASEComputerName__Job1Output1" } + It "Handles SQLDIR" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ - Job = 'Job1' + Job = "Job1" StepId = 1 - OutputFileName = '$(SQLDIR)__Job1Output1' + OutputFileName = "`$(SQLDIR)__Job1Output1" } ) } $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -WithOutputFile - - ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq 'Job1').OutputFileName | Should Be 'BASEInstallDataDirectory__Job1Output1' + $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile + ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "BASEInstallDataDirectory__Job1Output1" } + It "Handles SQLLOGDIR" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ - Job = 'Job1' + Job = "Job1" StepId = 1 - OutputFileName = '$(SQLLOGDIR)__Job1Output1' + OutputFileName = "`$(SQLLOGDIR)__Job1Output1" } ) } $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -WithOutputFile - - ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq 'Job1').OutputFileName | Should Be 'BASEErrorLog_''_"_]_Path__Job1Output1' + $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile + ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "BASEErrorLog_''_""_]_Path__Job1Output1" } + It "Handles SRVR" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ - Job = 'Job1' + Job = "Job1" StepId = 1 - OutputFileName = '$(SRVR)__Job1Output1' + OutputFileName = "`$(SRVR)__Job1Output1" } ) } $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -WithOutputFile - - ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq 'Job1').OutputFileName | Should Be 'BASEDomainInstanceName__Job1Output1' + $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile + ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "BASEDomainInstanceName__Job1Output1" } It "Handles STEPID" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ - Job = 'Job1' + Job = "Job1" StepId = 1 - OutputFileName = '$(STEPID)__Job1Output1' + OutputFileName = "`$(STEPID)__Job1Output1" } ) } $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -WithOutputFile - ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq 'Job1').OutputFileName | Should Be '1__Job1Output1' - + $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile + ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "1__Job1Output1" } + It "Handles JOBID" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ - Job = 'Job1' + Job = "Job1" StepId = 1 - OutputFileName = '$(JOBID)__Job1Output1' + OutputFileName = "`$(JOBID)__Job1Output1" } ) } $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -WithOutputFile - - ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq 'Job1').OutputFileName | Should Be '0x848A71E7438BD0468F8D4FC4464F9FC5__Job1Output1' + $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile + ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "0x848A71E7438BD0468F8D4FC4464F9FC5__Job1Output1" } - It "Handles STRTDT" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ - Job = 'Job1' + Job = "Job1" StepId = 1 - OutputFileName = '$(STRTDT)__Job1Output1' + OutputFileName = "`$(STRTDT)__Job1Output1" } ) } $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -WithOutputFile - ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq 'Job1').OutputFileName | Should Be '20170926__Job1Output1' + $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile + ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "20170926__Job1Output1" } + It "Handles STRTTM" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ - Job = 'Job1' + Job = "Job1" StepId = 1 - OutputFileName = '$(STRTTM)__Job1Output1' + OutputFileName = "`$(STRTTM)__Job1Output1" } ) } $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -WithOutputFile - ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq 'Job1').OutputFileName | Should Be '130000__Job1Output1' + $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile + ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "130000__Job1Output1" } + It "Handles DATE" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ - Job = 'Job1' + Job = "Job1" StepId = 1 - OutputFileName = '$(DATE)__Job1Output1' + OutputFileName = "`$(DATE)__Job1Output1" } ) } $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -WithOutputFile - ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq 'Job1').OutputFileName | Should Be '20170926__Job1Output1' + $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile + ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "20170926__Job1Output1" } It "Handles TIME" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ - Job = 'Job1' + Job = "Job1" StepId = 2 - OutputFileName = '$(TIME)__Job1Output1' + OutputFileName = "`$(TIME)__Job1Output1" } ) } $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -WithOutputFile - ($Results | Where-Object StepID -eq 2 | Where-Object JobName -eq 'Job1').OutputFileName | Should Be '130001__Job1Output1' - + $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile + ($Results | Where-Object StepID -eq 2 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "130001__Job1Output1" } } + Context "SQL Agent escape sequences" { It "Handles ESCAPE_NONE" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ - Job = 'Job1' + Job = "Job1" StepId = 1 - OutputFileName = '$(ESCAPE_NONE(SQLLOGDIR))__Job1Output1' + OutputFileName = "`$(ESCAPE_NONE(SQLLOGDIR))__Job1Output1" } ) } $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -WithOutputFile - - ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq 'Job1').OutputFileName | Should Be 'BASEErrorLog_''_"_]_Path__Job1Output1' + $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile + ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "BASEErrorLog_''_""_]_Path__Job1Output1" } + It "Handles ESCAPE_SQUOTE" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ - Job = 'Job1' + Job = "Job1" StepId = 1 - OutputFileName = '$(ESCAPE_SQUOTE(SQLLOGDIR))__Job1Output1' + OutputFileName = "`$(ESCAPE_SQUOTE(SQLLOGDIR))__Job1Output1" } ) } $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -WithOutputFile - - ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq 'Job1').OutputFileName | Should Be 'BASEErrorLog_''''_"_]_Path__Job1Output1' + $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile + ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "BASEErrorLog_''''_""_]_Path__Job1Output1" } + It "Handles ESCAPE_DQUOTE" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ - Job = 'Job1' + Job = "Job1" StepId = 1 - OutputFileName = '$(ESCAPE_DQUOTE(SQLLOGDIR))__Job1Output1' + OutputFileName = "`$(ESCAPE_DQUOTE(SQLLOGDIR))__Job1Output1" } ) } $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -WithOutputFile - - ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq 'Job1').OutputFileName | Should Be 'BASEErrorLog_''_""_]_Path__Job1Output1' + $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile + ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "BASEErrorLog_''_""""_]_Path__Job1Output1" } + It "Handles ESCAPE_RBRACKET" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ - Job = 'Job1' + Job = "Job1" StepId = 1 - OutputFileName = '$(ESCAPE_RBRACKET(SQLLOGDIR))__Job1Output1' + OutputFileName = "`$(ESCAPE_RBRACKET(SQLLOGDIR))__Job1Output1" } ) } $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -WithOutputFile - - ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq 'Job1').OutputFileName | Should Be 'BASEErrorLog_''_"_]]_Path__Job1Output1' + $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile + ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "BASEErrorLog_''_""_]]_Path__Job1Output1" } } } diff --git a/tests/Get-DbaAgentLog.Tests.ps1 b/tests/Get-DbaAgentLog.Tests.ps1 index 1445215a9d62..5d07c32f5dfc 100644 --- a/tests/Get-DbaAgentLog.Tests.ps1 +++ b/tests/Get-DbaAgentLog.Tests.ps1 @@ -1,35 +1,55 @@ -$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', 'LogNumber', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaAgentLog", + $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", + "LogNumber", + "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 agent log" { - $results = Get-DbaAgentLog -SqlInstance $TestConfig.instance2 + BeforeAll { + $results = Get-DbaAgentLog -SqlInstance $TestConfig.instance2 + } + It "Results are not empty" { - $results | Should Not Be $Null + $results | Should -Not -BeNullOrEmpty } + It "Results contain SQLServerAgent version" { - $results.text -like '`[100`] Microsoft SQLServerAgent version*' | Should Be $true + $results.text -like "`[100`] Microsoft SQLServerAgent version*" | Should -Be $true } + It "LogDate is a DateTime type" { - $($results | Select-Object -first 1).LogDate | Should BeOfType DateTime + ($results | Select-Object -First 1).LogDate | Should -BeOfType DateTime } } + Context "Command gets current agent log using LogNumber parameter" { - $results = Get-DbaAgentLog -SqlInstance $TestConfig.instance2 -LogNumber 0 + BeforeAll { + $logResults = Get-DbaAgentLog -SqlInstance $TestConfig.instance2 -LogNumber 0 + } + It "Results are not empty" { - $results | Should Not Be $Null + $logResults | Should -Not -BeNullOrEmpty } } -} +} \ No newline at end of file diff --git a/tests/New-DbaDbTransfer.Tests.ps1 b/tests/New-DbaDbTransfer.Tests.ps1 index a0f791d6630a..fd908d456c4d 100644 --- a/tests/New-DbaDbTransfer.Tests.ps1 +++ b/tests/New-DbaDbTransfer.Tests.ps1 @@ -1,114 +1,123 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "New-DbaDbTransfer", + $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', - 'DestinationSqlInstance', - 'DestinationSqlCredential', - 'Database', - 'DestinationDatabase', - 'BatchSize', - 'BulkCopyTimeOut', - 'InputObject', - 'EnableException', - 'CopyAllObjects', - 'CopyAll', - 'SchemaOnly', - 'DataOnly', - 'ScriptingOption' - ) - $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", + "DestinationSqlInstance", + "DestinationSqlCredential", + "Database", + "DestinationDatabase", + "BatchSize", + "BulkCopyTimeOut", + "InputObject", + "EnableException", + "CopyAllObjects", + "CopyAll", + "SchemaOnly", + "DataOnly", + "ScriptingOption" + ) + } + + 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 { - $dbName = 'dbatools_transfer' - $source = Connect-DbaInstance -SqlInstance $TestConfig.instance1 - $destination = Connect-DbaInstance -SqlInstance $TestConfig.instance2 - $source.Query("CREATE DATABASE $dbName") - $db = Get-DbaDatabase -SqlInstance $TestConfig.instance1 -Database $dbName - $null = $db.Query("CREATE TABLE dbo.transfer_test (id int); + $global:dbName = "dbatools_transfer" + $global:source = Connect-DbaInstance -SqlInstance $TestConfig.instance1 + $global:destination = Connect-DbaInstance -SqlInstance $TestConfig.instance2 + $global:source.Query("CREATE DATABASE $global:dbName") + $global:db = Get-DbaDatabase -SqlInstance $TestConfig.instance1 -Database $global:dbName + $null = $global:db.Query("CREATE TABLE dbo.transfer_test (id int); INSERT dbo.transfer_test SELECT top 10 1 FROM sys.objects") - $null = $db.Query("CREATE TABLE dbo.transfer_test2 (id int)") - $null = $db.Query("CREATE TABLE dbo.transfer_test3 (id int)") - $null = $db.Query("CREATE TABLE dbo.transfer_test4 (id int); + $null = $global:db.Query("CREATE TABLE dbo.transfer_test2 (id int)") + $null = $global:db.Query("CREATE TABLE dbo.transfer_test3 (id int)") + $null = $global:db.Query("CREATE TABLE dbo.transfer_test4 (id int); INSERT dbo.transfer_test4 SELECT top 13 1 FROM sys.objects") - $allowedObjects = @( - 'FullTextCatalogs', - 'FullTextStopLists', - 'SearchPropertyLists', - 'Tables', - 'Views', - 'StoredProcedures', - 'UserDefinedFunctions', - 'UserDefinedDataTypes', - 'UserDefinedTableTypes', - 'PlanGuides', - 'Rules', - 'Defaults', - 'Users', - 'Roles', - 'PartitionSchemes', - 'PartitionFunctions', - 'XmlSchemaCollections', - 'SqlAssemblies', - 'UserDefinedAggregates', - 'UserDefinedTypes', - 'Schemas', - 'Synonyms', - 'Sequences', - 'DatabaseTriggers', - 'DatabaseScopedCredentials', - 'ExternalFileFormats', - 'ExternalDataSources', - 'Logins', - 'ExternalLibraries' + $global:allowedObjects = @( + "FullTextCatalogs", + "FullTextStopLists", + "SearchPropertyLists", + "Tables", + "Views", + "StoredProcedures", + "UserDefinedFunctions", + "UserDefinedDataTypes", + "UserDefinedTableTypes", + "PlanGuides", + "Rules", + "Defaults", + "Users", + "Roles", + "PartitionSchemes", + "PartitionFunctions", + "XmlSchemaCollections", + "SqlAssemblies", + "UserDefinedAggregates", + "UserDefinedTypes", + "Schemas", + "Synonyms", + "Sequences", + "DatabaseTriggers", + "DatabaseScopedCredentials", + "ExternalFileFormats", + "ExternalDataSources", + "Logins", + "ExternalLibraries" ) - $securePassword = 'bar' | ConvertTo-SecureString -AsPlainText -Force - $creds = New-Object PSCredential ('foo', $securePassword) + $securePassword = "bar" | ConvertTo-SecureString -AsPlainText -Force + $global:creds = New-Object PSCredential ("foo", $securePassword) } AfterAll { try { - $null = $db.Query("DROP TABLE dbo.transfer_test") - $null = $db.Query("DROP TABLE dbo.transfer_test2") - $null = $db.Query("DROP TABLE dbo.transfer_test3") - $null = $db.Query("DROP TABLE dbo.transfer_test4") + $null = $global:db.Query("DROP TABLE dbo.transfer_test") + $null = $global:db.Query("DROP TABLE dbo.transfer_test2") + $null = $global:db.Query("DROP TABLE dbo.transfer_test3") + $null = $global:db.Query("DROP TABLE dbo.transfer_test4") } catch { $null = 1 } - Remove-DbaDatabase -SqlInstance $TestConfig.instance1 -Database $dbName -Confirm:$false + Remove-DbaDatabase -SqlInstance $TestConfig.instance1 -Database $global:dbName -Confirm:$false -ErrorAction SilentlyContinue } Context "Testing connection parameters" { It "Should create a transfer object" { - $transfer = New-DbaDbTransfer -SqlInstance $TestConfig.instance1 -Database $dbName + $transfer = New-DbaDbTransfer -SqlInstance $TestConfig.instance1 -Database $global:dbName $transfer | Should -BeOfType Microsoft.SqlServer.Management.Smo.Transfer $transfer.BatchSize | Should -Be 50000 $transfer.BulkCopyTimeout | Should -Be 5000 - $transfer.Database.Name | Should -Be $dbName + $transfer.Database.Name | Should -Be $global:dbName $transfer.ObjectList | Should -BeNullOrEmpty $transfer.CopyAllObjects | Should -Be $false - $allowedObjects | ForEach-Object { $transfer.$_ | Should -BeNullOrEmpty } + $global:allowedObjects | ForEach-Object { $transfer.$_ | Should -BeNullOrEmpty } $transfer.CopyData | Should -Be $true $transfer.CopySchema | Should -Be $true - $transfer.DestinationDatabase | Should -Be $dbName + $transfer.DestinationDatabase | Should -Be $global:dbName $transfer.DestinationServer | Should -BeNullOrEmpty } It "Should properly assign dest server parameters from full connstring" { - $transfer = New-DbaDbTransfer -SqlInstance $TestConfig.instance1 -Database $dbName -DestinationSqlInstance 'Data Source=foo;User=bar;password=foobar;Initial Catalog=hog' + $transfer = New-DbaDbTransfer -SqlInstance $TestConfig.instance1 -Database $global:dbName -DestinationSqlInstance "Data Source=foo;User=bar;password=foobar;Initial Catalog=hog" $transfer.DestinationDatabase | Should -Be hog $transfer.DestinationLoginSecure | Should -Be $false $transfer.DestinationLogin | Should -Be bar @@ -116,8 +125,8 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { $transfer.DestinationServer | Should -Be foo } It "Should properly assign dest server parameters from trusted connstring" { - $transfer = New-DbaDbTransfer -SqlInstance $TestConfig.instance1 -Database $dbName -DestinationSqlInstance 'Data Source=foo;Integrated Security=True' - $transfer.DestinationDatabase | Should -Be $dbName + $transfer = New-DbaDbTransfer -SqlInstance $TestConfig.instance1 -Database $global:dbName -DestinationSqlInstance "Data Source=foo;Integrated Security=True" + $transfer.DestinationDatabase | Should -Be $global:dbName $transfer.DestinationLoginSecure | Should -Be $true $transfer.DestinationLogin | Should -BeNullOrEmpty $transfer.DestinationPassword | Should -BeNullOrEmpty @@ -126,108 +135,108 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { It "Should properly assign dest server parameters from server object" { $dest = Connect-DbaInstance -SqlInstance $TestConfig.instance2 -Database msdb $connStringBuilder = New-Object Microsoft.Data.SqlClient.SqlConnectionStringBuilder $dest.ConnectionContext.ConnectionString - $transfer = New-DbaDbTransfer -SqlInstance $TestConfig.instance1 -Database $dbName -DestinationSqlInstance $dest - $transfer.DestinationDatabase | Should -Be $connStringBuilder['Initial Catalog'] - $transfer.DestinationLoginSecure | Should -Be $connStringBuilder['Integrated Security'] - $transfer.DestinationLogin | Should -Be $connStringBuilder['User ID'] - $transfer.DestinationPassword | Should -Be $connStringBuilder['Password'] - $transfer.DestinationServer | Should -Be $connStringBuilder['Data Source'] + $transfer = New-DbaDbTransfer -SqlInstance $TestConfig.instance1 -Database $global:dbName -DestinationSqlInstance $dest + $transfer.DestinationDatabase | Should -Be $connStringBuilder["Initial Catalog"] + $transfer.DestinationLoginSecure | Should -Be $connStringBuilder["Integrated Security"] + $transfer.DestinationLogin | Should -Be $connStringBuilder["User ID"] + $transfer.DestinationPassword | Should -Be $connStringBuilder["Password"] + $transfer.DestinationServer | Should -Be $connStringBuilder["Data Source"] } It "Should properly assign dest server parameters from plaintext params" { - $transfer = New-DbaDbTransfer -SqlInstance $TestConfig.instance1 -Database $dbName -DestinationSqlInstance foo -DestinationDatabase bar -DestinationSqlCredential $creds + $transfer = New-DbaDbTransfer -SqlInstance $TestConfig.instance1 -Database $global:dbName -DestinationSqlInstance foo -DestinationDatabase bar -DestinationSqlCredential $global:creds $transfer.DestinationDatabase | Should -Be bar $transfer.DestinationLoginSecure | Should -Be $false - $transfer.DestinationLogin | Should -Be $creds.UserName - $transfer.DestinationPassword | Should -Be $creds.GetNetworkCredential().Password + $transfer.DestinationLogin | Should -Be $global:creds.UserName + $transfer.DestinationPassword | Should -Be $global:creds.GetNetworkCredential().Password $transfer.DestinationServer | Should -Be foo } } Context "Testing function parameters" { It "Should script all objects" { - $transfer = New-DbaDbTransfer -SqlInstance $TestConfig.instance1 -Database $dbName -CopyAllObjects + $transfer = New-DbaDbTransfer -SqlInstance $TestConfig.instance1 -Database $global:dbName -CopyAllObjects $transfer.CopyData | Should -Be $true $transfer.CopySchema | Should -Be $true $script = $transfer.ScriptTransfer() -join "`n" - $script | Should -BeLike '*CREATE TABLE `[dbo`].`[transfer_test`]*' - $script | Should -BeLike '*CREATE TABLE `[dbo`].`[transfer_test2`]*' - $script | Should -BeLike '*CREATE TABLE `[dbo`].`[transfer_test3`]*' - $script | Should -BeLike '*CREATE TABLE `[dbo`].`[transfer_test4`]*' + $script | Should -BeLike "*CREATE TABLE `[dbo`].`[transfer_test`]*" + $script | Should -BeLike "*CREATE TABLE `[dbo`].`[transfer_test2`]*" + $script | Should -BeLike "*CREATE TABLE `[dbo`].`[transfer_test3`]*" + $script | Should -BeLike "*CREATE TABLE `[dbo`].`[transfer_test4`]*" } It "Should script all tables with just schemas" { - $transfer = New-DbaDbTransfer -SqlInstance $TestConfig.instance1 -Database $dbName -CopyAll Tables -SchemaOnly + $transfer = New-DbaDbTransfer -SqlInstance $TestConfig.instance1 -Database $global:dbName -CopyAll Tables -SchemaOnly $transfer.CopyData | Should -Be $false $transfer.CopySchema | Should -Be $true $script = $transfer.ScriptTransfer() -join "`n" - $script | Should -BeLike '*CREATE TABLE `[dbo`].`[transfer_test`]*' - $script | Should -BeLike '*CREATE TABLE `[dbo`].`[transfer_test2`]*' - $script | Should -BeLike '*CREATE TABLE `[dbo`].`[transfer_test3`]*' - $script | Should -BeLike '*CREATE TABLE `[dbo`].`[transfer_test4`]*' + $script | Should -BeLike "*CREATE TABLE `[dbo`].`[transfer_test`]*" + $script | Should -BeLike "*CREATE TABLE `[dbo`].`[transfer_test2`]*" + $script | Should -BeLike "*CREATE TABLE `[dbo`].`[transfer_test3`]*" + $script | Should -BeLike "*CREATE TABLE `[dbo`].`[transfer_test4`]*" } It "Should script one table with just data" { - $table = Get-DbaDbTable -SqlInstance $TestConfig.instance1 -Database $dbName -Table transfer_test - $transfer = New-DbaDbTransfer -SqlInstance $TestConfig.instance1 -Database $dbName -InputObject $table -DataOnly + $table = Get-DbaDbTable -SqlInstance $TestConfig.instance1 -Database $global:dbName -Table transfer_test + $transfer = New-DbaDbTransfer -SqlInstance $TestConfig.instance1 -Database $global:dbName -InputObject $table -DataOnly $transfer.ObjectList.Count | Should -Be 1 $transfer.CopyData | Should -Be $true $transfer.CopySchema | Should -Be $false # # data only ScriptTransfer still creates schema $script = $transfer.ScriptTransfer() -join "`n" - $script | Should -BeLike '*CREATE TABLE `[dbo`].`[transfer_test`]*' + $script | Should -BeLike "*CREATE TABLE `[dbo`].`[transfer_test`]*" } It "Should script two tables from pipeline" { - $tables = Get-DbaDbTable -SqlInstance $TestConfig.instance1 -Database $dbName -Table transfer_test2, transfer_test4 - $transfer = $tables | New-DbaDbTransfer -SqlInstance $TestConfig.instance1 -Database $dbName + $tables = Get-DbaDbTable -SqlInstance $TestConfig.instance1 -Database $global:dbName -Table transfer_test2, transfer_test4 + $transfer = $tables | New-DbaDbTransfer -SqlInstance $TestConfig.instance1 -Database $global:dbName $transfer.ObjectList.Count | Should -Be 2 $script = $transfer.ScriptTransfer() -join "`n" - $script | Should -Not -BeLike '*CREATE TABLE `[dbo`].`[transfer_test`]*' - $script | Should -BeLike '*CREATE TABLE `[dbo`].`[transfer_test2`]*' - $script | Should -Not -BeLike '*CREATE TABLE `[dbo`].`[transfer_test3`]*' - $script | Should -BeLike '*CREATE TABLE `[dbo`].`[transfer_test4`]*' + $script | Should -Not -BeLike "*CREATE TABLE `[dbo`].`[transfer_test`]*" + $script | Should -BeLike "*CREATE TABLE `[dbo`].`[transfer_test2`]*" + $script | Should -Not -BeLike "*CREATE TABLE `[dbo`].`[transfer_test3`]*" + $script | Should -BeLike "*CREATE TABLE `[dbo`].`[transfer_test4`]*" } It "Should accept script options object" { $options = New-DbaScriptingOption $options.ScriptDrops = $true - $transfer = New-DbaDbTransfer -SqlInstance $TestConfig.instance1 -Database $dbName -CopyAll Tables -ScriptingOption $options + $transfer = New-DbaDbTransfer -SqlInstance $TestConfig.instance1 -Database $global:dbName -CopyAll Tables -ScriptingOption $options $transfer.Options.ScriptDrops | Should -BeTrue $script = $transfer.ScriptTransfer() -join "`n" - $script | Should -BeLike '*DROP TABLE `[dbo`].`[transfer_test`]*' + $script | Should -BeLike "*DROP TABLE `[dbo`].`[transfer_test`]*" } } Context "Testing object transfer" { BeforeEach { - $destination.Query("CREATE DATABASE $dbname") - $db2 = Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbName + $global:destination.Query("CREATE DATABASE $global:dbName") + $global:db2 = Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $global:dbName } AfterEach { - Remove-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbName -Confirm:$false + Remove-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $global:dbName -Confirm:$false -ErrorAction SilentlyContinue } It "Should transfer all tables" { - $transfer = New-DbaDbTransfer -SqlInstance $TestConfig.instance1 -DestinationSqlInstance $TestConfig.instance2 -Database $dbName -CopyAll Tables + $transfer = New-DbaDbTransfer -SqlInstance $TestConfig.instance1 -DestinationSqlInstance $TestConfig.instance2 -Database $global:dbName -CopyAll Tables $transfer.TransferData() - $tables = Get-DbaDbTable -SqlInstance $TestConfig.instance2 -Database $dbName -Table transfer_test, transfer_test2, transfer_test3, transfer_test4 + $tables = Get-DbaDbTable -SqlInstance $TestConfig.instance2 -Database $global:dbName -Table transfer_test, transfer_test2, transfer_test3, transfer_test4 $tables.Count | Should -Be 4 - $db.Query("select id from dbo.transfer_test").id | Should -Not -BeNullOrEmpty - $db.Query("select id from dbo.transfer_test4").id | Should -Not -BeNullOrEmpty - $db.Query("select id from dbo.transfer_test").id | Should -BeIn $db2.Query("select id from dbo.transfer_test").id - $db.Query("select id from dbo.transfer_test4").id | Should -BeIn $db2.Query("select id from dbo.transfer_test4").id + $global:db.Query("select id from dbo.transfer_test").id | Should -Not -BeNullOrEmpty + $global:db.Query("select id from dbo.transfer_test4").id | Should -Not -BeNullOrEmpty + $global:db.Query("select id from dbo.transfer_test").id | Should -BeIn $global:db2.Query("select id from dbo.transfer_test").id + $global:db.Query("select id from dbo.transfer_test4").id | Should -BeIn $global:db2.Query("select id from dbo.transfer_test4").id } It "Should transfer two tables with just schemas" { - $sourceTables = Get-DbaDbTable -SqlInstance $TestConfig.instance1 -Database $dbName -Table transfer_test, transfer_test2 - $transfer = $sourceTables | New-DbaDbTransfer -SqlInstance $TestConfig.instance1 -DestinationSqlInstance $TestConfig.instance2 -Database $dbName -SchemaOnly + $sourceTables = Get-DbaDbTable -SqlInstance $TestConfig.instance1 -Database $global:dbName -Table transfer_test, transfer_test2 + $transfer = $sourceTables | New-DbaDbTransfer -SqlInstance $TestConfig.instance1 -DestinationSqlInstance $TestConfig.instance2 -Database $global:dbName -SchemaOnly $transfer.TransferData() - $tables = Get-DbaDbTable -SqlInstance $TestConfig.instance2 -Database $dbName -Table transfer_test, transfer_test2 + $tables = Get-DbaDbTable -SqlInstance $TestConfig.instance2 -Database $global:dbName -Table transfer_test, transfer_test2 $tables.Count | Should -Be 2 - $db2.Query("select id from dbo.transfer_test").id | Should -BeNullOrEmpty + $global:db2.Query("select id from dbo.transfer_test").id | Should -BeNullOrEmpty } It "Should transfer two tables without copying schema" { - $null = $db2.Query("CREATE TABLE dbo.transfer_test (id int)") - $null = $db2.Query("CREATE TABLE dbo.transfer_test2 (id int)") - $sourceTables = Get-DbaDbTable -SqlInstance $TestConfig.instance1 -Database $dbName -Table transfer_test, transfer_test2 - $transfer = $sourceTables | New-DbaDbTransfer -SqlInstance $TestConfig.instance1 -DestinationSqlInstance $TestConfig.instance2 -Database $dbName -DataOnly + $null = $global:db2.Query("CREATE TABLE dbo.transfer_test (id int)") + $null = $global:db2.Query("CREATE TABLE dbo.transfer_test2 (id int)") + $sourceTables = Get-DbaDbTable -SqlInstance $TestConfig.instance1 -Database $global:dbName -Table transfer_test, transfer_test2 + $transfer = $sourceTables | New-DbaDbTransfer -SqlInstance $TestConfig.instance1 -DestinationSqlInstance $TestConfig.instance2 -Database $global:dbName -DataOnly $transfer.TransferData() - $tables = Get-DbaDbTable -SqlInstance $TestConfig.instance2 -Database $dbName -Table transfer_test, transfer_test2 + $tables = Get-DbaDbTable -SqlInstance $TestConfig.instance2 -Database $global:dbName -Table transfer_test, transfer_test2 $tables.Count | Should -Be 2 - $db.Query("select id from dbo.transfer_test").id | Should -Not -BeNullOrEmpty - $db.Query("select id from dbo.transfer_test").id | Should -BeIn $db2.Query("select id from dbo.transfer_test").id + $global:db.Query("select id from dbo.transfer_test").id | Should -Not -BeNullOrEmpty + $global:db.Query("select id from dbo.transfer_test").id | Should -BeIn $global:db2.Query("select id from dbo.transfer_test").id } } -} +} \ No newline at end of file diff --git a/tests/Read-DbaAuditFile.Tests.ps1 b/tests/Read-DbaAuditFile.Tests.ps1 index fbc86a291939..406fadfe19f0 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 From a5dff07bccf773dffd86d37dc8bd8c8d80a069a7 Mon Sep 17 00:00:00 2001 From: Chrissy LeMaire Date: Mon, 11 Aug 2025 08:22:54 +0200 Subject: [PATCH 14/14] These can't be converted Find-DbaAgentJob, Get-DbaAgentJobHistory, Get-DbaAgentLog, and New-DbaDbTransfer --- tests/Find-DbaAgentJob.Tests.ps1 | 154 ++++----- tests/Get-DbaAgentJobHistory.Tests.ps1 | 419 ++++++++++++------------- tests/Get-DbaAgentLog.Tests.ps1 | 58 ++-- tests/New-DbaDbTransfer.Tests.ps1 | 267 ++++++++-------- 4 files changed, 398 insertions(+), 500 deletions(-) diff --git a/tests/Find-DbaAgentJob.Tests.ps1 b/tests/Find-DbaAgentJob.Tests.ps1 index 6ca9cee80f43..b28e4a089dd9 100644 --- a/tests/Find-DbaAgentJob.Tests.ps1 +++ b/tests/Find-DbaAgentJob.Tests.ps1 @@ -1,135 +1,91 @@ -#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } -param( - $ModuleName = "dbatools", - $CommandName = "Find-DbaAgentJob", - $PSDefaultParameterValues = $TestConfig.Defaults -) - +$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -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", - "JobName", - "ExcludeJobName", - "StepName", - "LastUsed", - "IsDisabled", - "IsFailed", - "IsNotScheduled", - "IsNoEmailNotification", - "Category", - "Owner", - "Since", - "EnableException" - ) - } - - It "Should have the expected parameters" { - Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty +Describe "$CommandName Unit Tests" -Tag 'UnitTests' { + Context "Validate parameters" { + [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} + [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'JobName', 'ExcludeJobName', 'StepName', 'LastUsed', 'IsDisabled', 'IsFailed', 'IsNotScheduled', 'IsNoEmailNotification', 'Category', 'Owner', 'Since', 'EnableException' + $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters + It "Should only contain our specific parameters" { + (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 } } } -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 - - #subsystemServer needs the real underlying name, and it doesn't work if targeting something like localhost\namedinstance - # the typical error would be WARNING: [17:19:26][New-DbaAgentJobStep] Something went wrong creating the job step | The specified '@server' is - #invalid (valid values are returned by sp_helpserver). - $srvName = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Query "select @@servername as sn" -as PSObject - $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job "dbatoolsci_testjob" -OwnerLogin "sa" - $null = New-DbaAgentJobStep -SqlInstance $TestConfig.instance2 -Job "dbatoolsci_testjob" -StepId 1 -StepName "dbatoolsci Failed" -Subsystem TransactSql -SubsystemServer $srvName.sn -Command "RAISERROR (15600,-1,-1, 'dbatools_error');" -CmdExecSuccessCode 0 -OnSuccessAction QuitWithSuccess -OnFailAction QuitWithFailure -Database master -RetryAttempts 1 -RetryInterval 2 - $null = Start-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job "dbatoolsci_testjob" - $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job "dbatoolsregr_testjob" -OwnerLogin "sa" - $null = New-DbaAgentJobStep -SqlInstance $TestConfig.instance2 -Job "dbatoolsregr_testjob" -StepId 1 -StepName "dbatoolsci Failed" -Subsystem TransactSql -SubsystemServer $srvName.sn -Command "RAISERROR (15600,-1,-1, 'dbatools_error');" -CmdExecSuccessCode 0 -OnSuccessAction QuitWithSuccess -OnFailAction QuitWithFailure -Database master -RetryAttempts 1 -RetryInterval 2 - $null = New-DbaAgentJobCategory -SqlInstance $TestConfig.instance2 -Category "dbatoolsci_job_category" -CategoryType LocalJob - $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job "dbatoolsci_testjob_disabled" -Category "dbatoolsci_job_category" -Disabled - $null = New-DbaAgentJobStep -SqlInstance $TestConfig.instance2 -Job "dbatoolsci_testjob_disabled" -StepId 1 -StepName "dbatoolsci Test Step" -Subsystem TransactSql -SubsystemServer $srvName.sn -Command "SELECT * FROM master.sys.all_columns" -CmdExecSuccessCode 0 -OnSuccessAction QuitWithSuccess -OnFailAction QuitWithFailure -Database master -RetryAttempts 1 -RetryInterval 2 - - # 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 - - $null = Remove-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob, dbatoolsregr_testjob, dbatoolsci_testjob_disabled -Confirm:$false - $null = Remove-DbaAgentJobCategory -SqlInstance $TestConfig.instance2 -Category "dbatoolsci_job_category" -Confirm:$false - } +Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { Context "Command finds jobs using all parameters" { - It "Should find a specific job" { - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob - $results.name | Should -Be "dbatoolsci_testjob" + BeforeAll { + #subsystemServer needs the real underlying name, and it doesn't work if targeting something like localhost\namedinstance + # the typical error would be WARNING: [17:19:26][New-DbaAgentJobStep] Something went wrong creating the job step | The specified '@server' is + #invalid (valid values are returned by sp_helpserver). + $srvName = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Query "select @@servername as sn" -as PSObject + $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job 'dbatoolsci_testjob' -OwnerLogin 'sa' + $null = New-DbaAgentJobStep -SqlInstance $TestConfig.instance2 -Job 'dbatoolsci_testjob' -StepId 1 -StepName 'dbatoolsci Failed' -Subsystem TransactSql -SubsystemServer $srvName.sn -Command "RAISERROR (15600,-1,-1, 'dbatools_error');" -CmdExecSuccessCode 0 -OnSuccessAction QuitWithSuccess -OnFailAction QuitWithFailure -Database master -RetryAttempts 1 -RetryInterval 2 + $null = Start-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job 'dbatoolsci_testjob' + $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job 'dbatoolsregr_testjob' -OwnerLogin 'sa' + $null = New-DbaAgentJobStep -SqlInstance $TestConfig.instance2 -Job 'dbatoolsregr_testjob' -StepId 1 -StepName 'dbatoolsci Failed' -Subsystem TransactSql -SubsystemServer $srvName.sn -Command "RAISERROR (15600,-1,-1, 'dbatools_error');" -CmdExecSuccessCode 0 -OnSuccessAction QuitWithSuccess -OnFailAction QuitWithFailure -Database master -RetryAttempts 1 -RetryInterval 2 + $null = New-DbaAgentJobCategory -SqlInstance $TestConfig.instance2 -Category 'dbatoolsci_job_category' -CategoryType LocalJob + $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job 'dbatoolsci_testjob_disabled' -Category 'dbatoolsci_job_category' -Disabled + $null = New-DbaAgentJobStep -SqlInstance $TestConfig.instance2 -Job 'dbatoolsci_testjob_disabled' -StepId 1 -StepName 'dbatoolsci Test Step' -Subsystem TransactSql -SubsystemServer $srvName.sn -Command 'SELECT * FROM master.sys.all_columns' -CmdExecSuccessCode 0 -OnSuccessAction QuitWithSuccess -OnFailAction QuitWithFailure -Database master -RetryAttempts 1 -RetryInterval 2 + } + AfterAll { + $null = Remove-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob, dbatoolsregr_testjob, dbatoolsci_testjob_disabled -Confirm:$false + $null = Remove-DbaAgentJobCategory -SqlInstance $TestConfig.instance2 -Category 'dbatoolsci_job_category' -Confirm:$false } + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob + It "Should find a specific job" { + $results.name | Should Be "dbatoolsci_testjob" + } + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job *dbatoolsci* -ExcludeJobName dbatoolsci_testjob_disabled It "Should find a specific job but not an excluded job" { - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job *dbatoolsci* -ExcludeJobName dbatoolsci_testjob_disabled - $results.name | Should -Not -Be "dbatoolsci_testjob_disabled" + $results.name | Should Not Be "dbatoolsci_testjob_disabled" } - + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -StepName 'dbatoolsci Test Step' It "Should find a specific job with a specific step" { - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -StepName "dbatoolsci Test Step" - $results.name | Should -Be "dbatoolsci_testjob_disabled" + $results.name | Should Be "dbatoolsci_testjob_disabled" } - + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -LastUsed 10 It "Should find jobs not used in the last 10 days" { - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -LastUsed 10 - $results | Should -Not -BeNullOrEmpty + $results | Should not be null } - + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsDisabled It "Should find jobs disabled from running" { - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsDisabled - $results.name | Should -Be "dbatoolsci_testjob_disabled" + $results.name | Should be "dbatoolsci_testjob_disabled" } - + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsDisabled It "Should find 1 job disabled from running" { - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsDisabled - $results.count | Should -Be 1 + $results.count | Should be 1 } - + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsNotScheduled It "Should find jobs that have not been scheduled" { - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsNotScheduled - $results | Should -Not -BeNullOrEmpty + $results | Should not be null } - + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsNotScheduled -Job *dbatoolsci* It "Should find 2 jobs that have no schedule" { - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsNotScheduled -Job *dbatoolsci* - $results.count | Should -Be 2 + $results.count | Should be 2 } - + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsNoEmailNotification It "Should find jobs that have no email notification" { - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsNoEmailNotification - $results | Should -Not -BeNullOrEmpty + $results | Should not be null } - + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Category 'dbatoolsci_job_category' It "Should find jobs that have a category of dbatoolsci_job_category" { - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Category "dbatoolsci_job_category" - $results.name | Should -Be "dbatoolsci_testjob_disabled" + $results.name | Should be "dbatoolsci_testjob_disabled" } - + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Owner 'sa' It "Should find jobs that are owned by sa" { - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Owner "sa" - $results | Should -Not -BeNullOrEmpty + $results | Should not be null } - + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsFailed -Since '2016-07-01 10:47:00' It "Should find jobs that have been failed since July of 2016" { - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsFailed -Since "2016-07-01 10:47:00" - $results | Should -Not -BeNullOrEmpty + $results | Should not be null } - + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job *dbatoolsci*,*dbatoolsregr* -ExcludeJobName dbatoolsci_testjob_disabled It "Should work with multiple wildcard passed in (see #9572)" { - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job *dbatoolsci*, *dbatoolsregr* -ExcludeJobName dbatoolsci_testjob_disabled $results.Count | Should -Be 2 } } -} \ No newline at end of file +} diff --git a/tests/Get-DbaAgentJobHistory.Tests.ps1 b/tests/Get-DbaAgentJobHistory.Tests.ps1 index 2554bbd2e698..862a38dc0ff6 100644 --- a/tests/Get-DbaAgentJobHistory.Tests.ps1 +++ b/tests/Get-DbaAgentJobHistory.Tests.ps1 @@ -1,427 +1,398 @@ -#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } -param( - $ModuleName = "dbatools", - $CommandName = "Get-DbaAgentJobHistory", - $PSDefaultParameterValues = $TestConfig.Defaults -) - +$commandname = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe $CommandName -Tag UnitTests { +Describe "$CommandName Unit Tests" -Tag 'UnitTests' { Context "Validate parameters" { - BeforeAll { - $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } - $expectedParameters = $TestConfig.CommonParameters - $expectedParameters += @( - "SqlInstance", - "SqlCredential", - "Job", - "ExcludeJob", - "StartDate", - "EndDate", - "OutcomeType", - "ExcludeJobSteps", - "WithOutputFile", - "JobCollection", - "EnableException" - ) - } - + [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } + [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Job', 'ExcludeJob', 'StartDate', 'EndDate', 'OutcomeType', 'ExcludeJobSteps', 'WithOutputFile', 'JobCollection', 'EnableException' + $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters It "Should only contain our specific parameters" { - Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty + (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 } } } -Describe $CommandName -Tag UnitTests { - InModuleScope "dbatools" { - BeforeAll { - Mock Connect-DbaInstance -MockWith { - # Thanks @Fred - $obj = [PSCustomObject]@{ - Name = "BASEName" - ComputerName = "BASEComputerName" - InstanceName = "BASEInstanceName" - DomainInstanceName = "BASEDomainInstanceName" - InstallDataDirectory = "BASEInstallDataDirectory" - ErrorLogPath = "BASEErrorLog_{0}_{1}_{2}_Path" -f "'", '"', "]" - ServiceName = "BASEServiceName" - JobServer = New-Object PSObject - ConnectionContext = New-Object PSObject - } - Add-Member -InputObject $obj.ConnectionContext -Name ConnectionString -MemberType NoteProperty -Value "put=an=equal=in=it" - Add-Member -InputObject $obj.JobServer -Name EnumJobHistory -MemberType ScriptMethod -Value { - param ($filter) - return @( - @{ - JobName = "Job1" - JobID = [guid]"E7718A84-8B43-46D0-8F8D-4FC4464F9FC5" - StepID = 0 - StepName = "(Job outcome)" - RunDate = [DateTime]::Parse("2017-09-26T13:00:00") - RunDuration = 112 - RunStatus = 0 - }, - @{ - JobName = "Job1" - JobID = [guid]"E7718A84-8B43-46D0-8F8D-4FC4464F9FC5" - StepID = 1 - StepName = "Job1Step1" - RunDate = [DateTime]::Parse("2017-09-26T13:00:00") - RunDuration = 1 - RunStatus = 0 - }, - @{ - JobName = "Job1" - JobID = [guid]"E7718A84-8B43-46D0-8F8D-4FC4464F9FC5" - StepID = 2 - StepName = "Job1Step2" - RunDate = [DateTime]::Parse("2017-09-26T13:00:01") - RunDuration = 1 - RunStatus = 0 - }, - @{ - JobName = "Job2" - JobID = [guid]"9C9A6819-58CE-451A-8DD7-6D17593F0DFA" - StepID = 0 - StepName = "(Job outcome)" - RunDate = [DateTime]::Parse("2017-09-26T01:00:00") - RunDuration = 2 - RunStatus = 0 - }, - @{ - JobName = "Job2" - JobID = [guid]"9C9A6819-58CE-451A-8DD7-6D17593F0DFA" - StepID = 1 - StepName = "Job2Step1" - RunDate = [DateTime]::Parse("2017-09-26T01:00:00") - RunDuration = 1 - RunStatus = 0 - }, - @{ - JobName = "Job2" - JobID = [guid]"9C9A6819-58CE-451A-8DD7-6D17593F0DFA" - StepID = 2 - StepName = "Job2Step2" - RunDate = [DateTime]::Parse("2017-09-26T01:00:01") - RunDuration = 1 - RunStatus = 0 - } - ) - } - $obj.PSObject.TypeNames.Clear() - $obj.PSObject.TypeNames.Add("Microsoft.SqlServer.Management.Smo.Server") - return $obj - } #mock Connect-DbaInstance - } - Context "Return values" { - BeforeAll { - Mock Get-DbaAgentJobOutputFile -MockWith { - @( - @{ - Job = "Job1" - StepId = 1 - OutputFileName = "Job1Output1" - }, - @{ - Job = "Job1" - StepId = 2 - OutputFileName = "Job1Output2" - }, - @{ - Job = "Job2" - StepId = 2 - OutputFileName = "Job2Output1" - } - ) - } +Describe "$CommandName Unittests" -Tag 'UnitTests' { + InModuleScope 'dbatools' { + Mock Connect-DbaInstance -MockWith { + # Thanks @Fred + $obj = [PSCustomObject]@{ + Name = 'BASEName' + ComputerName = 'BASEComputerName' + InstanceName = 'BASEInstanceName' + DomainInstanceName = 'BASEDomainInstanceName' + InstallDataDirectory = 'BASEInstallDataDirectory' + ErrorLogPath = 'BASEErrorLog_{0}_{1}_{2}_Path' -f "'", '"', ']' + ServiceName = 'BASEServiceName' + JobServer = New-Object PSObject + ConnectionContext = New-Object PSObject + } + Add-Member -InputObject $obj.ConnectionContext -Name ConnectionString -MemberType NoteProperty -Value 'put=an=equal=in=it' + Add-Member -InputObject $obj.JobServer -Name EnumJobHistory -MemberType ScriptMethod -Value { + param ($filter) + return @( + @{ + JobName = 'Job1' + JobID = [guid]'E7718A84-8B43-46D0-8F8D-4FC4464F9FC5' + StepID = 0 + StepName = '(Job outcome)' + RunDate = [DateTime]::Parse('2017-09-26T13:00:00') + RunDuration = 112 + RunStatus = 0 + }, + @{ + JobName = 'Job1' + JobID = [guid]'E7718A84-8B43-46D0-8F8D-4FC4464F9FC5' + StepID = 1 + StepName = 'Job1Step1' + RunDate = [DateTime]::Parse('2017-09-26T13:00:00') + RunDuration = 1 + RunStatus = 0 + }, + @{ + JobName = 'Job1' + JobID = [guid]'E7718A84-8B43-46D0-8F8D-4FC4464F9FC5' + StepID = 2 + StepName = 'Job1Step2' + RunDate = [DateTime]::Parse('2017-09-26T13:00:01') + RunDuration = 1 + RunStatus = 0 + }, + @{ + JobName = 'Job2' + JobID = [guid]'9C9A6819-58CE-451A-8DD7-6D17593F0DFA' + StepID = 0 + StepName = '(Job outcome)' + RunDate = [DateTime]::Parse('2017-09-26T01:00:00') + RunDuration = 2 + RunStatus = 0 + }, + @{ + JobName = 'Job2' + JobID = [guid]'9C9A6819-58CE-451A-8DD7-6D17593F0DFA' + StepID = 1 + StepName = 'Job2Step1' + RunDate = [DateTime]::Parse('2017-09-26T01:00:00') + RunDuration = 1 + RunStatus = 0 + }, + @{ + JobName = 'Job2' + JobID = [guid]'9C9A6819-58CE-451A-8DD7-6D17593F0DFA' + StepID = 2 + StepName = 'Job2Step2' + RunDate = [DateTime]::Parse('2017-09-26T01:00:01') + RunDuration = 1 + RunStatus = 0 + } + ) } + $obj.PSObject.TypeNames.Clear() + $obj.PSObject.TypeNames.Add("Microsoft.SqlServer.Management.Smo.Server") + return $obj + } #mock Connect-DbaInstance + Context "Return values" { + Mock Get-DbaAgentJobOutputFile -MockWith { + @( + @{ + Job = 'Job1' + StepId = 1 + OutputFileName = 'Job1Output1' + }, + @{ + Job = 'Job1' + StepId = 2 + OutputFileName = 'Job1Output2' + }, + @{ + Job = 'Job2' + StepId = 2 + OutputFileName = 'Job2Output1' + } + ) + } It "Throws when ExcludeJobSteps and WithOutputFile" { - { Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -ExcludeJobSteps -WithOutputFile -EnableException } | Should -Throw + { Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -ExcludeJobSteps -WithOutputFile -EnableException } | Should Throw } - It "Returns full history by default" { $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" - $Results.Length | Should -Be 6 + $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' + $Results.Length | Should Be 6 } - It "Returns only runs with no steps with ExcludeJobSteps" { $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -ExcludeJobSteps - $Results.Length | Should -Be 2 + $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -ExcludeJobSteps + $Results.Length | Should Be 2 } - - It "Returns our own ""augmented"" properties, too" { + It 'Returns our own "augmented" properties, too' { $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -ExcludeJobSteps - $Results[0].psobject.properties.Name | Should -Contain "StartDate" - $Results[0].psobject.properties.Name | Should -Contain "EndDate" - $Results[0].psobject.properties.Name | Should -Contain "Duration" + $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -ExcludeJobSteps + $Results[0].psobject.properties.Name | Should -Contain 'StartDate' + $Results[0].psobject.properties.Name | Should -Contain 'EndDate' + $Results[0].psobject.properties.Name | Should -Contain 'Duration' } - - It "Returns ""augmented"" properties that are correct" { + It 'Returns "augmented" properties that are correct' { $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -ExcludeJobSteps + $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -ExcludeJobSteps $Results[0].StartDate | Should -Be $Results[0].RunDate $Results[0].RunDuration | Should -Be 112 $Results[0].Duration.TotalSeconds | Should -Be 72 $Results[0].EndDate | Should -Be ($Results[0].StartDate.AddSeconds($Results[0].Duration.TotalSeconds)) } - It "Figures out plain outputfiles" { $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile + $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -WithOutputFile # no output for outcomes - ($Results | Where-Object StepID -eq 0).Length | Should -Be 2 - ($Results | Where-Object StepID -eq 0).OutputFileName -Join "" | Should -Be "" + ($Results | Where-Object StepID -eq 0).Length | Should Be 2 + ($Results | Where-Object StepID -eq 0).OutputFileName -Join '' | Should Be '' # correct output for job1 - ($Results | Where-Object StepID -ne 0 | Where-Object JobName -eq "Job1").OutputFileName | Should -Match "Job1Output[12]" + ($Results | Where-Object StepID -ne 0 | Where-Object JobName -eq 'Job1').OutputFileName | Should Match 'Job1Output[12]' # correct output for job2 - ($Results | Where-Object StepID -eq 2 | Where-Object JobName -eq "Job2").OutputFileName | Should -Match "Job2Output1" - ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job2").OutputFileName | Should -Be "" + ($Results | Where-Object StepID -eq 2 | Where-Object JobName -eq 'Job2').OutputFileName | Should Match 'Job2Output1' + ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq 'Job2').OutputFileName | Should Be '' } } - Context "SQL Agent Tokens" { It "Handles INST" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ - Job = "Job1" + Job = 'Job1' StepId = 1 - OutputFileName = "`$(INST)__Job1Output1" + OutputFileName = '$(INST)__Job1Output1' } ) } $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile + $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -WithOutputFile - ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "BASEServiceName__Job1Output1" - } + ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq 'Job1').OutputFileName | Should Be 'BASEServiceName__Job1Output1' + } It "Handles MACH" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ - Job = "Job1" + Job = 'Job1' StepId = 1 - OutputFileName = "`$(MACH)__Job1Output1" + OutputFileName = '$(MACH)__Job1Output1' } ) } $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile + $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -WithOutputFile - ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "BASEComputerName__Job1Output1" - } + ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq 'Job1').OutputFileName | Should Be 'BASEComputerName__Job1Output1' + } It "Handles SQLDIR" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ - Job = "Job1" + Job = 'Job1' StepId = 1 - OutputFileName = "`$(SQLDIR)__Job1Output1" + OutputFileName = '$(SQLDIR)__Job1Output1' } ) } $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile + $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -WithOutputFile - ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "BASEInstallDataDirectory__Job1Output1" - } + ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq 'Job1').OutputFileName | Should Be 'BASEInstallDataDirectory__Job1Output1' + } It "Handles SQLLOGDIR" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ - Job = "Job1" + Job = 'Job1' StepId = 1 - OutputFileName = "`$(SQLLOGDIR)__Job1Output1" + OutputFileName = '$(SQLLOGDIR)__Job1Output1' } ) } $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile + $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -WithOutputFile - ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "BASEErrorLog_''_""_]_Path__Job1Output1" - } + ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq 'Job1').OutputFileName | Should Be 'BASEErrorLog_''_"_]_Path__Job1Output1' + } It "Handles SRVR" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ - Job = "Job1" + Job = 'Job1' StepId = 1 - OutputFileName = "`$(SRVR)__Job1Output1" + OutputFileName = '$(SRVR)__Job1Output1' } ) } $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile + $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -WithOutputFile + + ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq 'Job1').OutputFileName | Should Be 'BASEDomainInstanceName__Job1Output1' - ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "BASEDomainInstanceName__Job1Output1" } It "Handles STEPID" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ - Job = "Job1" + Job = 'Job1' StepId = 1 - OutputFileName = "`$(STEPID)__Job1Output1" + OutputFileName = '$(STEPID)__Job1Output1' } ) } $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile - ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "1__Job1Output1" - } + $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -WithOutputFile + ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq 'Job1').OutputFileName | Should Be '1__Job1Output1' + } It "Handles JOBID" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ - Job = "Job1" + Job = 'Job1' StepId = 1 - OutputFileName = "`$(JOBID)__Job1Output1" + OutputFileName = '$(JOBID)__Job1Output1' } ) } $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile + $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -WithOutputFile + + ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq 'Job1').OutputFileName | Should Be '0x848A71E7438BD0468F8D4FC4464F9FC5__Job1Output1' - ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "0x848A71E7438BD0468F8D4FC4464F9FC5__Job1Output1" } + It "Handles STRTDT" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ - Job = "Job1" + Job = 'Job1' StepId = 1 - OutputFileName = "`$(STRTDT)__Job1Output1" + OutputFileName = '$(STRTDT)__Job1Output1' } ) } $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile - ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "20170926__Job1Output1" + $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -WithOutputFile + ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq 'Job1').OutputFileName | Should Be '20170926__Job1Output1' } - It "Handles STRTTM" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ - Job = "Job1" + Job = 'Job1' StepId = 1 - OutputFileName = "`$(STRTTM)__Job1Output1" + OutputFileName = '$(STRTTM)__Job1Output1' } ) } $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile - ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "130000__Job1Output1" + $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -WithOutputFile + ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq 'Job1').OutputFileName | Should Be '130000__Job1Output1' } - It "Handles DATE" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ - Job = "Job1" + Job = 'Job1' StepId = 1 - OutputFileName = "`$(DATE)__Job1Output1" + OutputFileName = '$(DATE)__Job1Output1' } ) } $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile - ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "20170926__Job1Output1" + $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -WithOutputFile + ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq 'Job1').OutputFileName | Should Be '20170926__Job1Output1' } It "Handles TIME" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ - Job = "Job1" + Job = 'Job1' StepId = 2 - OutputFileName = "`$(TIME)__Job1Output1" + OutputFileName = '$(TIME)__Job1Output1' } ) } $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile - ($Results | Where-Object StepID -eq 2 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "130001__Job1Output1" + $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -WithOutputFile + ($Results | Where-Object StepID -eq 2 | Where-Object JobName -eq 'Job1').OutputFileName | Should Be '130001__Job1Output1' + } } - Context "SQL Agent escape sequences" { It "Handles ESCAPE_NONE" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ - Job = "Job1" + Job = 'Job1' StepId = 1 - OutputFileName = "`$(ESCAPE_NONE(SQLLOGDIR))__Job1Output1" + OutputFileName = '$(ESCAPE_NONE(SQLLOGDIR))__Job1Output1' } ) } $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile + $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -WithOutputFile - ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "BASEErrorLog_''_""_]_Path__Job1Output1" - } + ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq 'Job1').OutputFileName | Should Be 'BASEErrorLog_''_"_]_Path__Job1Output1' + } It "Handles ESCAPE_SQUOTE" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ - Job = "Job1" + Job = 'Job1' StepId = 1 - OutputFileName = "`$(ESCAPE_SQUOTE(SQLLOGDIR))__Job1Output1" + OutputFileName = '$(ESCAPE_SQUOTE(SQLLOGDIR))__Job1Output1' } ) } $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile + $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -WithOutputFile - ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "BASEErrorLog_''''_""_]_Path__Job1Output1" - } + ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq 'Job1').OutputFileName | Should Be 'BASEErrorLog_''''_"_]_Path__Job1Output1' + } It "Handles ESCAPE_DQUOTE" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ - Job = "Job1" + Job = 'Job1' StepId = 1 - OutputFileName = "`$(ESCAPE_DQUOTE(SQLLOGDIR))__Job1Output1" + OutputFileName = '$(ESCAPE_DQUOTE(SQLLOGDIR))__Job1Output1' } ) } $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile + $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -WithOutputFile - ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "BASEErrorLog_''_""""_]_Path__Job1Output1" - } + ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq 'Job1').OutputFileName | Should Be 'BASEErrorLog_''_""_]_Path__Job1Output1' + } It "Handles ESCAPE_RBRACKET" { Mock Get-DbaAgentJobOutputFile -MockWith { @( @{ - Job = "Job1" + Job = 'Job1' StepId = 1 - OutputFileName = "`$(ESCAPE_RBRACKET(SQLLOGDIR))__Job1Output1" + OutputFileName = '$(ESCAPE_RBRACKET(SQLLOGDIR))__Job1Output1' } ) } $Results = @() - $Results += Get-DbaAgentJobHistory -SqlInstance "SQLServerName" -WithOutputFile + $Results += Get-DbaAgentJobHistory -SqlInstance 'SQLServerName' -WithOutputFile + + ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq 'Job1').OutputFileName | Should Be 'BASEErrorLog_''_"_]]_Path__Job1Output1' - ($Results | Where-Object StepID -eq 1 | Where-Object JobName -eq "Job1").OutputFileName | Should -Be "BASEErrorLog_''_""_]]_Path__Job1Output1" } } } diff --git a/tests/Get-DbaAgentLog.Tests.ps1 b/tests/Get-DbaAgentLog.Tests.ps1 index 5d07c32f5dfc..1445215a9d62 100644 --- a/tests/Get-DbaAgentLog.Tests.ps1 +++ b/tests/Get-DbaAgentLog.Tests.ps1 @@ -1,55 +1,35 @@ -#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } -param( - $ModuleName = "dbatools", - $CommandName = "Get-DbaAgentLog", - $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", - "LogNumber", - "EnableException" - ) - } - - It "Should have the expected parameters" { - Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty +$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', 'LogNumber', 'EnableException' + $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters + It "Should only contain our specific parameters" { + (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 } } } -Describe $CommandName -Tag IntegrationTests { +Describe "$commandname Integration Tests" -Tags "IntegrationTests" { Context "Command gets agent log" { - BeforeAll { - $results = Get-DbaAgentLog -SqlInstance $TestConfig.instance2 - } - + $results = Get-DbaAgentLog -SqlInstance $TestConfig.instance2 It "Results are not empty" { - $results | Should -Not -BeNullOrEmpty + $results | Should Not Be $Null } - It "Results contain SQLServerAgent version" { - $results.text -like "`[100`] Microsoft SQLServerAgent version*" | Should -Be $true + $results.text -like '`[100`] Microsoft SQLServerAgent version*' | Should Be $true } - It "LogDate is a DateTime type" { - ($results | Select-Object -First 1).LogDate | Should -BeOfType DateTime + $($results | Select-Object -first 1).LogDate | Should BeOfType DateTime } } - Context "Command gets current agent log using LogNumber parameter" { - BeforeAll { - $logResults = Get-DbaAgentLog -SqlInstance $TestConfig.instance2 -LogNumber 0 - } - + $results = Get-DbaAgentLog -SqlInstance $TestConfig.instance2 -LogNumber 0 It "Results are not empty" { - $logResults | Should -Not -BeNullOrEmpty + $results | Should Not Be $Null } } -} \ No newline at end of file +} diff --git a/tests/New-DbaDbTransfer.Tests.ps1 b/tests/New-DbaDbTransfer.Tests.ps1 index fd908d456c4d..a0f791d6630a 100644 --- a/tests/New-DbaDbTransfer.Tests.ps1 +++ b/tests/New-DbaDbTransfer.Tests.ps1 @@ -1,123 +1,114 @@ -#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } -param( - $ModuleName = "dbatools", - $CommandName = "New-DbaDbTransfer", - $PSDefaultParameterValues = $TestConfig.Defaults -) - +$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -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", - "DestinationSqlInstance", - "DestinationSqlCredential", - "Database", - "DestinationDatabase", - "BatchSize", - "BulkCopyTimeOut", - "InputObject", - "EnableException", - "CopyAllObjects", - "CopyAll", - "SchemaOnly", - "DataOnly", - "ScriptingOption" - ) - } - - It "Should have the expected parameters" { - Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty +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', + 'DestinationSqlInstance', + 'DestinationSqlCredential', + 'Database', + 'DestinationDatabase', + 'BatchSize', + 'BulkCopyTimeOut', + 'InputObject', + 'EnableException', + 'CopyAllObjects', + 'CopyAll', + 'SchemaOnly', + 'DataOnly', + 'ScriptingOption' + ) + $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 IntegrationTests { +Describe "$commandname Integration Tests" -Tags "IntegrationTests" { BeforeAll { - $global:dbName = "dbatools_transfer" - $global:source = Connect-DbaInstance -SqlInstance $TestConfig.instance1 - $global:destination = Connect-DbaInstance -SqlInstance $TestConfig.instance2 - $global:source.Query("CREATE DATABASE $global:dbName") - $global:db = Get-DbaDatabase -SqlInstance $TestConfig.instance1 -Database $global:dbName - $null = $global:db.Query("CREATE TABLE dbo.transfer_test (id int); + $dbName = 'dbatools_transfer' + $source = Connect-DbaInstance -SqlInstance $TestConfig.instance1 + $destination = Connect-DbaInstance -SqlInstance $TestConfig.instance2 + $source.Query("CREATE DATABASE $dbName") + $db = Get-DbaDatabase -SqlInstance $TestConfig.instance1 -Database $dbName + $null = $db.Query("CREATE TABLE dbo.transfer_test (id int); INSERT dbo.transfer_test SELECT top 10 1 FROM sys.objects") - $null = $global:db.Query("CREATE TABLE dbo.transfer_test2 (id int)") - $null = $global:db.Query("CREATE TABLE dbo.transfer_test3 (id int)") - $null = $global:db.Query("CREATE TABLE dbo.transfer_test4 (id int); + $null = $db.Query("CREATE TABLE dbo.transfer_test2 (id int)") + $null = $db.Query("CREATE TABLE dbo.transfer_test3 (id int)") + $null = $db.Query("CREATE TABLE dbo.transfer_test4 (id int); INSERT dbo.transfer_test4 SELECT top 13 1 FROM sys.objects") - $global:allowedObjects = @( - "FullTextCatalogs", - "FullTextStopLists", - "SearchPropertyLists", - "Tables", - "Views", - "StoredProcedures", - "UserDefinedFunctions", - "UserDefinedDataTypes", - "UserDefinedTableTypes", - "PlanGuides", - "Rules", - "Defaults", - "Users", - "Roles", - "PartitionSchemes", - "PartitionFunctions", - "XmlSchemaCollections", - "SqlAssemblies", - "UserDefinedAggregates", - "UserDefinedTypes", - "Schemas", - "Synonyms", - "Sequences", - "DatabaseTriggers", - "DatabaseScopedCredentials", - "ExternalFileFormats", - "ExternalDataSources", - "Logins", - "ExternalLibraries" + $allowedObjects = @( + 'FullTextCatalogs', + 'FullTextStopLists', + 'SearchPropertyLists', + 'Tables', + 'Views', + 'StoredProcedures', + 'UserDefinedFunctions', + 'UserDefinedDataTypes', + 'UserDefinedTableTypes', + 'PlanGuides', + 'Rules', + 'Defaults', + 'Users', + 'Roles', + 'PartitionSchemes', + 'PartitionFunctions', + 'XmlSchemaCollections', + 'SqlAssemblies', + 'UserDefinedAggregates', + 'UserDefinedTypes', + 'Schemas', + 'Synonyms', + 'Sequences', + 'DatabaseTriggers', + 'DatabaseScopedCredentials', + 'ExternalFileFormats', + 'ExternalDataSources', + 'Logins', + 'ExternalLibraries' ) - $securePassword = "bar" | ConvertTo-SecureString -AsPlainText -Force - $global:creds = New-Object PSCredential ("foo", $securePassword) + $securePassword = 'bar' | ConvertTo-SecureString -AsPlainText -Force + $creds = New-Object PSCredential ('foo', $securePassword) } AfterAll { try { - $null = $global:db.Query("DROP TABLE dbo.transfer_test") - $null = $global:db.Query("DROP TABLE dbo.transfer_test2") - $null = $global:db.Query("DROP TABLE dbo.transfer_test3") - $null = $global:db.Query("DROP TABLE dbo.transfer_test4") + $null = $db.Query("DROP TABLE dbo.transfer_test") + $null = $db.Query("DROP TABLE dbo.transfer_test2") + $null = $db.Query("DROP TABLE dbo.transfer_test3") + $null = $db.Query("DROP TABLE dbo.transfer_test4") } catch { $null = 1 } - Remove-DbaDatabase -SqlInstance $TestConfig.instance1 -Database $global:dbName -Confirm:$false -ErrorAction SilentlyContinue + Remove-DbaDatabase -SqlInstance $TestConfig.instance1 -Database $dbName -Confirm:$false } Context "Testing connection parameters" { It "Should create a transfer object" { - $transfer = New-DbaDbTransfer -SqlInstance $TestConfig.instance1 -Database $global:dbName + $transfer = New-DbaDbTransfer -SqlInstance $TestConfig.instance1 -Database $dbName $transfer | Should -BeOfType Microsoft.SqlServer.Management.Smo.Transfer $transfer.BatchSize | Should -Be 50000 $transfer.BulkCopyTimeout | Should -Be 5000 - $transfer.Database.Name | Should -Be $global:dbName + $transfer.Database.Name | Should -Be $dbName $transfer.ObjectList | Should -BeNullOrEmpty $transfer.CopyAllObjects | Should -Be $false - $global:allowedObjects | ForEach-Object { $transfer.$_ | Should -BeNullOrEmpty } + $allowedObjects | ForEach-Object { $transfer.$_ | Should -BeNullOrEmpty } $transfer.CopyData | Should -Be $true $transfer.CopySchema | Should -Be $true - $transfer.DestinationDatabase | Should -Be $global:dbName + $transfer.DestinationDatabase | Should -Be $dbName $transfer.DestinationServer | Should -BeNullOrEmpty } It "Should properly assign dest server parameters from full connstring" { - $transfer = New-DbaDbTransfer -SqlInstance $TestConfig.instance1 -Database $global:dbName -DestinationSqlInstance "Data Source=foo;User=bar;password=foobar;Initial Catalog=hog" + $transfer = New-DbaDbTransfer -SqlInstance $TestConfig.instance1 -Database $dbName -DestinationSqlInstance 'Data Source=foo;User=bar;password=foobar;Initial Catalog=hog' $transfer.DestinationDatabase | Should -Be hog $transfer.DestinationLoginSecure | Should -Be $false $transfer.DestinationLogin | Should -Be bar @@ -125,8 +116,8 @@ Describe $CommandName -Tag IntegrationTests { $transfer.DestinationServer | Should -Be foo } It "Should properly assign dest server parameters from trusted connstring" { - $transfer = New-DbaDbTransfer -SqlInstance $TestConfig.instance1 -Database $global:dbName -DestinationSqlInstance "Data Source=foo;Integrated Security=True" - $transfer.DestinationDatabase | Should -Be $global:dbName + $transfer = New-DbaDbTransfer -SqlInstance $TestConfig.instance1 -Database $dbName -DestinationSqlInstance 'Data Source=foo;Integrated Security=True' + $transfer.DestinationDatabase | Should -Be $dbName $transfer.DestinationLoginSecure | Should -Be $true $transfer.DestinationLogin | Should -BeNullOrEmpty $transfer.DestinationPassword | Should -BeNullOrEmpty @@ -135,108 +126,108 @@ Describe $CommandName -Tag IntegrationTests { It "Should properly assign dest server parameters from server object" { $dest = Connect-DbaInstance -SqlInstance $TestConfig.instance2 -Database msdb $connStringBuilder = New-Object Microsoft.Data.SqlClient.SqlConnectionStringBuilder $dest.ConnectionContext.ConnectionString - $transfer = New-DbaDbTransfer -SqlInstance $TestConfig.instance1 -Database $global:dbName -DestinationSqlInstance $dest - $transfer.DestinationDatabase | Should -Be $connStringBuilder["Initial Catalog"] - $transfer.DestinationLoginSecure | Should -Be $connStringBuilder["Integrated Security"] - $transfer.DestinationLogin | Should -Be $connStringBuilder["User ID"] - $transfer.DestinationPassword | Should -Be $connStringBuilder["Password"] - $transfer.DestinationServer | Should -Be $connStringBuilder["Data Source"] + $transfer = New-DbaDbTransfer -SqlInstance $TestConfig.instance1 -Database $dbName -DestinationSqlInstance $dest + $transfer.DestinationDatabase | Should -Be $connStringBuilder['Initial Catalog'] + $transfer.DestinationLoginSecure | Should -Be $connStringBuilder['Integrated Security'] + $transfer.DestinationLogin | Should -Be $connStringBuilder['User ID'] + $transfer.DestinationPassword | Should -Be $connStringBuilder['Password'] + $transfer.DestinationServer | Should -Be $connStringBuilder['Data Source'] } It "Should properly assign dest server parameters from plaintext params" { - $transfer = New-DbaDbTransfer -SqlInstance $TestConfig.instance1 -Database $global:dbName -DestinationSqlInstance foo -DestinationDatabase bar -DestinationSqlCredential $global:creds + $transfer = New-DbaDbTransfer -SqlInstance $TestConfig.instance1 -Database $dbName -DestinationSqlInstance foo -DestinationDatabase bar -DestinationSqlCredential $creds $transfer.DestinationDatabase | Should -Be bar $transfer.DestinationLoginSecure | Should -Be $false - $transfer.DestinationLogin | Should -Be $global:creds.UserName - $transfer.DestinationPassword | Should -Be $global:creds.GetNetworkCredential().Password + $transfer.DestinationLogin | Should -Be $creds.UserName + $transfer.DestinationPassword | Should -Be $creds.GetNetworkCredential().Password $transfer.DestinationServer | Should -Be foo } } Context "Testing function parameters" { It "Should script all objects" { - $transfer = New-DbaDbTransfer -SqlInstance $TestConfig.instance1 -Database $global:dbName -CopyAllObjects + $transfer = New-DbaDbTransfer -SqlInstance $TestConfig.instance1 -Database $dbName -CopyAllObjects $transfer.CopyData | Should -Be $true $transfer.CopySchema | Should -Be $true $script = $transfer.ScriptTransfer() -join "`n" - $script | Should -BeLike "*CREATE TABLE `[dbo`].`[transfer_test`]*" - $script | Should -BeLike "*CREATE TABLE `[dbo`].`[transfer_test2`]*" - $script | Should -BeLike "*CREATE TABLE `[dbo`].`[transfer_test3`]*" - $script | Should -BeLike "*CREATE TABLE `[dbo`].`[transfer_test4`]*" + $script | Should -BeLike '*CREATE TABLE `[dbo`].`[transfer_test`]*' + $script | Should -BeLike '*CREATE TABLE `[dbo`].`[transfer_test2`]*' + $script | Should -BeLike '*CREATE TABLE `[dbo`].`[transfer_test3`]*' + $script | Should -BeLike '*CREATE TABLE `[dbo`].`[transfer_test4`]*' } It "Should script all tables with just schemas" { - $transfer = New-DbaDbTransfer -SqlInstance $TestConfig.instance1 -Database $global:dbName -CopyAll Tables -SchemaOnly + $transfer = New-DbaDbTransfer -SqlInstance $TestConfig.instance1 -Database $dbName -CopyAll Tables -SchemaOnly $transfer.CopyData | Should -Be $false $transfer.CopySchema | Should -Be $true $script = $transfer.ScriptTransfer() -join "`n" - $script | Should -BeLike "*CREATE TABLE `[dbo`].`[transfer_test`]*" - $script | Should -BeLike "*CREATE TABLE `[dbo`].`[transfer_test2`]*" - $script | Should -BeLike "*CREATE TABLE `[dbo`].`[transfer_test3`]*" - $script | Should -BeLike "*CREATE TABLE `[dbo`].`[transfer_test4`]*" + $script | Should -BeLike '*CREATE TABLE `[dbo`].`[transfer_test`]*' + $script | Should -BeLike '*CREATE TABLE `[dbo`].`[transfer_test2`]*' + $script | Should -BeLike '*CREATE TABLE `[dbo`].`[transfer_test3`]*' + $script | Should -BeLike '*CREATE TABLE `[dbo`].`[transfer_test4`]*' } It "Should script one table with just data" { - $table = Get-DbaDbTable -SqlInstance $TestConfig.instance1 -Database $global:dbName -Table transfer_test - $transfer = New-DbaDbTransfer -SqlInstance $TestConfig.instance1 -Database $global:dbName -InputObject $table -DataOnly + $table = Get-DbaDbTable -SqlInstance $TestConfig.instance1 -Database $dbName -Table transfer_test + $transfer = New-DbaDbTransfer -SqlInstance $TestConfig.instance1 -Database $dbName -InputObject $table -DataOnly $transfer.ObjectList.Count | Should -Be 1 $transfer.CopyData | Should -Be $true $transfer.CopySchema | Should -Be $false # # data only ScriptTransfer still creates schema $script = $transfer.ScriptTransfer() -join "`n" - $script | Should -BeLike "*CREATE TABLE `[dbo`].`[transfer_test`]*" + $script | Should -BeLike '*CREATE TABLE `[dbo`].`[transfer_test`]*' } It "Should script two tables from pipeline" { - $tables = Get-DbaDbTable -SqlInstance $TestConfig.instance1 -Database $global:dbName -Table transfer_test2, transfer_test4 - $transfer = $tables | New-DbaDbTransfer -SqlInstance $TestConfig.instance1 -Database $global:dbName + $tables = Get-DbaDbTable -SqlInstance $TestConfig.instance1 -Database $dbName -Table transfer_test2, transfer_test4 + $transfer = $tables | New-DbaDbTransfer -SqlInstance $TestConfig.instance1 -Database $dbName $transfer.ObjectList.Count | Should -Be 2 $script = $transfer.ScriptTransfer() -join "`n" - $script | Should -Not -BeLike "*CREATE TABLE `[dbo`].`[transfer_test`]*" - $script | Should -BeLike "*CREATE TABLE `[dbo`].`[transfer_test2`]*" - $script | Should -Not -BeLike "*CREATE TABLE `[dbo`].`[transfer_test3`]*" - $script | Should -BeLike "*CREATE TABLE `[dbo`].`[transfer_test4`]*" + $script | Should -Not -BeLike '*CREATE TABLE `[dbo`].`[transfer_test`]*' + $script | Should -BeLike '*CREATE TABLE `[dbo`].`[transfer_test2`]*' + $script | Should -Not -BeLike '*CREATE TABLE `[dbo`].`[transfer_test3`]*' + $script | Should -BeLike '*CREATE TABLE `[dbo`].`[transfer_test4`]*' } It "Should accept script options object" { $options = New-DbaScriptingOption $options.ScriptDrops = $true - $transfer = New-DbaDbTransfer -SqlInstance $TestConfig.instance1 -Database $global:dbName -CopyAll Tables -ScriptingOption $options + $transfer = New-DbaDbTransfer -SqlInstance $TestConfig.instance1 -Database $dbName -CopyAll Tables -ScriptingOption $options $transfer.Options.ScriptDrops | Should -BeTrue $script = $transfer.ScriptTransfer() -join "`n" - $script | Should -BeLike "*DROP TABLE `[dbo`].`[transfer_test`]*" + $script | Should -BeLike '*DROP TABLE `[dbo`].`[transfer_test`]*' } } Context "Testing object transfer" { BeforeEach { - $global:destination.Query("CREATE DATABASE $global:dbName") - $global:db2 = Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $global:dbName + $destination.Query("CREATE DATABASE $dbname") + $db2 = Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbName } AfterEach { - Remove-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $global:dbName -Confirm:$false -ErrorAction SilentlyContinue + Remove-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbName -Confirm:$false } It "Should transfer all tables" { - $transfer = New-DbaDbTransfer -SqlInstance $TestConfig.instance1 -DestinationSqlInstance $TestConfig.instance2 -Database $global:dbName -CopyAll Tables + $transfer = New-DbaDbTransfer -SqlInstance $TestConfig.instance1 -DestinationSqlInstance $TestConfig.instance2 -Database $dbName -CopyAll Tables $transfer.TransferData() - $tables = Get-DbaDbTable -SqlInstance $TestConfig.instance2 -Database $global:dbName -Table transfer_test, transfer_test2, transfer_test3, transfer_test4 + $tables = Get-DbaDbTable -SqlInstance $TestConfig.instance2 -Database $dbName -Table transfer_test, transfer_test2, transfer_test3, transfer_test4 $tables.Count | Should -Be 4 - $global:db.Query("select id from dbo.transfer_test").id | Should -Not -BeNullOrEmpty - $global:db.Query("select id from dbo.transfer_test4").id | Should -Not -BeNullOrEmpty - $global:db.Query("select id from dbo.transfer_test").id | Should -BeIn $global:db2.Query("select id from dbo.transfer_test").id - $global:db.Query("select id from dbo.transfer_test4").id | Should -BeIn $global:db2.Query("select id from dbo.transfer_test4").id + $db.Query("select id from dbo.transfer_test").id | Should -Not -BeNullOrEmpty + $db.Query("select id from dbo.transfer_test4").id | Should -Not -BeNullOrEmpty + $db.Query("select id from dbo.transfer_test").id | Should -BeIn $db2.Query("select id from dbo.transfer_test").id + $db.Query("select id from dbo.transfer_test4").id | Should -BeIn $db2.Query("select id from dbo.transfer_test4").id } It "Should transfer two tables with just schemas" { - $sourceTables = Get-DbaDbTable -SqlInstance $TestConfig.instance1 -Database $global:dbName -Table transfer_test, transfer_test2 - $transfer = $sourceTables | New-DbaDbTransfer -SqlInstance $TestConfig.instance1 -DestinationSqlInstance $TestConfig.instance2 -Database $global:dbName -SchemaOnly + $sourceTables = Get-DbaDbTable -SqlInstance $TestConfig.instance1 -Database $dbName -Table transfer_test, transfer_test2 + $transfer = $sourceTables | New-DbaDbTransfer -SqlInstance $TestConfig.instance1 -DestinationSqlInstance $TestConfig.instance2 -Database $dbName -SchemaOnly $transfer.TransferData() - $tables = Get-DbaDbTable -SqlInstance $TestConfig.instance2 -Database $global:dbName -Table transfer_test, transfer_test2 + $tables = Get-DbaDbTable -SqlInstance $TestConfig.instance2 -Database $dbName -Table transfer_test, transfer_test2 $tables.Count | Should -Be 2 - $global:db2.Query("select id from dbo.transfer_test").id | Should -BeNullOrEmpty + $db2.Query("select id from dbo.transfer_test").id | Should -BeNullOrEmpty } It "Should transfer two tables without copying schema" { - $null = $global:db2.Query("CREATE TABLE dbo.transfer_test (id int)") - $null = $global:db2.Query("CREATE TABLE dbo.transfer_test2 (id int)") - $sourceTables = Get-DbaDbTable -SqlInstance $TestConfig.instance1 -Database $global:dbName -Table transfer_test, transfer_test2 - $transfer = $sourceTables | New-DbaDbTransfer -SqlInstance $TestConfig.instance1 -DestinationSqlInstance $TestConfig.instance2 -Database $global:dbName -DataOnly + $null = $db2.Query("CREATE TABLE dbo.transfer_test (id int)") + $null = $db2.Query("CREATE TABLE dbo.transfer_test2 (id int)") + $sourceTables = Get-DbaDbTable -SqlInstance $TestConfig.instance1 -Database $dbName -Table transfer_test, transfer_test2 + $transfer = $sourceTables | New-DbaDbTransfer -SqlInstance $TestConfig.instance1 -DestinationSqlInstance $TestConfig.instance2 -Database $dbName -DataOnly $transfer.TransferData() - $tables = Get-DbaDbTable -SqlInstance $TestConfig.instance2 -Database $global:dbName -Table transfer_test, transfer_test2 + $tables = Get-DbaDbTable -SqlInstance $TestConfig.instance2 -Database $dbName -Table transfer_test, transfer_test2 $tables.Count | Should -Be 2 - $global:db.Query("select id from dbo.transfer_test").id | Should -Not -BeNullOrEmpty - $global:db.Query("select id from dbo.transfer_test").id | Should -BeIn $global:db2.Query("select id from dbo.transfer_test").id + $db.Query("select id from dbo.transfer_test").id | Should -Not -BeNullOrEmpty + $db.Query("select id from dbo.transfer_test").id | Should -BeIn $db2.Query("select id from dbo.transfer_test").id } } -} \ No newline at end of file +}