From 2740d7de5f628576476e25fba13fb05e1ad7c50d Mon Sep 17 00:00:00 2001 From: Chrissy LeMaire Date: Sun, 27 Oct 2024 13:49:14 +0100 Subject: [PATCH] Pester migration - Third batch (#9531) --- .aider/aider.psm1 | 17 +- .aider/prompts/conventions.md | 68 ++++---- tests/Copy-DbaAgentProxy.Tests.ps1 | 64 +++++--- tests/Copy-DbaAgentSchedule.Tests.ps1 | 67 +++++--- tests/Copy-DbaAgentServer.Tests.ps1 | 49 ++++-- tests/Copy-DbaBackupDevice.Tests.ps1 | 102 +++++++----- tests/Copy-DbaCustomError.Tests.ps1 | 97 +++++++---- tests/Copy-DbaDataCollector.Tests.ps1 | 49 ++++-- tests/Copy-DbaDbCertificate.Tests.ps1 | 107 ++++++++---- tests/Copy-DbaDbMail.Tests.ps1 | 92 ++++++----- tests/Copy-DbaDbQueryStoreOption.Tests.ps1 | 56 +++++-- tests/Copy-DbaDbTableData.Tests.ps1 | 74 +++++++-- tests/Copy-DbaEndpoint.Tests.ps1 | 61 ++++--- tests/Copy-DbaInstanceAudit.Tests.ps1 | 49 ++++-- ...py-DbaInstanceAuditSpecification.Tests.ps1 | 48 ++++-- tests/Copy-DbaInstanceTrigger.Tests.ps1 | 94 +++++++---- tests/Copy-DbaLinkedServer.Tests.ps1 | 154 ++++++++++++------ tests/Copy-DbaPolicyManagement.Tests.ps1 | 50 ++++-- tests/Copy-DbaRegServer.Tests.ps1 | 112 ++++++++----- tests/Copy-DbaResourceGovernor.Tests.ps1 | 142 ++++++++-------- tests/Copy-DbaSpConfigure.Tests.ps1 | 84 ++++++---- tests/Copy-DbaSsisCatalog.Tests.ps1 | 51 ++++-- tests/Copy-DbaStartupProcedure.Tests.ps1 | 58 ++++--- tests/Copy-DbaSystemDbUserObject.Tests.ps1 | 64 +++++--- tests/Copy-DbaXESession.Tests.ps1 | 48 ++++-- tests/Copy-DbaXESessionTemplate.Tests.ps1 | 46 ++++-- tests/Disable-DbaAgHadr.Tests.ps1 | 51 ++++-- tests/Disable-DbaDbEncryption.Tests.ps1 | 108 ++++++++---- tests/Disable-DbaFilestream.Tests.ps1 | 20 ++- ...isable-DbaForceNetworkEncryption.Tests.ps1 | 48 ++++-- tests/Disable-DbaHideInstance.Tests.ps1 | 48 ++++-- tests/Disable-DbaReplDistributor.Tests.ps1 | 43 +++-- tests/Disable-DbaReplPublishing.Tests.ps1 | 39 +++-- tests/Disable-DbaStartupProcedure.Tests.ps1 | 132 +++++++++++---- tests/Disable-DbaTraceFlag.Tests.ps1 | 73 +++++---- tests/Disconnect-DbaInstance.Tests.ps1 | 45 +++-- tests/Dismount-DbaDatabase.Tests.ps1 | 146 +++++++++-------- tests/Enable-DbaAgHadr.Tests.ps1 | 55 +++++-- tests/Enable-DbaDbEncryption.Tests.ps1 | 86 ++++++---- tests/Enable-DbaFilestream.Tests.ps1 | 64 +++++--- ...Enable-DbaForceNetworkEncryption.Tests.ps1 | 48 ++++-- tests/Enable-DbaHideInstance.Tests.ps1 | 52 ++++-- tests/Enable-DbaReplDistributor.Tests.ps1 | 43 +++-- tests/Enable-DbaReplPublishing.Tests.ps1 | 44 +++-- tests/Enable-DbaStartupProcedure.Tests.ps1 | 98 +++++++---- tests/Enable-DbaTraceFlag.Tests.ps1 | 72 +++++--- tests/pester.groups.ps1 | 1 + 47 files changed, 2113 insertions(+), 1106 deletions(-) diff --git a/.aider/aider.psm1 b/.aider/aider.psm1 index 93694b9f0e..f9bdbef18c 100644 --- a/.aider/aider.psm1 +++ b/.aider/aider.psm1 @@ -27,7 +27,10 @@ function Update-PesterTest { .PARAMETER MaxFileSize The maximum size of test files to process, in bytes. Files larger than this will be skipped. - Defaults to 8KB. + Defaults to 7.5kb. + + .PARAMETER Model + The AI model to use (e.g., azure/gpt-4o, gpt-4o-mini, claude-3-5-sonnet). .NOTES Tags: Testing, Pester @@ -61,7 +64,8 @@ function Update-PesterTest { [int]$Skip, [string[]]$PromptFilePath = "/workspace/.aider/prompts/template.md", [string[]]$CacheFilePath = @("/workspace/.aider/prompts/conventions.md","/workspace/private/testing/Get-TestConfig.ps1"), - [int]$MaxFileSize = 8kb + [int]$MaxFileSize = 7.5kb, + [string]$Model ) begin { # Full prompt path @@ -158,9 +162,10 @@ function Update-PesterTest { Message = $cmdPrompt File = $filename YesAlways = $true - Stream = $false + NoStream = $true CachePrompts = $true ReadFile = $CacheFilePath + Model = $Model } Write-Verbose "Invoking Aider to update test file" @@ -244,7 +249,7 @@ function Repair-Error { $aiderParams = @{ Message = $cmdPrompt File = $filename - Stream = $false + NoStream = $true CachePrompts = $true ReadFile = $CacheFilePath } @@ -386,7 +391,7 @@ function Repair-SmallThing { } # if file is larger than MaxFileSize, skip - if ((Get-Item $filename).Length -gt 8kb) { + if ((Get-Item $filename).Length -gt 7.5kb) { Write-Warning "Skipping $cmdName because it's too large" continue } @@ -715,7 +720,7 @@ function Repair-Error { $aiderParams = @{ Message = $cmdPrompt File = $filename - Stream = $false + NoStream = $true CachePrompts = $true ReadFile = $CacheFilePath } diff --git a/.aider/prompts/conventions.md b/.aider/prompts/conventions.md index 2008800ffa..abf901a042 100644 --- a/.aider/prompts/conventions.md +++ b/.aider/prompts/conventions.md @@ -126,28 +126,27 @@ Describe "Add-DbaAgReplica" -Tag "IntegrationTests" { ```powershell Describe "Get-DbaDatabase" -Tag "UnitTests" { - Context "Parameter validation" { - BeforeAll { - $command = Get-Command Get-DbaDatabase - $expected = $TestConfig.CommonParameters - $expected += @( - "SqlInstance", - "SqlCredential", - "Database", - "Confirm", - "WhatIf" - ) - } - - It "Has parameter: <_>" -ForEach $expected { - $command | Should -HaveParameter $PSItem - } - - It "Should have exactly the number of expected parameters ($($expected.Count))" { - $hasparms = $command.Parameters.Values.Name - Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty - } - } + BeforeAll { + $command = Get-Command Get-DbaDatabase + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "Database", + "Confirm", + "WhatIf" + ) + } + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty + } + } } ``` @@ -172,11 +171,22 @@ Describe "Get-DbaDatabase" -Tag "IntegrationTests" { } ``` -## Additional instructions +## Additional Instructions + +### Test Structure +- Parameter validation must be tagged as Unit Test +- No loose code outside of proper test blocks +- Must maintain all instance reference comments (#TestConfig.instance3, etc.) + +### Syntax Requirements +- Use $PSItem instead of $_ +- No trailing spaces +- Use $results.Status.Count for accurate counting + +### Must Not Use +- $MyInvocation.MyCommand.Name for command names +- Old knownParameters validation approach +- Assumed parameter names - match original tests exactly -- DO NOT use `$MyInvocation.MyCommand.Name` to get command names -- DO NOT use the old `knownParameters` validation approach -- DO NOT include loose code outside of proper test blocks -- DO NOT remove comments like "#TestConfig.instance3" or "#$TestConfig.instance2 for appveyor" -- DO NOT use $_ DO use $PSItem instead -- Parameter validation is ALWAYS tagged as a Unit Test \ No newline at end of file +# Important +ALL comments must be preserved exactly as they appear in the original code, including seemingly unrelated or end-of-file comments. Even comments that appear to be development notes or temporary must be kept. This is especially important for comments related to CI/CD systems like AppVeyor. \ No newline at end of file diff --git a/tests/Copy-DbaAgentProxy.Tests.ps1 b/tests/Copy-DbaAgentProxy.Tests.ps1 index 867a6ca36f..28ac1b9bdc 100644 --- a/tests/Copy-DbaAgentProxy.Tests.ps1 +++ b/tests/Copy-DbaAgentProxy.Tests.ps1 @@ -1,19 +1,40 @@ -$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 = 'Source', 'SourceSqlCredential', 'Destination', 'DestinationSqlCredential', 'ProxyAccount', 'ExcludeProxyAccount', 'Force', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + +Describe "Copy-DbaAgentProxy" -Tag "UnitTests" { + Context "Parameter validation" { + BeforeAll { + $command = Get-Command Copy-DbaAgentProxy + $expected = $TestConfig.CommonParameters + $expected += @( + "Source", + "SourceSqlCredential", + "Destination", + "DestinationSqlCredential", + "ProxyAccount", + "ExcludeProxyAccount", + "Force", + "EnableException", + "Confirm", + "WhatIf" + ) + } + + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tag "IntegrationTests" { +Describe "Copy-DbaAgentProxy" -Tag "IntegrationTests" { BeforeAll { $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 $sql = "CREATE CREDENTIAL dbatoolsci_credential WITH IDENTITY = 'sa', SECRET = 'dbatools'" @@ -25,6 +46,7 @@ Describe "$commandname Integration Tests" -Tag "IntegrationTests" { $sql = "CREATE CREDENTIAL dbatoolsci_credential WITH IDENTITY = 'sa', SECRET = 'dbatools'" $server.Query($sql) } + AfterAll { $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 $sql = "EXEC msdb.dbo.sp_delete_proxy @proxy_name = 'dbatoolsci_agentproxy'" @@ -39,17 +61,19 @@ Describe "$commandname Integration Tests" -Tag "IntegrationTests" { $server.Query($sql) } - Context "Copies Agent Proxy" { - $results = Copy-DbaAgentProxy -Source $TestConfig.instance2 -Destination $TestConfig.instance3 -ProxyAccount dbatoolsci_agentproxy + Context "When copying agent proxy between instances" { + BeforeAll { + $results = Copy-DbaAgentProxy -Source $TestConfig.instance2 -Destination $TestConfig.instance3 -ProxyAccount dbatoolsci_agentproxy + } - It "returns one results" { - $results.Count -eq 1 - $results.Status -eq "Successful" + It "Should return one successful result" { + $results.Status.Count | Should -Be 1 + $results.Status | Should -Be "Successful" } - It "return one result that's skipped" { - $results = Get-DbaAgentProxy -SqlInstance $TestConfig.instance3 -Proxy dbatoolsci_agentproxy - $results.Count -eq 1 + It "Should create the proxy on the destination" { + $proxyResults = Get-DbaAgentProxy -SqlInstance $TestConfig.instance3 -Proxy dbatoolsci_agentproxy + $proxyResults.Name | Should -Be "dbatoolsci_agentproxy" } } } diff --git a/tests/Copy-DbaAgentSchedule.Tests.ps1 b/tests/Copy-DbaAgentSchedule.Tests.ps1 index 6d23d68ece..2f0bbaa7d2 100644 --- a/tests/Copy-DbaAgentSchedule.Tests.ps1 +++ b/tests/Copy-DbaAgentSchedule.Tests.ps1 @@ -1,24 +1,47 @@ -$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 = 'Source', 'SourceSqlCredential', 'Destination', 'DestinationSqlCredential', 'Force', 'EnableException', 'Schedule', 'Id', '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 +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + +Describe "Copy-DbaAgentSchedule" -Tag "UnitTests" { + Context "Parameter validation" { + BeforeAll { + $command = Get-Command Copy-DbaAgentSchedule + $expected = $TestConfig.CommonParameters + $expected += @( + "Source", + "SourceSqlCredential", + "Destination", + "DestinationSqlCredential", + "Schedule", + "Id", + "InputObject", + "Force", + "EnableException", + "Confirm", + "WhatIf" + ) + } + + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tag "IntegrationTests" { +Describe "Copy-DbaAgentSchedule" -Tag "IntegrationTests" { BeforeAll { $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 $sql = "EXEC msdb.dbo.sp_add_schedule @schedule_name = N'dbatoolsci_DailySchedule' , @freq_type = 4, @freq_interval = 1, @active_start_time = 010000" $server.Query($sql) } + AfterAll { $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 $sql = "EXEC msdb.dbo.sp_delete_schedule @schedule_name = 'dbatoolsci_DailySchedule'" @@ -27,20 +50,24 @@ Describe "$commandname Integration Tests" -Tag "IntegrationTests" { $server = Connect-DbaInstance -SqlInstance $TestConfig.instance3 $sql = "EXEC msdb.dbo.sp_delete_schedule @schedule_name = 'dbatoolsci_DailySchedule'" $server.Query($sql) - } - Context "Copies Agent Schedule" { - $results = Copy-DbaAgentSchedule -Source $TestConfig.instance2 -Destination $TestConfig.instance3 + Context "When copying agent schedule between instances" { + BeforeAll { + $results = Copy-DbaAgentSchedule -Source $TestConfig.instance2 -Destination $TestConfig.instance3 + } - It "returns one results" { + It "Returns more than one result" { $results.Count | Should -BeGreaterThan 1 - ($results | Where Status -eq "Successful") | Should -Not -Be $null } - It "return one result of Start Time 1:00 AM" { - $results = Get-DbaAgentSchedule -SqlInstance $TestConfig.instance3 -Schedule dbatoolsci_DailySchedule - $results.ActiveStartTimeOfDay -eq '01:00:00' + It "Contains at least one successful copy" { + $results | Where-Object Status -eq "Successful" | Should -Not -BeNullOrEmpty + } + + It "Creates schedule with correct start time" { + $schedule = Get-DbaAgentSchedule -SqlInstance $TestConfig.instance3 -Schedule dbatoolsci_DailySchedule + $schedule.ActiveStartTimeOfDay | Should -Be '01:00:00' } } } diff --git a/tests/Copy-DbaAgentServer.Tests.ps1 b/tests/Copy-DbaAgentServer.Tests.ps1 index b691e7ae93..24814a4ae1 100644 --- a/tests/Copy-DbaAgentServer.Tests.ps1 +++ b/tests/Copy-DbaAgentServer.Tests.ps1 @@ -1,19 +1,36 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'Source', 'SourceSqlCredential', 'Destination', 'DestinationSqlCredential', 'DisableJobsOnDestination', 'DisableJobsOnSource', 'ExcludeServerProperties', 'Force', '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 "Copy-DbaAgentServer" -Tag "UnitTests" { + Context "Parameter validation" { + BeforeAll { + $command = Get-Command Copy-DbaAgentServer + $expected = $TestConfig.CommonParameters + $expected += @( + "Source", + "SourceSqlCredential", + "Destination", + "DestinationSqlCredential", + "DisableJobsOnDestination", + "DisableJobsOnSource", + "ExcludeServerProperties", + "Force", + "EnableException", + "Confirm", + "WhatIf" + ) + } + + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasParams = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasParams | Should -BeNullOrEmpty } } -} -<# - 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/Copy-DbaBackupDevice.Tests.ps1 b/tests/Copy-DbaBackupDevice.Tests.ps1 index 4766c988c3..49287fa22a 100644 --- a/tests/Copy-DbaBackupDevice.Tests.ps1 +++ b/tests/Copy-DbaBackupDevice.Tests.ps1 @@ -1,54 +1,76 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig - -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'Source', 'SourceSqlCredential', 'Destination', 'DestinationSqlCredential', 'BackupDevice', 'Force', '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 "Copy-DbaBackupDevice" -Tag "UnitTests" { + Context "Parameter validation" { + BeforeAll { + $command = Get-Command Copy-DbaBackupDevice + $expected = $TestConfig.CommonParameters + $expected += @( + "Source", + "SourceSqlCredential", + "Destination", + "DestinationSqlCredential", + "BackupDevice", + "Force", + "EnableException", + "Confirm", + "WhatIf" + ) + } + + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } if (-not $env:appveyor) { - Describe "$commandname Integration Tests" -Tags "IntegrationTests" { - Context "Setup" { - BeforeAll { - $devicename = "dbatoolsci-backupdevice" - $backupdir = (Get-DbaDefaultPath -SqlInstance $TestConfig.instance1).Backup - $backupfilename = "$backupdir\$devicename.bak" - $server = Connect-DbaInstance -SqlInstance $TestConfig.instance1 - $server.Query("EXEC master.dbo.sp_addumpdevice @devtype = N'disk', @logicalname = N'$devicename',@physicalname = N'$backupfilename'") - $server.Query("BACKUP DATABASE master TO DISK = '$backupfilename'") - } - AfterAll { - $server.Query("EXEC master.dbo.sp_dropdevice @logicalname = N'$devicename'") - $server1 = Connect-DbaInstance -SqlInstance $TestConfig.instance2 - try { - $server1.Query("EXEC master.dbo.sp_dropdevice @logicalname = N'$devicename'") - } catch { - # don't care - } - Get-ChildItem -Path $backupfilename | Remove-Item + Describe "Copy-DbaBackupDevice" -Tag "IntegrationTests" { + BeforeAll { + $deviceName = "dbatoolsci-backupdevice" + $backupDir = (Get-DbaDefaultPath -SqlInstance $TestConfig.instance1).Backup + $backupFileName = "$backupDir\$deviceName.bak" + $sourceServer = Connect-DbaInstance -SqlInstance $TestConfig.instance1 + $sourceServer.Query("EXEC master.dbo.sp_addumpdevice @devtype = N'disk', @logicalname = N'$deviceName',@physicalname = N'$backupFileName'") + $sourceServer.Query("BACKUP DATABASE master TO DISK = '$backupFileName'") + } + + AfterAll { + $sourceServer.Query("EXEC master.dbo.sp_dropdevice @logicalname = N'$deviceName'") + $destServer = Connect-DbaInstance -SqlInstance $TestConfig.instance2 + try { + $destServer.Query("EXEC master.dbo.sp_dropdevice @logicalname = N'$deviceName'") + } catch { + # Device may not exist, ignore error } + Get-ChildItem -Path $backupFileName | Remove-Item + } - $results = Copy-DbaBackupDevice -Source $TestConfig.instance1 -Destination $TestConfig.instance2 -WarningVariable warn -WarningAction SilentlyContinue 3> $null - if ($warn) { - It "warns if it has a problem moving (issue for local to local)" { - $warn | Should -Match "backup device to destination" - } - } else { - It "should report success" { - $results.Status | Should Be "Successful" + Context "When copying backup device between instances" { + It "Should copy the backup device successfully or warn about local copy" { + $results = Copy-DbaBackupDevice -Source $TestConfig.instance1 -Destination $TestConfig.instance2 -WarningVariable warning -WarningAction SilentlyContinue 3> $null + + if ($warning) { + $warning | Should -Match "backup device to destination" + } else { + $results.Status | Should -Be "Successful" } } - $results = Copy-DbaBackupDevice -Source $TestConfig.instance1 -Destination $TestConfig.instance2 - It "Should say skipped" { - $results.Status -ne "Successful" | Should be $true + It "Should skip copying when device already exists" { + $results = Copy-DbaBackupDevice -Source $TestConfig.instance1 -Destination $TestConfig.instance2 + $results.Status | Should -Not -Be "Successful" } } } diff --git a/tests/Copy-DbaCustomError.Tests.ps1 b/tests/Copy-DbaCustomError.Tests.ps1 index c87d1a9f42..e97e6394be 100644 --- a/tests/Copy-DbaCustomError.Tests.ps1 +++ b/tests/Copy-DbaCustomError.Tests.ps1 @@ -1,45 +1,80 @@ -$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 = 'Source', 'SourceSqlCredential', 'Destination', 'DestinationSqlCredential', 'CustomError', 'ExcludeCustomError', 'Force', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + +Describe "Copy-DbaCustomError" -Tag "UnitTests" { + Context "Parameter validation" { + BeforeAll { + $command = Get-Command Copy-DbaCustomError + $expected = $TestConfig.CommonParameters + $expected += @( + "Source", + "SourceSqlCredential", + "Destination", + "DestinationSqlCredential", + "CustomError", + "ExcludeCustomError", + "Force", + "EnableException", + "Confirm", + "WhatIf" + ) + } + + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tag "IntegrationTests" { +Describe "Copy-DbaCustomError" -Tag "IntegrationTests" { BeforeAll { $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 -Database master - $server.Query("EXEC sp_addmessage @msgnum = 60000, @severity = 16,@msgtext = N'The item named %s already exists in %s.',@lang = 'us_english';") - $server.Query("EXEC sp_addmessage @msgnum = 60000, @severity = 16, @msgtext = N'L''élément nommé %1! existe déjà dans %2!',@lang = 'French';") + $server.Query("IF EXISTS (SELECT 1 FROM sys.messages WHERE message_id = 60000) EXEC sp_dropmessage @msgnum = 60000, @lang = 'all'") + $server.Query("EXEC sp_addmessage @msgnum = 60000, @severity = 16, @msgtext = N'The item named %s already exists in %s.', @lang = 'us_english'") + $server.Query("EXEC sp_addmessage @msgnum = 60000, @severity = 16, @msgtext = N'L''élément nommé %1! existe déjà dans %2!', @lang = 'French'") } + AfterAll { - $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 -Database master - $server.Query("EXEC sp_dropmessage @msgnum = 60000, @lang = 'all';") - $server = Connect-DbaInstance -SqlInstance $TestConfig.instance3 -Database master - $server.Query("EXEC sp_dropmessage @msgnum = 60000, @lang = 'all';") + $serversToClean = @($TestConfig.instance2, $TestConfig.instance3) + foreach ($serverInstance in $serversToClean) { + $cleanupServer = Connect-DbaInstance -SqlInstance $serverInstance -Database master + $cleanupServer.Query("IF EXISTS (SELECT 1 FROM sys.messages WHERE message_id = 60000) EXEC sp_dropmessage @msgnum = 60000, @lang = 'all'") + } } - It "copies the sample custom errror" { - $results = Copy-DbaCustomError -Source $TestConfig.instance2 -Destination $TestConfig.instance3 -CustomError 60000 - $results.Name -eq "60000:'us_english'", "60000:'Français'" - $results.Status -eq 'Successful', 'Successful' - } + Context "When copying custom errors" { + BeforeEach { + # Clean destination before each test + $destServer = Connect-DbaInstance -SqlInstance $TestConfig.instance3 -Database master + $destServer.Query("IF EXISTS (SELECT 1 FROM sys.messages WHERE message_id = 60000) EXEC sp_dropmessage @msgnum = 60000, @lang = 'all'") + } - It "doesn't overwrite existing custom errors" { - $results = Copy-DbaCustomError -Source $TestConfig.instance2 -Destination $TestConfig.instance3 -CustomError 60000 - $results.Name -eq "60000:'us_english'", "60000:'Français'" - $results.Status -eq 'Skipped', 'Skipped' - } + It "Should successfully copy custom error messages" { + $results = Copy-DbaCustomError -Source $TestConfig.instance2 -Destination $TestConfig.instance3 -CustomError 60000 + $results.Name[0] | Should -Be "60000:'us_english'" + $results.Name[1] | Should -Match "60000\:'Fran" + $results.Status | Should -Be @("Successful", "Successful") + } - It "the newly copied custom error exists" { - $results = Get-DbaCustomError -SqlInstance $TestConfig.instance2 - $results.ID -contains 60000 + It "Should skip existing custom errors" { + Copy-DbaCustomError -Source $TestConfig.instance2 -Destination $TestConfig.instance3 -CustomError 60000 + $results = Copy-DbaCustomError -Source $TestConfig.instance2 -Destination $TestConfig.instance3 -CustomError 60000 + $results.Name[0] | Should -Be "60000:'us_english'" + $results.Name[1] | Should -Match "60000\:'Fran" + $results.Status | Should -Be @("Skipped", "Skipped") + } + + It "Should verify custom error exists" { + $results = Get-DbaCustomError -SqlInstance $TestConfig.instance2 + $results.ID | Should -Contain 60000 + } } } diff --git a/tests/Copy-DbaDataCollector.Tests.ps1 b/tests/Copy-DbaDataCollector.Tests.ps1 index 62af2cfc21..fbac8bf06e 100644 --- a/tests/Copy-DbaDataCollector.Tests.ps1 +++ b/tests/Copy-DbaDataCollector.Tests.ps1 @@ -1,19 +1,38 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'Source', 'SourceSqlCredential', 'Destination', 'DestinationSqlCredential', 'CollectionSet', 'ExcludeCollectionSet', 'NoServerReconfig', 'Force', '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 "Copy-DbaDataCollector" -Tag "UnitTests" { + Context "Parameter validation" { + BeforeAll { + $command = Get-Command Copy-DbaDataCollector + $expected = $TestConfig.CommonParameters + $expected += @( + 'Source', + 'SourceSqlCredential', + 'Destination', + 'DestinationSqlCredential', + 'CollectionSet', + 'ExcludeCollectionSet', + 'NoServerReconfig', + 'Force', + 'EnableException', + 'Confirm', + 'WhatIf' + ) + } + + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } -} -<# - Integration test should appear below and are custom to the command you are writing. - Read https://github.com/dataplat/dbatools/blob/development/contributing.md#tests - for more guidence. -#> \ No newline at end of file +} \ No newline at end of file diff --git a/tests/Copy-DbaDbCertificate.Tests.ps1 b/tests/Copy-DbaDbCertificate.Tests.ps1 index 7fd3634d71..c833edd252 100644 --- a/tests/Copy-DbaDbCertificate.Tests.ps1 +++ b/tests/Copy-DbaDbCertificate.Tests.ps1 @@ -1,53 +1,90 @@ -$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 = 'Source', 'SourceSqlCredential', 'Destination', 'DestinationSqlCredential', 'Database', 'ExcludeDatabase', 'Certificate', 'ExcludeCertificate', 'SharedPath', 'MasterKeyPassword', 'EncryptionPassword', 'DecryptionPassword', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + +Describe "Copy-DbaDbCertificate" -Tag "UnitTests" { + Context "Parameter validation" { + BeforeAll { + $command = Get-Command Copy-DbaDbCertificate + $expected = $TestConfig.CommonParameters + $expected += @( + 'Source', + 'SourceSqlCredential', + 'Destination', + 'DestinationSqlCredential', + 'Database', + 'ExcludeDatabase', + 'Certificate', + 'ExcludeCertificate', + 'SharedPath', + 'MasterKeyPassword', + 'EncryptionPassword', + 'DecryptionPassword', + 'EnableException' + ) + } + + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasParams = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasParams | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { +Describe "Copy-DbaDbCertificate" -Tag "IntegrationTests" { Context "Can create a database certificate" { BeforeAll { - $passwd = $(ConvertTo-SecureString -String "GoodPass1234!" -AsPlainText -Force) - $masterkey = New-DbaDbMasterKey -SqlInstance $TestConfig.instance2 -Database master -SecurePassword $passwd -Confirm:$false -ErrorAction SilentlyContinue + $securePassword = ConvertTo-SecureString -String "GoodPass1234!" -AsPlainText -Force + + # Create master key on instance2 + $masterKey = New-DbaDbMasterKey -SqlInstance $TestConfig.instance2 -Database master -SecurePassword $securePassword -Confirm:$false -ErrorAction SilentlyContinue + + # Create test databases + $testDatabases = New-DbaDatabase -SqlInstance $TestConfig.instance2, $TestConfig.instance3 -Name dbatoolscopycred + + # Create master key and certificate on source + $null = New-DbaDbMasterKey -SqlInstance $TestConfig.instance2 -Database dbatoolscopycred -SecurePassword $securePassword -Confirm:$false + $certificateName = "Cert_$(Get-Random)" + $null = New-DbaDbCertificate -SqlInstance $TestConfig.instance2 -Name $certificateName -Database dbatoolscopycred -Confirm:$false - $newdbs = New-DbaDatabase -SqlInstance $TestConfig.instance2, $TestConfig.instance3 -Name dbatoolscopycred - $null = New-DbaDbMasterKey -SqlInstance $TestConfig.instance2 -Database dbatoolscopycred -SecurePassword $passwd -Confirm:$false - $certificateName2 = "Cert_$(Get-Random)" - $null = New-DbaDbCertificate -SqlInstance $TestConfig.instance2 -Name $certificateName2 -Database dbatoolscopycred -Confirm:$false + # Setup copy parameters + $splatCopyCert = @{ + Source = $TestConfig.instance2 + Destination = $TestConfig.instance3 + EncryptionPassword = $securePassword + MasterKeyPassword = $securePassword + Database = "dbatoolscopycred" + SharedPath = $TestConfig.appveyorlabrepo + Confirm = $false + } } + AfterAll { - $null = $newdbs | Remove-DbaDatabase -Confirm:$false -ErrorAction SilentlyContinue + $null = $testDatabases | Remove-DbaDatabase -Confirm:$false -ErrorAction SilentlyContinue if ($masterKey) { - $masterkey | Remove-DbaDbMasterKey -Confirm:$false -ErrorAction SilentlyContinue + $masterKey | Remove-DbaDbMasterKey -Confirm:$false -ErrorAction SilentlyContinue } } - # doing it on docker instead. this works on linux and on a windows homelab so i dont know + It -Skip "Successfully copies a certificate" { - $passwd = $(ConvertTo-SecureString -String "GoodPass1234!" -AsPlainText -Force) - $paramscopydb = @{ - Source = $TestConfig.instance2 - Destination = $TestConfig.instance3 - EncryptionPassword = $passwd - MasterKeyPassword = $passwd - Database = "dbatoolscopycred" - SharedPath = $($TestConfig.appveyorlabrepo) - } - $results = Copy-DbaDbCertificate @paramscopydb -Confirm:$false | Where-Object SourceDatabase -eq dbatoolscopycred | Select-Object -First 1 - $results.Notes | Should -Be $null + $results = Copy-DbaDbCertificate @splatCopyCert | Where-Object SourceDatabase -eq dbatoolscopycred | Select-Object -First 1 + + $results.Notes | Should -BeNullOrEmpty $results.Status | Should -Be "Successful" - $results.SourceDatabaseID | Should -Be (Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database dbatoolscopycred).ID - $results.DestinationDatabaseID | Should -Be (Get-DbaDatabase -SqlInstance $TestConfig.instance3 -Database dbatoolscopycred).ID + + $sourceDb = Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database dbatoolscopycred + $destDb = Get-DbaDatabase -SqlInstance $TestConfig.instance3 -Database dbatoolscopycred + + $results.SourceDatabaseID | Should -Be $sourceDb.ID + $results.DestinationDatabaseID | Should -Be $destDb.ID - Get-DbaDbCertificate -SqlInstance $TestConfig.instance3 -Database dbatoolscopycred -Certificate $certificateName2 | Should -Not -BeNullOrEmpty + Get-DbaDbCertificate -SqlInstance $TestConfig.instance3 -Database dbatoolscopycred -Certificate $certificateName | Should -Not -BeNullOrEmpty } } } diff --git a/tests/Copy-DbaDbMail.Tests.ps1 b/tests/Copy-DbaDbMail.Tests.ps1 index 494007e91e..768cbdd878 100644 --- a/tests/Copy-DbaDbMail.Tests.ps1 +++ b/tests/Copy-DbaDbMail.Tests.ps1 @@ -1,19 +1,37 @@ -$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 = 'Source', 'Destination', 'Type', 'SourceSqlCredential', 'DestinationSqlCredential', 'Force', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + +Describe "Copy-DbaDbMail" -Tag "UnitTests" { + Context "Parameter validation" { + BeforeAll { + $command = Get-Command Copy-DbaDbMail + $expected = $TestConfig.CommonParameters + $expected += @( + "Source", + "Destination", + "Type", + "SourceSqlCredential", + "DestinationSqlCredential", + "Force", + "EnableException" + ) + } + + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name | Where-Object { $_ -notin ('whatif', 'confirm') } + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { +Describe "Copy-DbaDbMail" -Tags "IntegrationTests" { BeforeAll { $servers = Connect-DbaInstance -SqlInstance $TestConfig.instance2, $TestConfig.instance3 foreach ($s in $servers) { @@ -33,7 +51,6 @@ Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { $replyto_address = 'no-reply@dbatools.io' $mailaccountpriority = 1 - $splat1 = @{ SqlInstance = $TestConfig.instance2 Name = $accountName @@ -53,8 +70,8 @@ Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { MailAccountPriority = $mailaccountpriority } $null = New-DbaDbMailProfile @splat2 - } + AfterAll { $servers = Connect-DbaInstance -SqlInstance $TestConfig.instance2, $TestConfig.instance3 @@ -63,44 +80,37 @@ Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { Invoke-DbaQuery -SqlInstance $s -Query $mailAccountSettings -Database msdb $mailProfileSettings = "EXEC msdb.dbo.sysmail_delete_profile_sp @profile_name = '$profilename';" Invoke-DbaQuery -SqlInstance $s -Query $mailProfileSettings -Database msdb - } } - Context "Copy DbMail to $($TestConfig.instance3)" { - $results = Copy-DbaDbMail -Source $TestConfig.instance2 -Destination $TestConfig.instance3 + Context "When copying DbMail to $($TestConfig.instance3)" { + BeforeAll { + $results = Copy-DbaDbMail -Source $TestConfig.instance2 -Destination $TestConfig.instance3 + } - It "Should have copied database mailitems" { - $results | Should Not Be $null + It "Should have copied database mail items" { + $results | Should -Not -BeNullOrEmpty } - foreach ($r in $results) { - if ($r.type -in @('Mail Configuration', 'Mail Account', 'Mail Profile')) { - It "Should have copied $($r.type) from $($TestConfig.instance2)" { - $r.SourceServer | Should Be $TestConfig.instance2 - } - It "Should have copied $($r.type) to $($TestConfig.instance3)" { - $r.DestinationServer | Should Be $TestConfig.instance3 - } - } + + It "Should have copied <_.type> from source to destination" -ForEach ($results | Where-Object type -in @('Mail Configuration', 'Mail Account', 'Mail Profile')) { + $PSItem.SourceServer | Should -Be $TestConfig.instance2 + $PSItem.DestinationServer | Should -Be $TestConfig.instance3 } } - Context "Copy MailServers specifically" { - $results = Copy-DbaDbMail -Source $TestConfig.instance2 -Destination $TestConfig.instance3 -Type MailServers + Context "When copying MailServers specifically" { + BeforeAll { + $results = Copy-DbaDbMail -Source $TestConfig.instance2 -Destination $TestConfig.instance3 -Type MailServers + } - It "Should have copied database mailitems" { - $results | Should Not Be $null + It "Should have returned results" { + $results | Should -Not -BeNullOrEmpty } - foreach ($r in $results) { - It "Should have $($r.status) $($r.type) from $($TestConfig.instance2)" { - $r.SourceServer | Should Be $TestConfig.instance2 - $r.status | Should Be 'Skipped' - } - It "Should have $($r.status) $($r.type) to $($TestConfig.instance3)" { - $r.DestinationServer | Should Be $TestConfig.instance3 - $r.status | Should Be 'Skipped' - } + It "Should have skipped <_.type> copy operations" -ForEach $results { + $PSItem.SourceServer | Should -Be $TestConfig.instance2 + $PSItem.DestinationServer | Should -Be $TestConfig.instance3 + $PSItem.Status | Should -Be 'Skipped' } } } diff --git a/tests/Copy-DbaDbQueryStoreOption.Tests.ps1 b/tests/Copy-DbaDbQueryStoreOption.Tests.ps1 index a75b2782cf..8ff4f014d7 100644 --- a/tests/Copy-DbaDbQueryStoreOption.Tests.ps1 +++ b/tests/Copy-DbaDbQueryStoreOption.Tests.ps1 @@ -1,23 +1,48 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig - -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'Source', 'SourceSqlCredential', 'SourceDatabase', 'Destination', 'DestinationSqlCredential', 'DestinationDatabase', 'Exclude', 'AllDatabases', '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 "Copy-DbaDbQueryStoreOption" -Tag "UnitTests" { + Context "Parameter validation" { + BeforeAll { + $command = Get-Command Copy-DbaDbQueryStoreOption + $expected = $TestConfig.CommonParameters + $expected += @( + "Source", + "SourceSqlCredential", + "SourceDatabase", + "Destination", + "DestinationSqlCredential", + "DestinationDatabase", + "Exclude", + "AllDatabases", + "EnableException", + "Confirm", + "WhatIf" + ) + } + + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasParams = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasParams | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { +Describe "Copy-DbaDbQueryStoreOption" -Tag "IntegrationTests" { Context "Verifying query store options are copied" { BeforeAll { $server2 = Connect-DbaInstance -SqlInstance $TestConfig.instance2 } + BeforeEach { $db1Name = "dbatoolsci_querystoretest1" $db1 = New-DbaDatabase -SqlInstance $server2 -Name $db1Name @@ -36,6 +61,7 @@ Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { $db4Name = "dbatoolsci_querystoretest4" $db4 = New-DbaDatabase -SqlInstance $server2 -Name $db4Name } + AfterEach { $db1, $db2, $db3, $db4 | Remove-DbaDatabase -Confirm:$false } @@ -46,7 +72,7 @@ Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { $result = Copy-DbaDbQueryStoreOption -Source $server2 -SourceDatabase $db1Name -Destination $server2 -DestinationDatabase $db2Name - $result.Status | Should -Be Successful + $result.Status | Should -Be "Successful" $result.SourceDatabase | Should -Be $db1Name $result.SourceDatabaseID | Should -Be $db1.ID $result.Name | Should -Be $db2Name @@ -62,8 +88,8 @@ Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { $result = Copy-DbaDbQueryStoreOption -Source $server2 -SourceDatabase $db1Name -Destination $server2 -Exclude $db4Name - $result.Status | Should -Not -Contain 'Failed' - $result.Status | Should -Not -Contain 'Skipped' + $result.Status | Should -Not -Contain "Failed" + $result.Status | Should -Not -Contain "Skipped" $result.Name | Should -Contain $db1Name $result.Name | Should -Contain $db2Name @@ -77,7 +103,7 @@ Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { $result.DestinationDatabaseID | Should -Contain $db3.ID $dbQSOptions = Get-DbaDbQueryStoreOption -SqlInstance $server2 -Database $db1Name, $db2Name, $db3Name - ($dbQSOptions | Where-Object { $_.DataFlushIntervalInSeconds -eq ($originalQSOptionValue + 1) }).Count | Should -Be 3 + ($dbQSOptions | Where-Object { $PSItem.DataFlushIntervalInSeconds -eq ($originalQSOptionValue + 1) }).Count | Should -Be 3 $db4QSOptions = Get-DbaDbQueryStoreOption -SqlInstance $server2 -Database $db4Name $db4QSOptions.DataFlushIntervalInSeconds | Should -Be $originalQSOptionValue diff --git a/tests/Copy-DbaDbTableData.Tests.ps1 b/tests/Copy-DbaDbTableData.Tests.ps1 index 4f4b0aedee..b57f1f0547 100644 --- a/tests/Copy-DbaDbTableData.Tests.ps1 +++ b/tests/Copy-DbaDbTableData.Tests.ps1 @@ -1,19 +1,56 @@ -$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" { - It "Should only contain our specific parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'AutoCreateTable', 'BatchSize', 'BulkCopyTimeout', 'CheckConstraints', 'CommandTimeout', 'Database', 'Destination', 'DestinationDatabase', 'DestinationSqlCredential', 'DestinationTable', 'EnableException', 'FireTriggers', 'InputObject', 'KeepIdentity', 'KeepNulls', 'NoTableLock', 'NotifyAfter', 'Query', 'SqlCredential', 'SqlInstance', 'Table', 'Truncate', 'View', 'UseDefaultFileGroup' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should -Be 0 +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + +Describe "Copy-DbaDbTableData" -Tag "UnitTests" { + Context "Parameter validation" { + BeforeAll { + $command = Get-Command Copy-DbaDbTableData + $expected = $TestConfig.CommonParameters + $expected += @( + 'SqlInstance', + 'SqlCredential', + 'Destination', + 'DestinationSqlCredential', + 'Database', + 'DestinationDatabase', + 'Table', + 'View', + 'Query', + 'AutoCreateTable', + 'BatchSize', + 'NotifyAfter', + 'DestinationTable', + 'NoTableLock', + 'CheckConstraints', + 'FireTriggers', + 'KeepIdentity', + 'KeepNulls', + 'Truncate', + 'BulkCopyTimeout', + 'CommandTimeout', + 'UseDefaultFileGroup', + 'InputObject', + 'EnableException', + 'Confirm', + 'WhatIf' + ) + } + + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { + +Describe "Copy-DbaDbTableData" -Tag "IntegrationTests" { BeforeAll { $db = Get-DbaDatabase -SqlInstance $TestConfig.instance1 -Database tempdb $db2 = Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database tempdb @@ -49,7 +86,8 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { $null = 1 } } - Context "Data movement" { + + Context "When copying table data within same instance" { It "copies the table data" { $results = Copy-DbaDbTableData -SqlInstance $TestConfig.instance1 -Database tempdb -Table dbatoolsci_example -DestinationTable dbatoolsci_example2 $table1count = $db.Query("select id from dbo.dbatoolsci_example") @@ -58,7 +96,9 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { $results.SourceDatabaseID | Should -Be $db.ID $results.DestinationDatabaseID | Should -Be $db.ID } + } + Context "When copying table data between instances" { It "copies the table data to another instance" { $null = Copy-DbaDbTableData -SqlInstance $TestConfig.instance1 -Destination $TestConfig.instance2 -Database tempdb -Table tempdb.dbo.dbatoolsci_example -DestinationTable dbatoolsci_example3 $table1count = $db.Query("select id from dbo.dbatoolsci_example") @@ -76,7 +116,8 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { $result.RowsCopied | Should -Be 1 } } - Context "Functionality checks" { + + Context "When testing pipeline functionality" { It "supports piping" { $null = Get-DbaDbTable -SqlInstance $TestConfig.instance1 -Database tempdb -Table dbatoolsci_example | Copy-DbaDbTableData -DestinationTable dbatoolsci_example2 -Truncate $table1count = $db.Query("select id from dbo.dbatoolsci_example") @@ -91,7 +132,6 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { } It "opens and closes connections properly" { - #regression test, see #3468 $results = Get-DbaDbTable -SqlInstance $TestConfig.instance1 -Database tempdb -Table 'dbo.dbatoolsci_example', 'dbo.dbatoolsci_example4' | Copy-DbaDbTableData -Destination $TestConfig.instance2 -DestinationDatabase tempdb -KeepIdentity -KeepNulls -BatchSize 5000 -Truncate $results.Count | Should -Be 2 $table1DbCount = $db.Query("select id from dbo.dbatoolsci_example") @@ -105,7 +145,9 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { $table4Db2Check = $db2.Query("select id from dbo.dbatoolsci_example4 where id = 1") $table4Db2Check.Count | Should -Be 13 } + } + Context "When handling edge cases" { It "Should return nothing if Source and Destination are same" { $result = Copy-DbaDbTableData -SqlInstance $TestConfig.instance1 -Database tempdb -Table dbatoolsci_example -Truncate $result | Should -Be $null diff --git a/tests/Copy-DbaEndpoint.Tests.ps1 b/tests/Copy-DbaEndpoint.Tests.ps1 index 66e582f39f..37444bf61f 100644 --- a/tests/Copy-DbaEndpoint.Tests.ps1 +++ b/tests/Copy-DbaEndpoint.Tests.ps1 @@ -1,29 +1,46 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'Source', 'SourceSqlCredential', 'Destination', 'DestinationSqlCredential', 'Endpoint', 'ExcludeEndpoint', 'Force', '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 "Copy-DbaEndpoint" -Tag "UnitTests" { + Context "Parameter validation" { + BeforeAll { + $command = Get-Command Copy-DbaEndpoint + $expected = $TestConfig.CommonParameters + $expected += @( + "Source", + "SourceSqlCredential", + "Destination", + "DestinationSqlCredential", + "Endpoint", + "ExcludeEndpoint", + "Force", + "EnableException", + "Confirm", + "WhatIf" + ) + } + + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -<# - Integration test should appear below and are custom to the command you are writing. - Read https://github.com/dataplat/dbatools/blob/development/contributing.md#tests - for more guidence. -#> -Describe "$commandname Integration Tests" -Tag "IntegrationTests" { +Describe "Copy-DbaEndpoint" -Tag "IntegrationTests" { BeforeAll { Get-DbaEndpoint -SqlInstance $TestConfig.instance2 -Type DatabaseMirroring | Remove-DbaEndpoint -Confirm:$false New-DbaEndpoint -SqlInstance $TestConfig.instance2 -Name dbatoolsci_MirroringEndpoint -Type DatabaseMirroring -Port 5022 -Owner sa Get-DbaEndpoint -SqlInstance $TestConfig.instance3 -Type DatabaseMirroring | Remove-DbaEndpoint -Confirm:$false } + AfterAll { Get-DbaEndpoint -SqlInstance $TestConfig.instance2 -Type DatabaseMirroring | Remove-DbaEndpoint -Confirm:$false New-DbaEndpoint -SqlInstance $TestConfig.instance2 -Name dbatoolsci_MirroringEndpoint -Type DatabaseMirroring -Port 5022 -Owner sa @@ -31,10 +48,12 @@ Describe "$commandname Integration Tests" -Tag "IntegrationTests" { New-DbaEndpoint -SqlInstance $TestConfig.instance3 -Name dbatoolsci_MirroringEndpoint -Type DatabaseMirroring -Port 5023 -Owner sa } - It "copies an endpoint" { - $results = Copy-DbaEndpoint -Source $TestConfig.instance2 -Destination $TestConfig.instance3 -Endpoint dbatoolsci_MirroringEndpoint - $results.DestinationServer | Should -Be $TestConfig.instance3 - $results.Status | Should -Be 'Successful' - $results.Name | Should -Be 'dbatoolsci_MirroringEndpoint' + Context "When copying endpoints between instances" { + It "Successfully copies a mirroring endpoint" { + $results = Copy-DbaEndpoint -Source $TestConfig.instance2 -Destination $TestConfig.instance3 -Endpoint dbatoolsci_MirroringEndpoint + $results.DestinationServer | Should -Be $TestConfig.instance3 + $results.Status | Should -Be "Successful" + $results.Name | Should -Be "dbatoolsci_MirroringEndpoint" + } } } diff --git a/tests/Copy-DbaInstanceAudit.Tests.ps1 b/tests/Copy-DbaInstanceAudit.Tests.ps1 index 6b735c4db7..4b4c18d57b 100644 --- a/tests/Copy-DbaInstanceAudit.Tests.ps1 +++ b/tests/Copy-DbaInstanceAudit.Tests.ps1 @@ -1,19 +1,36 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'Source', 'SourceSqlCredential', 'Destination', 'DestinationSqlCredential', 'Audit', 'ExcludeAudit', 'Path', 'Force', '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 "Copy-DbaInstanceAudit" -Tag "UnitTests" { + Context "Parameter validation" { + BeforeAll { + $command = Get-Command Copy-DbaInstanceAudit + $expected = $TestConfig.CommonParameters + $expected += @( + "Source", + "SourceSqlCredential", + "Destination", + "DestinationSqlCredential", + "Audit", + "ExcludeAudit", + "Path", + "Force", + "EnableException", + "Confirm", + "WhatIf" + ) + } + + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } -} -<# - Integration test should appear below and are custom to the command you are writing. - Read https://github.com/dataplat/dbatools/blob/development/contributing.md#tests - for more guidence. -#> \ No newline at end of file +} \ No newline at end of file diff --git a/tests/Copy-DbaInstanceAuditSpecification.Tests.ps1 b/tests/Copy-DbaInstanceAuditSpecification.Tests.ps1 index 6c2b2b7986..60c0fe818a 100644 --- a/tests/Copy-DbaInstanceAuditSpecification.Tests.ps1 +++ b/tests/Copy-DbaInstanceAuditSpecification.Tests.ps1 @@ -1,19 +1,35 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'Source', 'SourceSqlCredential', 'Destination', 'DestinationSqlCredential', 'AuditSpecification', 'ExcludeAuditSpecification', 'Force', '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 "Copy-DbaInstanceAuditSpecification" -Tag "UnitTests" { + Context "Parameter validation" { + BeforeAll { + $command = Get-Command Copy-DbaInstanceAuditSpecification + $expected = $TestConfig.CommonParameters + $expected += @( + "Source", + "SourceSqlCredential", + "Destination", + "DestinationSqlCredential", + "AuditSpecification", + "ExcludeAuditSpecification", + "Force", + "EnableException", + "Confirm", + "WhatIf" + ) + } + + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } -} -<# - Integration test should appear below and are custom to the command you are writing. - Read https://github.com/dataplat/dbatools/blob/development/contributing.md#tests - for more guidence. -#> \ No newline at end of file +} \ No newline at end of file diff --git a/tests/Copy-DbaInstanceTrigger.Tests.ps1 b/tests/Copy-DbaInstanceTrigger.Tests.ps1 index 59afe9b311..df3f93678b 100644 --- a/tests/Copy-DbaInstanceTrigger.Tests.ps1 +++ b/tests/Copy-DbaInstanceTrigger.Tests.ps1 @@ -1,45 +1,69 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig - -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'Source', 'SourceSqlCredential', 'Destination', 'DestinationSqlCredential', 'ServerTrigger', 'ExcludeServerTrigger', 'Force', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + +Describe "Copy-DbaInstanceTrigger" -Tag "UnitTests" { + Context "Parameter validation" { + BeforeAll { + $command = Get-Command Copy-DbaInstanceTrigger + $expected = $TestConfig.CommonParameters + $expected += @( + 'Source', + 'SourceSqlCredential', + 'Destination', + 'DestinationSqlCredential', + 'ServerTrigger', + 'ExcludeServerTrigger', + 'Force', + 'EnableException', + 'Confirm', + 'WhatIf' + ) + } + + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasParams = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasParams | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { - Context "Setup" { - BeforeAll { - $triggername = "dbatoolsci-trigger" - $sql = "CREATE TRIGGER [$triggername] -- Trigger name - ON ALL SERVER FOR LOGON -- Tells you it's a logon trigger - AS - PRINT 'hello'" - $server = Connect-DbaInstance -SqlInstance $TestConfig.instance1 - $server.Query($sql) - } - AfterAll { - $server.Query("DROP TRIGGER [$triggername] ON ALL SERVER") - - try { - $server1 = Connect-DbaInstance -SqlInstance $TestConfig.instance2 - $server1.Query("DROP TRIGGER [$triggername] ON ALL SERVER") - } catch { - # don't care - } +Describe "Copy-DbaInstanceTrigger" -Tag "IntegrationTests" { + BeforeAll { + $triggerName = "dbatoolsci-trigger" + $sql = "CREATE TRIGGER [$triggerName] -- Trigger name + ON ALL SERVER FOR LOGON -- Tells you it's a logon trigger + AS + PRINT 'hello'" + + $sourceServer = Connect-DbaInstance -SqlInstance $TestConfig.instance1 + $sourceServer.Query($sql) + } + + AfterAll { + $sourceServer.Query("DROP TRIGGER [$triggerName] ON ALL SERVER") + + try { + $destServer = Connect-DbaInstance -SqlInstance $TestConfig.instance2 + $destServer.Query("DROP TRIGGER [$triggerName] ON ALL SERVER") + } catch { + # Ignore cleanup errors } + } - $results = Copy-DbaInstanceTrigger -Source $TestConfig.instance1 -Destination $TestConfig.instance2 -WarningAction SilentlyContinue + Context "When copying server triggers between instances" { + BeforeAll { + $results = Copy-DbaInstanceTrigger -Source $TestConfig.instance1 -Destination $TestConfig.instance2 -WarningAction SilentlyContinue + } - It "should report success" { - $results.Status | Should Be "Successful" + It "Should report successful copy operation" { + $results.Status | Should -BeExactly "Successful" } - # same properties need to be added } } diff --git a/tests/Copy-DbaLinkedServer.Tests.ps1 b/tests/Copy-DbaLinkedServer.Tests.ps1 index 3bc272778b..a0cc40e262 100644 --- a/tests/Copy-DbaLinkedServer.Tests.ps1 +++ b/tests/Copy-DbaLinkedServer.Tests.ps1 @@ -1,67 +1,115 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'Source', 'SourceSqlCredential', 'Destination', 'DestinationSqlCredential', 'LinkedServer', 'ExcludeLinkedServer', 'UpgradeSqlClient', 'ExcludePassword', 'Force', '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 "Copy-DbaLinkedServer" -Tag "UnitTests" { + Context "Parameter validation" { + BeforeAll { + $command = Get-Command Copy-DbaLinkedServer + $expected = $TestConfig.CommonParameters + $expected += @( + "Source", + "SourceSqlCredential", + "Destination", + "DestinationSqlCredential", + "LinkedServer", + "ExcludeLinkedServer", + "UpgradeSqlClient", + "ExcludePassword", + "Force", + "EnableException", + "Confirm", + "WhatIf" + ) + } + + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { - BeforeAll { - $createsql = "EXEC master.dbo.sp_addlinkedserver @server = N'dbatoolsci_localhost', @srvproduct=N'SQL Server'; - EXEC master.dbo.sp_addlinkedsrvlogin @rmtsrvname=N'dbatoolsci_localhost',@useself=N'False',@locallogin=NULL,@rmtuser=N'testuser1',@rmtpassword='supfool'; - EXEC master.dbo.sp_addlinkedserver @server = N'dbatoolsci_localhost2', @srvproduct=N'', @provider=N'SQLNCLI10'; - EXEC master.dbo.sp_addlinkedsrvlogin @rmtsrvname=N'dbatoolsci_localhost2',@useself=N'False',@locallogin=NULL,@rmtuser=N'testuser1',@rmtpassword='supfool';" +Describe "Copy-DbaLinkedServer" -Tag "IntegrationTests" { + BeforeAll { + $server1 = Connect-DbaInstance -SqlInstance $TestConfig.instance2 + $server2 = Connect-DbaInstance -SqlInstance $TestConfig.instance3 - $server1 = Connect-DbaInstance -SqlInstance $TestConfig.instance2 - $server2 = Connect-DbaInstance -SqlInstance $TestConfig.instance3 - $server1.Query($createsql) - } - AfterAll { - $dropsql = "EXEC master.dbo.sp_dropserver @server=N'dbatoolsci_localhost', @droplogins='droplogins'; - EXEC master.dbo.sp_dropserver @server=N'dbatoolsci_localhost2', @droplogins='droplogins'" + $createSql = "EXEC master.dbo.sp_addlinkedserver @server = N'dbatoolsci_localhost', @srvproduct=N'SQL Server'; + EXEC master.dbo.sp_addlinkedsrvlogin @rmtsrvname=N'dbatoolsci_localhost',@useself=N'False',@locallogin=NULL,@rmtuser=N'testuser1',@rmtpassword='supfool'; + EXEC master.dbo.sp_addlinkedserver @server = N'dbatoolsci_localhost2', @srvproduct=N'', @provider=N'SQLNCLI10'; + EXEC master.dbo.sp_addlinkedsrvlogin @rmtsrvname=N'dbatoolsci_localhost2',@useself=N'False',@locallogin=NULL,@rmtuser=N'testuser1',@rmtpassword='supfool';" - try { - $server1.Query($dropsql) - $server2.Query($dropsql) - } catch {} - } + $server1.Query($createSql) + } - Context "Copy linked server with the same properties" { - It "copies successfully" { - $result = Copy-DbaLinkedServer -Source $TestConfig.instance2 -Destination $TestConfig.instance3 -LinkedServer dbatoolsci_localhost -WarningAction SilentlyContinue - $result | Select-Object -ExpandProperty Name -Unique | Should Be "dbatoolsci_localhost" - $result | Select-Object -ExpandProperty Status -Unique | Should Be "Successful" - } + AfterAll { + $dropSql = "EXEC master.dbo.sp_dropserver @server=N'dbatoolsci_localhost', @droplogins='droplogins'; + EXEC master.dbo.sp_dropserver @server=N'dbatoolsci_localhost2', @droplogins='droplogins'" + try { + $server1.Query($dropSql) + $server2.Query($dropSql) + } catch { + # Silently continue + } + } - It "retains the same properties" { - $LinkedServer1 = Get-DbaLinkedServer -SqlInstance $server1 -LinkedServer dbatoolsci_localhost -WarningAction SilentlyContinue - $LinkedServer2 = Get-DbaLinkedServer -SqlInstance $server2 -LinkedServer dbatoolsci_localhost -WarningAction SilentlyContinue + Context "When copying linked server with the same properties" { + It "Copies successfully" { + $copySplat = @{ + Source = $TestConfig.instance2 + Destination = $TestConfig.instance3 + LinkedServer = 'dbatoolsci_localhost' + WarningAction = 'SilentlyContinue' + } + $result = Copy-DbaLinkedServer @copySplat + $result | Select-Object -ExpandProperty Name -Unique | Should -BeExactly "dbatoolsci_localhost" + $result | Select-Object -ExpandProperty Status -Unique | Should -BeExactly "Successful" + } - # Compare its value - $LinkedServer1.Name | Should Be $LinkedServer2.Name - $LinkedServer1.LinkedServer | Should Be $LinkedServer2.LinkedServer - } + It "Retains the same properties" { + $getLinkSplat = @{ + LinkedServer = 'dbatoolsci_localhost' + WarningAction = 'SilentlyContinue' + } + $LinkedServer1 = Get-DbaLinkedServer -SqlInstance $server1 @getLinkSplat + $LinkedServer2 = Get-DbaLinkedServer -SqlInstance $server2 @getLinkSplat - It "skips existing linked servers" { - $results = Copy-DbaLinkedServer -Source $TestConfig.instance2 -Destination $TestConfig.instance3 -LinkedServer dbatoolsci_localhost -WarningAction SilentlyContinue - $results.Status | Should Be "Skipped" - } + $LinkedServer1.Name | Should -BeExactly $LinkedServer2.Name + $LinkedServer1.LinkedServer | Should -BeExactly $LinkedServer2.LinkedServer + } + + It "Skips existing linked servers" { + $copySplat = @{ + Source = $TestConfig.instance2 + Destination = $TestConfig.instance3 + LinkedServer = 'dbatoolsci_localhost' + WarningAction = 'SilentlyContinue' + } + $results = Copy-DbaLinkedServer @copySplat + $results.Status | Should -BeExactly "Skipped" + } # SQLNCLI10 and SQLNCLI11 are not used on newer versions, not sure which versions, but skipping if later than 2017 - It -Skip:$($server1.VersionMajor -gt 14 -or $server2.VersionMajor -gt 14) "upgrades SQLNCLI provider based on what is registered" { - $result = Copy-DbaLinkedServer -Source $TestConfig.instance2 -Destination $TestConfig.instance3 -LinkedServer dbatoolsci_localhost2 -UpgradeSqlClient - $server1 = Connect-DbaInstance -SqlInstance $TestConfig.instance2 - $server2 = Connect-DbaInstance -SqlInstance $TestConfig.instance3 - $server1.LinkedServers.Script() -match 'SQLNCLI10' | Should -Be $true - $server2.LinkedServers.Script() -match 'SQLNCLI11' | Should -Be $true + Context "When upgrading SQL Client provider" -Skip:($server1.VersionMajor -gt 14 -or $server2.VersionMajor -gt 14) { + BeforeAll { + $result = Copy-DbaLinkedServer -Source $TestConfig.instance2 -Destination $TestConfig.instance3 -LinkedServer dbatoolsci_localhost2 -UpgradeSqlClient + $sourceLinked = Get-DbaLinkedServer -SqlInstance $TestConfig.instance2 + $destLinked = Get-DbaLinkedServer -SqlInstance $TestConfig.instance3 + } + + It "Should retain SQLNCLI10 on source" { + $sourceLinked.Script() | Should -Match 'SQLNCLI10' + } + + It "Should upgrade to SQLNCLI11 on destination" { + $destLinked.Script() | Should -Match 'SQLNCLI11' + } } - } -} +} \ No newline at end of file diff --git a/tests/Copy-DbaPolicyManagement.Tests.ps1 b/tests/Copy-DbaPolicyManagement.Tests.ps1 index d07cb1296f..99043c6c15 100644 --- a/tests/Copy-DbaPolicyManagement.Tests.ps1 +++ b/tests/Copy-DbaPolicyManagement.Tests.ps1 @@ -1,19 +1,37 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'Source', 'SourceSqlCredential', 'Destination', 'DestinationSqlCredential', 'Policy', 'ExcludePolicy', 'Condition', 'ExcludeCondition', 'Force', '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 "Copy-DbaPolicyManagement" -Tag "UnitTests" { + Context "Parameter validation" { + BeforeAll { + $command = Get-Command Copy-DbaPolicyManagement + $expected = $TestConfig.CommonParameters + $expected += @( + "Source", + "SourceSqlCredential", + "Destination", + "DestinationSqlCredential", + "Policy", + "ExcludePolicy", + "Condition", + "ExcludeCondition", + "Force", + "EnableException", + "Confirm", + "WhatIf" + ) + } + + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } -} -<# - Integration test should appear below and are custom to the command you are writing. - Read https://github.com/dataplat/dbatools/blob/development/contributing.md#tests - for more guidence. -#> \ No newline at end of file +} \ No newline at end of file diff --git a/tests/Copy-DbaRegServer.Tests.ps1 b/tests/Copy-DbaRegServer.Tests.ps1 index a995598688..412031e6ad 100644 --- a/tests/Copy-DbaRegServer.Tests.ps1 +++ b/tests/Copy-DbaRegServer.Tests.ps1 @@ -1,55 +1,77 @@ -$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 = 'Source', 'SourceSqlCredential', 'Destination', 'DestinationSqlCredential', 'Group', 'SwitchServerName', 'Force', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 - } - } -} +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { - Context "Setup" { +Describe "Copy-DbaRegServer" -Tag "UnitTests" { + Context "Parameter validation" { BeforeAll { - $server = Connect-DbaInstance $TestConfig.instance2 - $regstore = New-Object Microsoft.SqlServer.Management.RegisteredServers.RegisteredServersStore($server.ConnectionContext.SqlConnectionObject) - $dbstore = $regstore.DatabaseEngineServerGroup - - $servername = "dbatoolsci-server1" - $group = "dbatoolsci-group1" - $regservername = "dbatoolsci-server12" - $regserverdescription = "dbatoolsci-server123" - - $newgroup = New-Object Microsoft.SqlServer.Management.RegisteredServers.ServerGroup($dbstore, $group) - $newgroup.Create() - $dbstore.Refresh() - - $groupstore = $dbstore.ServerGroups[$group] - $newserver = New-Object Microsoft.SqlServer.Management.RegisteredServers.RegisteredServer($groupstore, $regservername) - $newserver.ServerName = $servername - $newserver.Description = $regserverdescription - $newserver.Create() + $command = Get-Command Copy-DbaRegServer + $expected = $TestConfig.CommonParameters + $expected += @( + "Source", + "SourceSqlCredential", + "Destination", + "DestinationSqlCredential", + "Group", + "SwitchServerName", + "Force", + "EnableException", + "Confirm", + "WhatIf" + ) + } + + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem } - AfterAll { - $newgroup.Drop() - $server = Connect-DbaInstance $TestConfig.instance1 - $regstore = New-Object Microsoft.SqlServer.Management.RegisteredServers.RegisteredServersStore($server.ConnectionContext.SqlConnectionObject) - $dbstore = $regstore.DatabaseEngineServerGroup - $groupstore = $dbstore.ServerGroups[$group] - $groupstore.Drop() + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } + } +} - $results = Copy-DbaRegServer -Source $TestConfig.instance2 -Destination $TestConfig.instance1 -WarningAction SilentlyContinue -CMSGroup $group +Describe "Copy-DbaRegServer" -Tag "IntegrationTests" { + BeforeAll { + $server = Connect-DbaInstance $TestConfig.instance2 + $regstore = New-Object Microsoft.SqlServer.Management.RegisteredServers.RegisteredServersStore($server.ConnectionContext.SqlConnectionObject) + $dbstore = $regstore.DatabaseEngineServerGroup - It "should report success" { - $results.Status | Should Be "Successful", "Successful" + $servername = "dbatoolsci-server1" + $group = "dbatoolsci-group1" + $regservername = "dbatoolsci-server12" + $regserverdescription = "dbatoolsci-server123" + + $newgroup = New-Object Microsoft.SqlServer.Management.RegisteredServers.ServerGroup($dbstore, $group) + $newgroup.Create() + $dbstore.Refresh() + + $groupstore = $dbstore.ServerGroups[$group] + $newserver = New-Object Microsoft.SqlServer.Management.RegisteredServers.RegisteredServer($groupstore, $regservername) + $newserver.ServerName = $servername + $newserver.Description = $regserverdescription + $newserver.Create() + } + + AfterAll { + $newgroup.Drop() + $server = Connect-DbaInstance $TestConfig.instance1 + $regstore = New-Object Microsoft.SqlServer.Management.RegisteredServers.RegisteredServersStore($server.ConnectionContext.SqlConnectionObject) + $dbstore = $regstore.DatabaseEngineServerGroup + $groupstore = $dbstore.ServerGroups[$group] + $groupstore.Drop() + } + + Context "When copying registered servers" { + BeforeAll { + $results = Copy-DbaRegServer -Source $TestConfig.instance2 -Destination $TestConfig.instance1 -CMSGroup $group } - # Property Comparisons will come later when we have the commands + It "Should complete successfully" { + $results.Status | Should -Be @("Successful", "Successful") + } } } diff --git a/tests/Copy-DbaResourceGovernor.Tests.ps1 b/tests/Copy-DbaResourceGovernor.Tests.ps1 index 5381e0912a..a368cc2d3c 100644 --- a/tests/Copy-DbaResourceGovernor.Tests.ps1 +++ b/tests/Copy-DbaResourceGovernor.Tests.ps1 @@ -1,80 +1,94 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'Source', 'SourceSqlCredential', 'Destination', 'DestinationSqlCredential', 'ResourcePool', 'ExcludeResourcePool', 'Force', '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 "Copy-DbaResourceGovernor" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Copy-DbaResourceGovernor + $expected = $TestConfig.CommonParameters + $expected += @( + "Source", + "SourceSqlCredential", + "Destination", + "DestinationSqlCredential", + "ResourcePool", + "ExcludeResourcePool", + "Force", + "EnableException", + "Confirm", + "WhatIf" + ) + } + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tag "IntegrationTests" { +Describe "Copy-DbaResourceGovernor" -Tag "IntegrationTests" { BeforeAll { - $sql = "CREATE RESOURCE POOL dbatoolsci_prod - WITH - ( - MAX_CPU_PERCENT = 100, - MIN_CPU_PERCENT = 50 - )" - Invoke-DbaQuery -WarningAction SilentlyContinue -SqlInstance $TestConfig.instance2 -Query $sql - $sql = "CREATE WORKLOAD GROUP dbatoolsci_prodprocessing - WITH - ( - IMPORTANCE = MEDIUM - ) USING dbatoolsci_prod" - Invoke-DbaQuery -WarningAction SilentlyContinue -SqlInstance $TestConfig.instance2 -Query $sql - $sql = "CREATE RESOURCE POOL dbatoolsci_offhoursprocessing - WITH - ( - MAX_CPU_PERCENT = 50, - MIN_CPU_PERCENT = 0 - )" - Invoke-DbaQuery -WarningAction SilentlyContinue -SqlInstance $TestConfig.instance2 -Query $sql - $sql = "CREATE WORKLOAD GROUP dbatoolsci_goffhoursprocessing - WITH - ( - IMPORTANCE = LOW - ) - USING dbatoolsci_offhoursprocessing" - Invoke-DbaQuery -WarningAction SilentlyContinue -SqlInstance $TestConfig.instance2 -Query $sql - $sql = "ALTER RESOURCE GOVERNOR RECONFIGURE" - Invoke-DbaQuery -WarningAction SilentlyContinue -SqlInstance $TestConfig.instance2 -Query $sql - $sql = "CREATE FUNCTION dbatoolsci_fnRG() - RETURNS sysname - WITH SCHEMABINDING - AS - BEGIN - RETURN N'dbatoolsci_goffhoursprocessing' - END" - Invoke-DbaQuery -WarningAction SilentlyContinue -SqlInstance $TestConfig.instance2 -Query $sql - $sql = "ALTER RESOURCE GOVERNOR with (CLASSIFIER_FUNCTION = dbo.dbatoolsci_fnRG); ALTER RESOURCE GOVERNOR RECONFIGURE;" - Invoke-DbaQuery -WarningAction SilentlyContinue -SqlInstance $TestConfig.instance2 -Query $sql + $querySplat = @{ + SqlInstance = $TestConfig.instance2 + WarningAction = 'SilentlyContinue' + } + + # Create prod pool and workload + Invoke-DbaQuery @querySplat -Query "CREATE RESOURCE POOL dbatoolsci_prod WITH (MAX_CPU_PERCENT = 100, MIN_CPU_PERCENT = 50)" + Invoke-DbaQuery @querySplat -Query "CREATE WORKLOAD GROUP dbatoolsci_prodprocessing WITH (IMPORTANCE = MEDIUM) USING dbatoolsci_prod" + + # Create offhours pool and workload + Invoke-DbaQuery @querySplat -Query "CREATE RESOURCE POOL dbatoolsci_offhoursprocessing WITH (MAX_CPU_PERCENT = 50, MIN_CPU_PERCENT = 0)" + Invoke-DbaQuery @querySplat -Query "CREATE WORKLOAD GROUP dbatoolsci_goffhoursprocessing WITH (IMPORTANCE = LOW) USING dbatoolsci_offhoursprocessing" + + Invoke-DbaQuery @querySplat -Query "ALTER RESOURCE GOVERNOR RECONFIGURE" + + # Create and set classifier function + Invoke-DbaQuery @querySplat -Query "CREATE FUNCTION dbatoolsci_fnRG() RETURNS sysname WITH SCHEMABINDING AS BEGIN RETURN N'dbatoolsci_goffhoursprocessing' END" + Invoke-DbaQuery @querySplat -Query "ALTER RESOURCE GOVERNOR with (CLASSIFIER_FUNCTION = dbo.dbatoolsci_fnRG); ALTER RESOURCE GOVERNOR RECONFIGURE;" } + AfterAll { - Get-DbaProcess -SqlInstance $TestConfig.instance2, $TestConfig.instance3 -Program 'dbatools PowerShell module - dbatools.io' | Stop-DbaProcess -WarningAction SilentlyContinue - Invoke-DbaQuery -WarningAction SilentlyContinue -SqlInstance $TestConfig.instance2, $TestConfig.instance3 -Query "ALTER RESOURCE GOVERNOR WITH (CLASSIFIER_FUNCTION = NULL); ALTER RESOURCE GOVERNOR RECONFIGURE" - Invoke-DbaQuery -WarningAction SilentlyContinue -SqlInstance $TestConfig.instance2, $TestConfig.instance3 -Query "DROP FUNCTION [dbo].[dbatoolsci_fnRG];ALTER RESOURCE GOVERNOR RECONFIGURE" - Invoke-DbaQuery -WarningAction SilentlyContinue -SqlInstance $TestConfig.instance2, $TestConfig.instance3 -Query "DROP WORKLOAD GROUP [dbatoolsci_prodprocessing];ALTER RESOURCE GOVERNOR RECONFIGURE" - Invoke-DbaQuery -WarningAction SilentlyContinue -SqlInstance $TestConfig.instance2, $TestConfig.instance3 -Query "DROP WORKLOAD GROUP [dbatoolsci_goffhoursprocessing];ALTER RESOURCE GOVERNOR RECONFIGURE" - Invoke-DbaQuery -WarningAction SilentlyContinue -SqlInstance $TestConfig.instance2, $TestConfig.instance3 -Query "DROP RESOURCE POOL [dbatoolsci_offhoursprocessing];ALTER RESOURCE GOVERNOR RECONFIGURE" - Invoke-DbaQuery -WarningAction SilentlyContinue -SqlInstance $TestConfig.instance2, $TestConfig.instance3 -Query "DROP RESOURCE POOL [dbatoolsci_prod];ALTER RESOURCE GOVERNOR RECONFIGURE" + $cleanupSplat = @{ + SqlInstance = $TestConfig.instance2, $TestConfig.instance3 + WarningAction = 'SilentlyContinue' + } + + Get-DbaProcess -SqlInstance $TestConfig.instance2, $TestConfig.instance3 -Program 'dbatools PowerShell module - dbatools.io' | Stop-DbaProcess -WarningAction SilentlyContinue + + Invoke-DbaQuery @cleanupSplat -Query "ALTER RESOURCE GOVERNOR WITH (CLASSIFIER_FUNCTION = NULL); ALTER RESOURCE GOVERNOR RECONFIGURE" + Invoke-DbaQuery @cleanupSplat -Query "DROP FUNCTION [dbo].[dbatoolsci_fnRG];ALTER RESOURCE GOVERNOR RECONFIGURE" + Invoke-DbaQuery @cleanupSplat -Query "DROP WORKLOAD GROUP [dbatoolsci_prodprocessing];ALTER RESOURCE GOVERNOR RECONFIGURE" + Invoke-DbaQuery @cleanupSplat -Query "DROP WORKLOAD GROUP [dbatoolsci_goffhoursprocessing];ALTER RESOURCE GOVERNOR RECONFIGURE" + Invoke-DbaQuery @cleanupSplat -Query "DROP RESOURCE POOL [dbatoolsci_offhoursprocessing];ALTER RESOURCE GOVERNOR RECONFIGURE" + Invoke-DbaQuery @cleanupSplat -Query "DROP RESOURCE POOL [dbatoolsci_prod];ALTER RESOURCE GOVERNOR RECONFIGURE" } - Context "Command works" { - It "copies the resource governor successfully" { - $results = Copy-DbaResourceGovernor -Source $TestConfig.instance2 -Destination $TestConfig.instance3 -Force -WarningAction SilentlyContinue - $results.Status | Select-Object -Unique | Should -Be 'Successful' + Context "When copying resource governor settings" { + It "Copies the resource governor successfully" { + $copyRGSplat = @{ + Source = $TestConfig.instance2 + Destination = $TestConfig.instance3 + Force = $true + WarningAction = 'SilentlyContinue' + } + + $results = Copy-DbaResourceGovernor @copyRGSplat + $results.Status | Select-Object -Unique | Should -BeExactly 'Successful' $results.Status.Count | Should -BeGreaterThan 3 $results.Name | Should -Contain 'dbatoolsci_prod' } - It "returns the proper classifier function" { + + It "Returns the proper classifier function" { $results = Get-DbaRgClassifierFunction -SqlInstance $TestConfig.instance3 - $results.Name | Should -Be 'dbatoolsci_fnRG' + $results.Name | Should -BeExactly 'dbatoolsci_fnRG' } } -} +} \ No newline at end of file diff --git a/tests/Copy-DbaSpConfigure.Tests.ps1 b/tests/Copy-DbaSpConfigure.Tests.ps1 index fd05be5e72..f2e777d5ee 100644 --- a/tests/Copy-DbaSpConfigure.Tests.ps1 +++ b/tests/Copy-DbaSpConfigure.Tests.ps1 @@ -1,55 +1,79 @@ -$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 = 'Source', 'SourceSqlCredential', 'Destination', 'DestinationSqlCredential', 'ConfigName', 'ExcludeConfigName', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + +Describe "Copy-DbaSpConfigure" -Tag "UnitTests" { + Context "Parameter validation" { + BeforeAll { + $command = Get-Command Copy-DbaSpConfigure + $expected = $TestConfig.CommonParameters + $expected += @( + "Source", + "SourceSqlCredential", + "Destination", + "DestinationSqlCredential", + "ConfigName", + "ExcludeConfigName", + "EnableException", + "Confirm", + "WhatIf" + ) + } + + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasParams = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasParams | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { - Context "Copy config with the same properties." { +Describe "Copy-DbaSpConfigure" -Tag "IntegrationTests" { + Context "When copying configuration with the same properties" { BeforeAll { - $sourceconfig = (Get-DbaSpConfigure -SqlInstance $TestConfig.instance1 -ConfigName RemoteQueryTimeout).ConfiguredValue - $destconfig = (Get-DbaSpConfigure -SqlInstance $TestConfig.instance2 -ConfigName RemoteQueryTimeout).ConfiguredValue - # Set it so they don't match - if ($sourceconfig -and $destconfig) { - $newvalue = $sourceconfig + $destconfig - $null = Set-DbaSpConfigure -SqlInstance $TestConfig.instance2 -ConfigName RemoteQueryTimeout -Value $newvalue + $sourceConfig = Get-DbaSpConfigure -SqlInstance $TestConfig.instance1 -ConfigName RemoteQueryTimeout + $destConfig = Get-DbaSpConfigure -SqlInstance $TestConfig.instance2 -ConfigName RemoteQueryTimeout + $sourceConfigValue = $sourceConfig.ConfiguredValue + $destConfigValue = $destConfig.ConfiguredValue + + # Set different values to ensure they don't match + if ($sourceConfigValue -and $destConfigValue) { + $newValue = $sourceConfigValue + $destConfigValue + $null = Set-DbaSpConfigure -SqlInstance $TestConfig.instance2 -ConfigName RemoteQueryTimeout -Value $newValue } } + AfterAll { - if ($destconfig -and $destconfig -ne $sourceconfig) { - $null = Set-DbaSpConfigure -SqlInstance $TestConfig.instance2 -ConfigName RemoteQueryTimeout -Value $destconfig + if ($destConfigValue -and $destConfigValue -ne $sourceConfigValue) { + $null = Set-DbaSpConfigure -SqlInstance $TestConfig.instance2 -ConfigName RemoteQueryTimeout -Value $destConfigValue } } - It "starts with different values" { + It "Should start with different values" { $config1 = Get-DbaSpConfigure -SqlInstance $TestConfig.instance1 -ConfigName RemoteQueryTimeout $config2 = Get-DbaSpConfigure -SqlInstance $TestConfig.instance2 -ConfigName RemoteQueryTimeout - $config1.ConfiguredValue -ne $config2.ConfiguredValue | Should be $true + $config1.ConfiguredValue | Should -Not -Be $config2.ConfiguredValue } - It "copied successfully" { + It "Should copy successfully" { $results = Copy-DbaSpConfigure -Source $TestConfig.instance1 -Destination $TestConfig.instance2 -ConfigName RemoteQueryTimeout - $results.Status | Should Be "Successful" + $results.Status | Should -Be "Successful" } - It "retains the same properties" { + It "Should retain the same properties after copy" { $config1 = Get-DbaSpConfigure -SqlInstance $TestConfig.instance1 -ConfigName RemoteQueryTimeout $config2 = Get-DbaSpConfigure -SqlInstance $TestConfig.instance2 -ConfigName RemoteQueryTimeout - $config1.ConfiguredValue | Should be $config2.ConfiguredValue + $config1.ConfiguredValue | Should -Be $config2.ConfiguredValue } - It "didn't modify the source" { - $newconfig = (Get-DbaSpConfigure -SqlInstance $TestConfig.instance1 -ConfigName RemoteQueryTimeout).ConfiguredValue - $newconfig -eq $sourceconfig | Should Be $true + It "Should not modify the source configuration" { + $newConfig = Get-DbaSpConfigure -SqlInstance $TestConfig.instance1 -ConfigName RemoteQueryTimeout + $newConfig.ConfiguredValue | Should -Be $sourceConfigValue } } } diff --git a/tests/Copy-DbaSsisCatalog.Tests.ps1 b/tests/Copy-DbaSsisCatalog.Tests.ps1 index ee4287596b..cfad21d21d 100644 --- a/tests/Copy-DbaSsisCatalog.Tests.ps1 +++ b/tests/Copy-DbaSsisCatalog.Tests.ps1 @@ -1,19 +1,38 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'Source', 'Destination', 'SourceSqlCredential', 'DestinationSqlCredential', 'Project', 'Folder', 'Environment', 'CreateCatalogPassword', 'EnableSqlClr', 'Force', '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 "Copy-DbaSsisCatalog" -Tag "UnitTests" { + Context "Parameter validation" { + BeforeAll { + $command = Get-Command Copy-DbaSsisCatalog + $expected = $TestConfig.CommonParameters + $expected += @( + "Source", + "Destination", + "SourceSqlCredential", + "DestinationSqlCredential", + "Project", + "Folder", + "Environment", + "CreateCatalogPassword", + "EnableSqlClr", + "Force", + "EnableException", + "Confirm", + "WhatIf" + ) + } + + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } -} -<# - Integration test should appear below and are custom to the command you are writing. - Read https://github.com/sqlcollaborative/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/Copy-DbaStartupProcedure.Tests.ps1 b/tests/Copy-DbaStartupProcedure.Tests.ps1 index adec8ddbb6..6174c5c331 100644 --- a/tests/Copy-DbaStartupProcedure.Tests.ps1 +++ b/tests/Copy-DbaStartupProcedure.Tests.ps1 @@ -1,24 +1,40 @@ -$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 = 'Source', 'SourceSqlCredential', 'Destination', 'DestinationSqlCredential', 'Procedure', 'ExcludeProcedure', 'Force', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + +Describe "Copy-DbaStartupProcedure" -Tag "UnitTests" { + Context "Parameter validation" { + BeforeAll { + $command = Get-Command Copy-DbaStartupProcedure + $expected = $TestConfig.CommonParameters + $expected += @( + 'Source', + 'SourceSqlCredential', + 'Destination', + 'DestinationSqlCredential', + 'Procedure', + 'ExcludeProcedure', + 'Force', + 'EnableException', + 'Confirm', + 'WhatIf' + ) + } + + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -<# - Integration test should appear below and are custom to the command you are writing. - Read https://github.com/dataplat/dbatools/blob/development/contributing.md#tests - for more guidence. -#> -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { +Describe "Copy-DbaStartupProcedure" -Tag "IntegrationTests" { BeforeAll { $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 $procName = "dbatoolsci_test_startup" @@ -35,11 +51,15 @@ Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { Invoke-DbaQuery -SqlInstance $TestConfig.instance2, $TestConfig.instance3 -Database "master" -Query "DROP PROCEDURE dbatoolsci_test_startup" } - Context "Command actually works" { - $results = Copy-DbaStartupProcedure -Source $TestConfig.instance2 -Destination $TestConfig.instance3 + Context "When copying startup procedures" { + BeforeAll { + $results = Copy-DbaStartupProcedure -Source $TestConfig.instance2 -Destination $TestConfig.instance3 + } + It "Should include test procedure: $procName" { ($results | Where-Object Name -eq $procName).Name | Should -Be $procName } + It "Should be successful" { ($results | Where-Object Name -eq $procName).Status | Should -Be 'Successful' } diff --git a/tests/Copy-DbaSystemDbUserObject.Tests.ps1 b/tests/Copy-DbaSystemDbUserObject.Tests.ps1 index 91cc69a1d0..f445c12301 100644 --- a/tests/Copy-DbaSystemDbUserObject.Tests.ps1 +++ b/tests/Copy-DbaSystemDbUserObject.Tests.ps1 @@ -1,18 +1,39 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'Source', 'SourceSqlCredential', 'Destination', 'DestinationSqlCredential', 'Force', 'Classic', '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 "Copy-DbaSystemDbUserObject" -Tag "UnitTests" { + Context "Parameter validation" { + BeforeAll { + $command = Get-Command Copy-DbaSystemDbUserObject + $expected = $TestConfig.CommonParameters + $expected += @( + "Source", + "SourceSqlCredential", + "Destination", + "DestinationSqlCredential", + "Force", + "Classic", + "EnableException", + "Confirm", + "WhatIf" + ) + } + + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { + +Describe "Copy-DbaSystemDbUserObject" -Tag "IntegrationTests" { BeforeAll { #Function Scripts roughly From https://docs.microsoft.com/en-us/sql/t-sql/statements/create-function-transact-sql #Rule Scripts roughly from https://docs.microsoft.com/en-us/sql/t-sql/statements/create-rule-transact-sql @@ -59,26 +80,27 @@ AS $null = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Query $TableFunction $null = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Query $Rule } + AfterAll { $null = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Query "DROP FUNCTION dbo.dbatoolscs_ISOweek;" $null = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Query "DROP FUNCTION dbo.dbatoolsci_TableFunction;" $null = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Query "DROP RULE dbo.dbatoolsci_range_rule;" } - Context "Should Copy Objects to the same instance" { - $results = Copy-DbaSystemDbUserObject -Source $TestConfig.instance2 -Destination $TestConfig.instance2 - It "Should execute with default parameters" { - $results | Should Not Be Null + Context "When copying objects to the same instance" { + It "Should execute successfully with default parameters" { + $results = Copy-DbaSystemDbUserObject -Source $TestConfig.instance2 -Destination $TestConfig.instance2 + $results | Should -Not -BeNullOrEmpty } - $results = Copy-DbaSystemDbUserObject -Source $TestConfig.instance2 -Destination $TestConfig.instance2 -Classic - It "Should execute with -Classic parameter" { - $results | Should Not Be Null + It "Should execute successfully with -Classic parameter" { + $results = Copy-DbaSystemDbUserObject -Source $TestConfig.instance2 -Destination $TestConfig.instance2 -Classic + $results | Should -Not -BeNullOrEmpty } - $results = Copy-DbaSystemDbUserObject -Source $TestConfig.instance2 -Destination $TestConfig.instance2 -Force - It "Should execute with -Classic parameter" { - $results | Should Not Be Null + It "Should execute successfully with -Force parameter" { + $results = Copy-DbaSystemDbUserObject -Source $TestConfig.instance2 -Destination $TestConfig.instance2 -Force + $results | Should -Not -BeNullOrEmpty } } } diff --git a/tests/Copy-DbaXESession.Tests.ps1 b/tests/Copy-DbaXESession.Tests.ps1 index 01d8545deb..6c9193f3c4 100644 --- a/tests/Copy-DbaXESession.Tests.ps1 +++ b/tests/Copy-DbaXESession.Tests.ps1 @@ -1,19 +1,35 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'Source', 'Destination', 'SourceSqlCredential', 'DestinationSqlCredential', 'XeSession', 'ExcludeXeSession', 'Force', '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 "Copy-DbaXESession" -Tag "UnitTests" { + Context "Parameter validation" { + BeforeAll { + $command = Get-Command Copy-DbaXESession + $expected = $TestConfig.CommonParameters + $expected += @( + "Source", + "Destination", + "SourceSqlCredential", + "DestinationSqlCredential", + "XeSession", + "ExcludeXeSession", + "Force", + "EnableException", + "Confirm", + "WhatIf" + ) + } + + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } -} -<# - Integration test should appear below and are custom to the command you are writing. - Read https://github.com/dataplat/dbatools/blob/development/contributing.md#tests - for more guidence. -#> \ No newline at end of file +} \ No newline at end of file diff --git a/tests/Copy-DbaXESessionTemplate.Tests.ps1 b/tests/Copy-DbaXESessionTemplate.Tests.ps1 index d9b07a268d..c5a416e9e5 100644 --- a/tests/Copy-DbaXESessionTemplate.Tests.ps1 +++ b/tests/Copy-DbaXESessionTemplate.Tests.ps1 @@ -1,24 +1,38 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'Path', 'Destination', '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 "Copy-DbaXESessionTemplate" -Tag "UnitTests" { + Context "Parameter validation" { + BeforeAll { + $command = Get-Command Copy-DbaXESessionTemplate + $expected = $TestConfig.CommonParameters + $expected += @( + "Path", + "Destination", + "EnableException" + ) + } + + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { - Context "Get Template Index" { - $null = Copy-DbaXESessionTemplate *>1 - $source = ((Get-DbaXESessionTemplate -Path $Path | Where-Object Source -ne Microsoft).Path | Select-Object -First 1).Name - It "copies the files properly" { - Get-ChildItem "$home\Documents\SQL Server Management Studio\Templates\XEventTemplates" | Where-Object Name -eq $source | Should Not Be Null +Describe "Copy-DbaXESessionTemplate" -Tag "IntegrationTests" { + Context "When copying XE session templates" { + It "Successfully copies the template files" { + $null = Copy-DbaXESessionTemplate *>1 + $source = ((Get-DbaXESessionTemplate | Where-Object Source -ne Microsoft).Path | Select-Object -First 1).Name + Get-ChildItem "$home\Documents\SQL Server Management Studio\Templates\XEventTemplates" | Where-Object Name -eq $source | Should -Not -BeNullOrEmpty } } } \ No newline at end of file diff --git a/tests/Disable-DbaAgHadr.Tests.ps1 b/tests/Disable-DbaAgHadr.Tests.ps1 index d9a4fbb9ea..1a35a28cdf 100644 --- a/tests/Disable-DbaAgHadr.Tests.ps1 +++ b/tests/Disable-DbaAgHadr.Tests.ps1 @@ -1,28 +1,47 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) -Describe "$CommandName Unit Tests" -Tag "UnitTests" { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'Credential', 'Force', '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 "Disable-DbaAgHadr" -Tag "UnitTests" { + Context "Parameter validation" { + BeforeAll { + $command = Get-Command Disable-DbaAgHadr + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "Credential", + "Force", + "EnableException", + "Confirm", + "WhatIf" + ) + } + + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -# $TestConfig.instance3 is used for Availability Group tests and needs Hadr service setting enabled - -Describe "$commandname Integration Tests" -Tag "IntegrationTests" { +Describe "Disable-DbaAgHadr" -Tag "IntegrationTests" { AfterAll { Enable-DbaAgHadr -SqlInstance $TestConfig.instance3 -Confirm:$false -Force } - $results = Disable-DbaAgHadr -SqlInstance $TestConfig.instance3 -Confirm:$false -Force + Context "When disabling HADR" { + BeforeAll { + $results = Disable-DbaAgHadr -SqlInstance $TestConfig.instance3 -Confirm:$false -Force + } - It "disables hadr" { - $results.IsHadrEnabled | Should -Be $false + It "Successfully disables HADR" { + $results.IsHadrEnabled | Should -BeFalse + } } } diff --git a/tests/Disable-DbaDbEncryption.Tests.ps1 b/tests/Disable-DbaDbEncryption.Tests.ps1 index 120a74adec..fb3e00c1c2 100644 --- a/tests/Disable-DbaDbEncryption.Tests.ps1 +++ b/tests/Disable-DbaDbEncryption.Tests.ps1 @@ -1,43 +1,67 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) -Describe "$CommandName Unit Tests" -Tags "UnitTests" { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'InputObject', 'EnableException', 'NoEncryptionKeyDrop' - $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 "Disable-DbaDbEncryption" -Tag "UnitTests" { + Context "Parameter validation" { + BeforeAll { + $command = Get-Command Disable-DbaDbEncryption + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "Database", + "InputObject", + "NoEncryptionKeyDrop", + "EnableException" + ) + } + + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name | Where-Object { $PSItem -notin "WhatIf", "Confirm" } + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { +Describe "Disable-DbaDbEncryption" -Tag "IntegrationTests" { BeforeAll { $PSDefaultParameterValues["*:Confirm"] = $false $passwd = ConvertTo-SecureString "dbatools.IO" -AsPlainText -Force + + # Setup master key if needed $masterkey = Get-DbaDbMasterKey -SqlInstance $TestConfig.instance2 -Database master if (-not $masterkey) { - $delmasterkey = $true + $global:delmasterkey = $true $masterkey = New-DbaServiceMasterKey -SqlInstance $TestConfig.instance2 -SecurePassword $passwd } - $mastercert = Get-DbaDbCertificate -SqlInstance $TestConfig.instance2 -Database master | Where-Object Name -notmatch "##" | Select-Object -First 1 + + # Setup master certificate if needed + $mastercert = Get-DbaDbCertificate -SqlInstance $TestConfig.instance2 -Database master | + Where-Object Name -notmatch "##" | + Select-Object -First 1 if (-not $mastercert) { - $delmastercert = $true + $global:delmastercert = $true $mastercert = New-DbaDbCertificate -SqlInstance $TestConfig.instance2 } - $db = New-DbaDatabase -SqlInstance $TestConfig.instance2 - $db | New-DbaDbMasterKey -SecurePassword $passwd - $db | New-DbaDbCertificate - $db | New-DbaDbEncryptionKey -Force - $db | Enable-DbaDbEncryption -EncryptorName $mastercert.Name -Force + # Create and configure test database + $global:testDb = New-DbaDatabase -SqlInstance $TestConfig.instance2 + $testDb | New-DbaDbMasterKey -SecurePassword $passwd + $testDb | New-DbaDbCertificate + $testDb | New-DbaDbEncryptionKey -Force + $testDb | Enable-DbaDbEncryption -EncryptorName $mastercert.Name -Force } AfterAll { - if ($db) { - $db | Remove-DbaDatabase + if ($testDb) { + $testDb | Remove-DbaDatabase } if ($delmastercert) { $mastercert | Remove-DbaDbCertificate @@ -47,20 +71,38 @@ Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { } } - Context "Command actually works" { - It "should disable encryption on a database with piping" { - # Give it time to finish encrypting or it'll error - Start-Sleep 10 - $results = $db | Disable-DbaDbEncryption -NoEncryptionKeyDrop -WarningVariable warn 3> $null - $warn | Should -Be $null + Context "When disabling encryption via pipeline" { + BeforeAll { + Start-Sleep -Seconds 10 # Allow encryption to complete + $results = $testDb | Disable-DbaDbEncryption -NoEncryptionKeyDrop -WarningVariable warn 3> $null + } + + It "Should complete without warnings" { + $warn | Should -BeNullOrEmpty + } + + It "Should disable encryption" { $results.EncryptionEnabled | Should -Be $false } - It "should disable encryption on a database" { - $null = $db | Enable-DbaDbEncryption -EncryptorName $mastercert.Name -Force - # Give it time to finish encrypting or it'll error - Start-Sleep 10 - $results = Disable-DbaDbEncryption -SqlInstance $TestConfig.instance2 -Database $db.Name -WarningVariable warn 3> $null - $warn | Should -Be $null + } + + Context "When disabling encryption via parameters" { + BeforeAll { + $null = $testDb | Enable-DbaDbEncryption -EncryptorName $mastercert.Name -Force + Start-Sleep -Seconds 10 # Allow encryption to complete + + $splatDisable = @{ + SqlInstance = $TestConfig.instance2 + Database = $testDb.Name + } + $results = Disable-DbaDbEncryption @splatDisable -WarningVariable warn 3> $null + } + + It "Should complete without warnings" { + $warn | Should -BeNullOrEmpty + } + + It "Should disable encryption" { $results.EncryptionEnabled | Should -Be $false } } diff --git a/tests/Disable-DbaFilestream.Tests.ps1 b/tests/Disable-DbaFilestream.Tests.ps1 index bfd631eda3..d34b4a2ec0 100644 --- a/tests/Disable-DbaFilestream.Tests.ps1 +++ b/tests/Disable-DbaFilestream.Tests.ps1 @@ -14,20 +14,24 @@ Describe "$CommandName Unit Tests" -Tag 'UnitTests' { } <# -Describe "$commandname Integration Tests" -Tag "IntegrationTests" { +Describe "Disable-DbaFilestream" -Tag "IntegrationTests" { BeforeAll { $OriginalFileStream = Get-DbaFilestream -SqlInstance $TestConfig.instance1 } + AfterAll { - Set-DbaFilestream -SqlInstance $TestConfig.instance1 -FileStreamLevel $OriginalFileStream.InstanceAccessLevel -force + Set-DbaFilestream -SqlInstance $TestConfig.instance1 -FileStreamLevel $OriginalFileStream.InstanceAccessLevel -Force } - Context "Changing FileStream Level" { - $NewLevel = ($OriginalFileStream.FileStreamStateId + 1) % 3 #Move it on one, but keep it less than 4 with modulo division - $results = Set-DbaFilestream -SqlInstance $TestConfig.instance1 -FileStreamLevel $NewLevel -Force -WarningAction silentlyContinue -ErrorVariable errvar -Erroraction silentlyContinue - It "Should have changed the FileStream Level" { - $results.InstanceAccessLevel | Should be $NewLevel + Context "When changing FileStream Level" { + BeforeAll { + $NewLevel = ($OriginalFileStream.FileStreamStateId + 1) % 3 #Move it on one, but keep it less than 4 with modulo division + $results = Set-DbaFilestream -SqlInstance $TestConfig.instance1 -FileStreamLevel $NewLevel -Force -WarningAction SilentlyContinue -ErrorVariable errvar -ErrorAction SilentlyContinue + } + + It "Should change the FileStream Level" { + $results.InstanceAccessLevel | Should -Be $NewLevel } } } -#> +#> \ No newline at end of file diff --git a/tests/Disable-DbaForceNetworkEncryption.Tests.ps1 b/tests/Disable-DbaForceNetworkEncryption.Tests.ps1 index 14b3172bf2..3ab13c0a2b 100644 --- a/tests/Disable-DbaForceNetworkEncryption.Tests.ps1 +++ b/tests/Disable-DbaForceNetworkEncryption.Tests.ps1 @@ -1,22 +1,42 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'Credential', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe "Disable-DbaForceNetworkEncryption" -Tag "UnitTests" { + Context "Parameter validation" { + BeforeAll { + $command = Get-Command Disable-DbaForceNetworkEncryption + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "Credential", + "EnableException", + "Confirm", + "WhatIf" + ) + } + + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { - $results = Disable-DbaForceNetworkEncryption $TestConfig.instance1 -EnableException +Describe "Disable-DbaForceNetworkEncryption" -Tag "IntegrationTests" { + Context "When disabling force network encryption" { + BeforeAll { + $results = Disable-DbaForceNetworkEncryption -SqlInstance $TestConfig.instance1 -EnableException + } - It "returns false" { - $results.ForceEncryption -eq $false + It "Returns results with ForceEncryption set to false" { + $results.ForceEncryption | Should -BeFalse + } } } diff --git a/tests/Disable-DbaHideInstance.Tests.ps1 b/tests/Disable-DbaHideInstance.Tests.ps1 index 2aa85769dc..6f9c7271ef 100644 --- a/tests/Disable-DbaHideInstance.Tests.ps1 +++ b/tests/Disable-DbaHideInstance.Tests.ps1 @@ -1,22 +1,42 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'SqlInstance', 'Credential', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 +Describe "Disable-DbaHideInstance" -Tag "UnitTests" { + Context "Parameter validation" { + BeforeAll { + $command = Get-Command Disable-DbaHideInstance + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "Credential", + "EnableException", + "Confirm", + "WhatIf" + ) + } + + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { - $results = Disable-DbaHideInstance $TestConfig.instance1 -EnableException +Describe "Disable-DbaHideInstance" -Tag "IntegrationTests" { + Context "When disabling hide instance" { + BeforeAll { + $results = Disable-DbaHideInstance -SqlInstance $TestConfig.instance1 -EnableException + } - It "returns false" { - $results.HideInstance -eq $false + It "Returns result with HideInstance set to false" { + $results.HideInstance | Should -BeFalse + } } } diff --git a/tests/Disable-DbaReplDistributor.Tests.ps1 b/tests/Disable-DbaReplDistributor.Tests.ps1 index a72c49deeb..5fcb683ae5 100644 --- a/tests/Disable-DbaReplDistributor.Tests.ps1 +++ b/tests/Disable-DbaReplDistributor.Tests.ps1 @@ -1,20 +1,37 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) +Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan Add-ReplicationLibrary -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', 'Force', '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 "Disable-DbaReplDistributor" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Disable-DbaReplDistributor + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "Force", + "EnableException", + "Confirm", + "WhatIf" + ) + } + + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } + + # Integration tests for replication are in GitHub Actions and run from \tests\gh-actions-repl-*.ps1 } -<# - Integration tests for replication are in GitHub Actions and run from \tests\gh-actions-repl-*.ps1.ps1 -#> \ No newline at end of file diff --git a/tests/Disable-DbaReplPublishing.Tests.ps1 b/tests/Disable-DbaReplPublishing.Tests.ps1 index d867b82ef1..5f069bc240 100644 --- a/tests/Disable-DbaReplPublishing.Tests.ps1 +++ b/tests/Disable-DbaReplPublishing.Tests.ps1 @@ -1,20 +1,37 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig - +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) Add-ReplicationLibrary -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', 'Force', '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 "Disable-DbaReplPublishing" -Tag "UnitTests" { + Context "Parameter validation" { + BeforeAll { + $command = Get-Command Disable-DbaReplPublishing + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "Force", + "EnableException", + "Confirm", + "WhatIf" + ) + } + + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasParams = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasParams | Should -BeNullOrEmpty } } } + <# Integration tests for replication are in GitHub Actions and run from \tests\gh-actions-repl-*.ps1.ps1 #> diff --git a/tests/Disable-DbaStartupProcedure.Tests.ps1 b/tests/Disable-DbaStartupProcedure.Tests.ps1 index d654d9d562..dfaa7e991a 100644 --- a/tests/Disable-DbaStartupProcedure.Tests.ps1 +++ b/tests/Disable-DbaStartupProcedure.Tests.ps1 @@ -1,20 +1,37 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('WhatIf', 'Confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'StartupProcedure', '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 "Disable-DbaStartupProcedure" -Tag "UnitTests" { + Context "Parameter validation" { + BeforeAll { + $command = Get-Command Disable-DbaStartupProcedure + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "StartupProcedure", + "InputObject", + "EnableException", + "Confirm", + "WhatIf" + ) } + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty + } } } -Describe "$commandname Integration Test" -Tag "IntegrationTests" { +Describe "Disable-DbaStartupProcedure" -Tag "IntegrationTests" { BeforeAll { $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 $random = Get-Random @@ -25,44 +42,87 @@ Describe "$commandname Integration Test" -Tag "IntegrationTests" { $null = $server.Query("CREATE PROCEDURE $startupProc AS Select 1", $dbname) $null = $server.Query("EXEC sp_procoption '$startupProc', 'startup', 'on'", $dbname) } + AfterAll { $null = $server.Query("DROP PROCEDURE $startupProc", $dbname) } - Context "Validate returns correct output for disable" { - $result = Disable-DbaStartupProcedure -SqlInstance $TestConfig.instance2 -StartupProcedure $startupProc -Confirm:$false + Context "When disabling a startup procedure" { + BeforeAll { + $result = Disable-DbaStartupProcedure -SqlInstance $TestConfig.instance2 -StartupProcedure $startupProc -Confirm:$false + } + + It "Should return correct schema" { + $result.Schema | Should -Be "dbo" + } + + It "Should return correct procedure name" { + $result.Name | Should -Be $startupProcName + } + + It "Should show Disable action" { + $result.Action | Should -Be "Disable" + } + + It "Should report success status" { + $result.Status | Should -Be $true + } - It "returns correct results" { - $result.Schema -eq "dbo" | Should Be $true - $result.Name -eq "$startupProcName" | Should Be $true - $result.Action -eq "Disable" | Should Be $true - $result.Status | Should Be $true - $result.Note -eq "Disable succeded" | Should Be $true + It "Should return success note" { + $result.Note | Should -Be "Disable succeded" } } - Context "Validate returns correct output for already existing state" { - $result = Disable-DbaStartupProcedure -SqlInstance $TestConfig.instance2 -StartupProcedure $startupProc -Confirm:$false + Context "When disabling an already disabled procedure" { + BeforeAll { + $result = Disable-DbaStartupProcedure -SqlInstance $TestConfig.instance2 -StartupProcedure $startupProc -Confirm:$false + } + + It "Should return correct schema" { + $result.Schema | Should -Be "dbo" + } - It "returns correct results" { - $result.Schema -eq "dbo" | Should Be $true - $result.Name -eq "$startupProcName" | Should Be $true - $result.Action -eq "Disable" | Should Be $true - $result.Status | Should Be $false - $result.Note -eq "Action Disable already performed" | Should Be $true + It "Should return correct procedure name" { + $result.Name | Should -Be $startupProcName + } + + It "Should show Disable action" { + $result.Action | Should -Be "Disable" + } + + It "Should report unchanged status" { + $result.Status | Should -Be $false + } + + It "Should return already performed note" { + $result.Note | Should -Be "Action Disable already performed" } } - Context "Validate returns correct results for piped input" { - $null = Enable-DbaStartupProcedure -SqlInstance $TestConfig.instance2 -StartupProcedure $startupProc -Confirm:$false - $result = Get-DbaStartupProcedure -SqlInstance $TestConfig.instance2 | Disable-DbaStartupProcedure -Confirm:$false + Context "When using pipeline input" { + BeforeAll { + $null = Enable-DbaStartupProcedure -SqlInstance $TestConfig.instance2 -StartupProcedure $startupProc -Confirm:$false + $result = Get-DbaStartupProcedure -SqlInstance $TestConfig.instance2 | Disable-DbaStartupProcedure -Confirm:$false + } + + It "Should return correct schema" { + $result.Schema | Should -Be "dbo" + } + + It "Should return correct procedure name" { + $result.Name | Should -Be $startupProcName + } + + It "Should show Disable action" { + $result.Action | Should -Be "Disable" + } + + It "Should report success status" { + $result.Status | Should -Be $true + } - It "returns correct results" { - $result.Schema -eq "dbo" | Should Be $true - $result.Name -eq "$startupProcName" | Should Be $true - $result.Action -eq "Disable" | Should Be $true - $result.Status | Should Be $true - $result.Note -eq "Disable succeded" | Should Be $true + It "Should return success note" { + $result.Note | Should -Be "Disable succeded" } } } diff --git a/tests/Disable-DbaTraceFlag.Tests.ps1 b/tests/Disable-DbaTraceFlag.Tests.ps1 index 07c9eb2818..51f3201927 100644 --- a/tests/Disable-DbaTraceFlag.Tests.ps1 +++ b/tests/Disable-DbaTraceFlag.Tests.ps1 @@ -1,40 +1,57 @@ -$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', 'TraceFlag', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + +Describe "Disable-DbaTraceFlag" -Tag "UnitTests" { + Context "Parameter validation" { + BeforeAll { + $command = Get-Command Disable-DbaTraceFlag + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "TraceFlag", + "EnableException" + ) + } + + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasParams = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasParams | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { - Context "Verifying TraceFlag output" { - BeforeAll { - $server = Connect-DbaInstance -SqlInstance $TestConfig.instance1 - $startingtfs = Get-DbaTraceFlag -SqlInstance $server - $safetraceflag = 3226 - - if ($startingtfs.TraceFlag -notcontains $safetraceflag) { - $null = $server.Query("DBCC TRACEON($safetraceflag,-1)") - } +Describe "Disable-DbaTraceFlag" -Tag "IntegrationTests" { + BeforeAll { + $server = Connect-DbaInstance -SqlInstance $TestConfig.instance1 + $startingTraceFlags = Get-DbaTraceFlag -SqlInstance $server + $safeTraceFlag = 3226 + if ($startingTraceFlags.TraceFlag -notcontains $safeTraceFlag) { + $null = $server.Query("DBCC TRACEON($safeTraceFlag,-1)") } - AfterAll { - if ($startingtfs.TraceFlag -contains $safetraceflag) { - $server.Query("DBCC TRACEON($safetraceflag,-1) WITH NO_INFOMSGS") - } + } + + AfterAll { + if ($startingTraceFlags.TraceFlag -contains $safeTraceFlag) { + $server.Query("DBCC TRACEON($safeTraceFlag,-1) WITH NO_INFOMSGS") } + } - $results = Disable-DbaTraceFlag -SqlInstance $server -TraceFlag $safetraceflag + Context "When disabling trace flags" { + BeforeAll { + $results = Disable-DbaTraceFlag -SqlInstance $server -TraceFlag $safeTraceFlag + } - It "Return $safetraceflag as disabled" { - $results.TraceFlag -contains $safetraceflag | Should Be $true + It "Should disable trace flag $safeTraceFlag" { + $results.TraceFlag | Should -Contain $safeTraceFlag } } } diff --git a/tests/Disconnect-DbaInstance.Tests.ps1 b/tests/Disconnect-DbaInstance.Tests.ps1 index d0c6044ed6..08c9c3f903 100644 --- a/tests/Disconnect-DbaInstance.Tests.ps1 +++ b/tests/Disconnect-DbaInstance.Tests.ps1 @@ -1,25 +1,44 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) -Describe "$CommandName Unit Tests" -Tag "UnitTests" { - Context "Validate parameters" { - [array]$params = ([Management.Automation.CommandMetaData]$ExecutionContext.SessionState.InvokeCommand.GetCommand($CommandName, 'Function')).Parameters.Keys - [object[]]$knownParameters = 'InputObject', 'EnableException' +Describe "Disconnect-DbaInstance" -Tag "UnitTests" { + Context "Parameter validation" { + BeforeAll { + $command = Get-Command Disconnect-DbaInstance + $expected = $TestConfig.CommonParameters + $expected += @( + "InputObject", + "EnableException", + "Confirm", + "WhatIf" + ) + } + + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } - It "Should only contain our specific parameters" { - Compare-Object -ReferenceObject $knownParameters -DifferenceObject $params | Should -BeNullOrEmpty + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tag "IntegrationTests" { +Describe "Disconnect-DbaInstance" -Tag "IntegrationTests" { BeforeAll { - $null = Connect-DbaInstance -SqlInstance $TestConfig.instance1 + $null = Connect-DbaInstance -SqlInstance $TestConfig.Instance1 } - Context "disconnets a server" { - It "disconnects and returns some results" { + + Context "When disconnecting a server" { + BeforeAll { $results = Get-DbaConnectedInstance | Disconnect-DbaInstance + } + + It "Returns results" { $results | Should -Not -BeNullOrEmpty } } diff --git a/tests/Dismount-DbaDatabase.Tests.ps1 b/tests/Dismount-DbaDatabase.Tests.ps1 index 2c20751ccf..d2a846425b 100644 --- a/tests/Dismount-DbaDatabase.Tests.ps1 +++ b/tests/Dismount-DbaDatabase.Tests.ps1 @@ -1,100 +1,114 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig - -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'InputObject', 'UpdateStatistics', 'Force', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + +Describe "Dismount-DbaDatabase" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Dismount-DbaDatabase + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "Database", + "InputObject", + "UpdateStatistics", + "Force", + "EnableException", + "Confirm", + "WhatIf" + ) + } + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tag "IntegrationTests" { - - # Setting up the environment we need to test the cmdlet +Describe "Dismount-DbaDatabase" -Tag "IntegrationTests" { BeforeAll { - # Everything in here gets executed before anything else in this context Get-DbaProcess -SqlInstance $TestConfig.instance3 -Program 'dbatools PowerShell module - dbatools.io' | Stop-DbaProcess -WarningAction SilentlyContinue - # Setting up variables names. If you want them to persist between all of the pester blocks, they can be moved outside - $dbname = "dbatoolsci_detachattach" - # making room in the remote case a db with the same name exists - $null = Get-DbaDatabase -SqlInstance $TestConfig.instance3 -Database $dbname | Remove-DbaDatabase -Confirm:$false - - $db1 = New-DbaDatabase -SqlInstance $TestConfig.instance3 -Name $dbname - # memorizing $fileStructure for a later test - $fileStructure = New-Object System.Collections.Specialized.StringCollection + $dbName = "dbatoolsci_detachattach" + $null = Get-DbaDatabase -SqlInstance $TestConfig.instance3 -Database $dbName | Remove-DbaDatabase -Confirm:$false + $database = New-DbaDatabase -SqlInstance $TestConfig.instance3 -Name $dbName - foreach ($file in (Get-DbaDbFile -SqlInstance $TestConfig.instance3 -Database $dbname).PhysicalName) { + $global:fileStructure = New-Object System.Collections.Specialized.StringCollection + foreach ($file in (Get-DbaDbFile -SqlInstance $TestConfig.instance3 -Database $dbName).PhysicalName) { $null = $fileStructure.Add($file) } } - # Everything we create/touch/mess with should be reverted to a "clean" state whenever possible AfterAll { - # this gets executed always (think "finally" in try/catch/finally) and it's the best place for final cleanups - $null = Mount-DbaDatabase -SqlInstance $TestConfig.instance3 -Database $dbname -FileStructure $TestConfig.fileStructure - $null = Get-DbaDatabase -SqlInstance $TestConfig.instance3 -Database $dbname | Remove-DbaDatabase -Confirm:$false + $null = Mount-DbaDatabase -SqlInstance $TestConfig.instance3 -Database $dbName -FileStructure $fileStructure + $null = Get-DbaDatabase -SqlInstance $TestConfig.instance3 -Database $dbName | Remove-DbaDatabase -Confirm:$false } - # Actual tests - Context "Detaches a single database and tests to ensure the alias still exists" { - $results = Dismount-DbaDatabase -SqlInstance $TestConfig.instance3 -Database $dbname -Force - - It "was successfull" { - $results.DetachResult | Should Be "Success" - $results.DatabaseID | Should -Be $db1.ID + Context "When detaching a single database" { + BeforeAll { + $results = Dismount-DbaDatabase -SqlInstance $TestConfig.instance3 -Database $dbName -Force } - It "removed just one database" { - $results.Database | Should Be $dbname + It "Should complete successfully" { + $results.DetachResult | Should -Be "Success" + $results.DatabaseID | Should -Be $database.ID } - It "has the correct properties" { - $ExpectedProps = 'ComputerName,InstanceName,SqlInstance,Database,DatabaseID,DetachResult'.Split(',') - ($results.PsObject.Properties.Name | Sort-Object) | Should Be ($ExpectedProps | Sort-Object) + It "Should remove just one database" { + $results.Database | Should -Be $dbName } } - Context "Database Detachment" { + + Context "When detaching databases with snapshots" { BeforeAll { Get-DbaProcess -SqlInstance $TestConfig.instance3 -Program 'dbatools PowerShell module - dbatools.io' | Stop-DbaProcess -WarningAction SilentlyContinue + $server = Connect-DbaInstance -SqlInstance $TestConfig.instance3 - $db1 = "dbatoolsci_dbsetstate_detached" - $server.Query("CREATE DATABASE $db1") - Get-DbaProcess -SqlInstance $TestConfig.instance3 -Program 'dbatools PowerShell module - dbatools.io' | Stop-DbaProcess -WarningAction SilentlyContinue - $server = Connect-DbaInstance -SqlInstance $TestConfig.instance3 - $db2 = "dbatoolsci_dbsetstate_detached_withSnap" + $dbDetached = "dbatoolsci_dbsetstate_detached" + $dbWithSnapshot = "dbatoolsci_dbsetstate_detached_withSnap" + + $server.Query("CREATE DATABASE $dbDetached") + $server.Query("CREATE DATABASE $dbWithSnapshot") + + $null = New-DbaDbSnapshot -SqlInstance $TestConfig.instance3 -Database $dbWithSnapshot - $server.Query("CREATE DATABASE $db2") - $null = New-DbaDbSnapshot -SqlInstance $TestConfig.instance3 -Database $db2 - $fileStructure = New-Object System.Collections.Specialized.StringCollection - foreach ($file in (Get-DbaDbFile -SqlInstance $TestConfig.instance3 -Database $db1).PhysicalName) { - $null = $fileStructure.Add($file) + $splatFileStructure = New-Object System.Collections.Specialized.StringCollection + foreach ($file in (Get-DbaDbFile -SqlInstance $TestConfig.instance3 -Database $dbDetached).PhysicalName) { + $null = $splatFileStructure.Add($file) } - Stop-DbaProcess -SqlInstance $TestConfig.instance3 -Database $db1 + + Stop-DbaProcess -SqlInstance $TestConfig.instance3 -Database $dbDetached } + AfterAll { - $null = Remove-DbaDbSnapshot -SqlInstance $TestConfig.instance3 -Database $db2 -Force - $null = Mount-DbaDatabase -SqlInstance $TestConfig.instance3 -Database $db1 -FileStructure $fileStructure - $null = Get-DbaDatabase -SqlInstance $TestConfig.instance3 -Database $db1, $db2 | Remove-DbaDatabase -Confirm:$false + $null = Remove-DbaDbSnapshot -SqlInstance $TestConfig.instance3 -Database $dbWithSnapshot -Force + $null = Mount-DbaDatabase -SqlInstance $TestConfig.instance3 -Database $dbDetached -FileStructure $splatFileStructure + $null = Get-DbaDatabase -SqlInstance $TestConfig.instance3 -Database $dbDetached, $dbWithSnapshot | Remove-DbaDatabase -Confirm:$false } - It "Skips detachment if database is snapshotted" { - $result = Dismount-DbaDatabase -SqlInstance $TestConfig.instance3 -Database $db2 -Force -WarningAction SilentlyContinue -WarningVariable warn 3> $null - $result | Should Be $null - $warn -match "snapshot" | Should Be $true - $result = Get-DbaDatabase -SqlInstance $TestConfig.instance3 -Database $db2 - $result | Should Not Be $null + It "Should skip detachment if database has snapshots" { + $result = Dismount-DbaDatabase -SqlInstance $TestConfig.instance3 -Database $dbWithSnapshot -Force -WarningAction SilentlyContinue -WarningVariable warn 3> $null + $result | Should -BeNullOrEmpty + $warn | Should -Match "snapshot" + + $database = Get-DbaDatabase -SqlInstance $TestConfig.instance3 -Database $dbWithSnapshot + $database | Should -Not -BeNullOrEmpty } - $null = Stop-DbaProcess -SqlInstance $TestConfig.instance3 -Database $db1 - $result = Dismount-DbaDatabase -SqlInstance $TestConfig.instance3 -Database $db1 - It "Detaches the database correctly" { - $result = Get-DbaDatabase -SqlInstance $TestConfig.instance3 -Database $db1 - $result | Should Be $null + + It "Should detach database without snapshots" { + # skip for now in appveyor, but when we do troubleshoot, maybe it just needs a sleep + Start-Sleep 3 + $null = Stop-DbaProcess -SqlInstance $TestConfig.instance3 -Database $dbDetached + $null = Dismount-DbaDatabase -SqlInstance $TestConfig.instance3 -Database $dbDetached + $result = Get-DbaDatabase -SqlInstance $TestConfig.instance3 -Database $dbDetached + $result | Should -BeNullOrEmpty } } } diff --git a/tests/Enable-DbaAgHadr.Tests.ps1 b/tests/Enable-DbaAgHadr.Tests.ps1 index b5f0675403..03750a9883 100644 --- a/tests/Enable-DbaAgHadr.Tests.ps1 +++ b/tests/Enable-DbaAgHadr.Tests.ps1 @@ -1,26 +1,53 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) -Describe "$CommandName Unit Tests" -Tag "UnitTests" { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'Credential', 'Force', '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 "Enable-DbaAgHadr" -Tag "UnitTests" { + Context "Parameter validation" { + BeforeAll { + $command = Get-Command Enable-DbaAgHadr + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "Credential", + "Force", + "EnableException", + "Confirm", + "WhatIf" + ) + } + + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tag "IntegrationTests" { +Describe "Enable-DbaAgHadr" -Tag "IntegrationTests" { BeforeAll { + # Ensure HADR is disabled before testing Disable-DbaAgHadr -SqlInstance $TestConfig.instance3 -Confirm:$false -Force } - $results = Enable-DbaAgHadr -SqlInstance $TestConfig.instance3 -Confirm:$false -Force + Context "When enabling HADR" { + BeforeAll { + $results = Enable-DbaAgHadr -SqlInstance $TestConfig.instance3 -Confirm:$false -Force + } - It "enables hadr" { - $results.IsHadrEnabled | Should -Be $true + It "Successfully enables HADR" { + $results.IsHadrEnabled | Should -BeTrue + } + } + + AfterAll { + # Clean up - disable HADR + Disable-DbaAgHadr -SqlInstance $TestConfig.instance3 -Confirm:$false -Force } } diff --git a/tests/Enable-DbaDbEncryption.Tests.ps1 b/tests/Enable-DbaDbEncryption.Tests.ps1 index 009c014f6d..b4ccfd1a46 100644 --- a/tests/Enable-DbaDbEncryption.Tests.ps1 +++ b/tests/Enable-DbaDbEncryption.Tests.ps1 @@ -1,43 +1,67 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig - -Describe "$CommandName Unit Tests" -Tags "UnitTests" { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'InputObject', 'EnableException', 'Force', 'EncryptorName' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + +Describe "Enable-DbaDbEncryption" -Tag "UnitTests" { + Context "Parameter validation" { + BeforeAll { + $command = Get-Command Enable-DbaDbEncryption + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "Database", + "EncryptorName", + "InputObject", + "Force", + "EnableException", + "Confirm", + "WhatIf" + ) + } + + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } - -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { +Describe "Enable-DbaDbEncryption" -Tag "IntegrationTests" { BeforeAll { $PSDefaultParameterValues["*:Confirm"] = $false $passwd = ConvertTo-SecureString "dbatools.IO" -AsPlainText -Force + $masterkey = Get-DbaDbMasterKey -SqlInstance $TestConfig.instance2 -Database master if (-not $masterkey) { - $delmasterkey = $true + $global:delmasterkey = $true $masterkey = New-DbaServiceMasterKey -SqlInstance $TestConfig.instance2 -SecurePassword $passwd } - $mastercert = Get-DbaDbCertificate -SqlInstance $TestConfig.instance2 -Database master | Where-Object Name -notmatch "##" | Select-Object -First 1 + + $mastercert = Get-DbaDbCertificate -SqlInstance $TestConfig.instance2 -Database master | + Where-Object Name -notmatch "##" | + Select-Object -First 1 + if (-not $mastercert) { - $delmastercert = $true + $global:delmastercert = $true $mastercert = New-DbaDbCertificate -SqlInstance $TestConfig.instance2 } - $db = New-DbaDatabase -SqlInstance $TestConfig.instance2 - $db | New-DbaDbMasterKey -SecurePassword $passwd - $db | New-DbaDbCertificate - $db | New-DbaDbEncryptionKey -Force + $global:testDb = New-DbaDatabase -SqlInstance $TestConfig.instance2 + $testDb | New-DbaDbMasterKey -SecurePassword $passwd + $testDb | New-DbaDbCertificate + $testDb | New-DbaDbEncryptionKey -Force } AfterAll { - if ($db) { - $db | Remove-DbaDatabase + if ($testDb) { + $testDb | Remove-DbaDatabase } if ($delmastercert) { $mastercert | Remove-DbaDbCertificate @@ -47,14 +71,20 @@ Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { } } - Context "Command actually works" { - It "should enable encryption on a database with piping" { - $results = $db | Enable-DbaDbEncryption -EncryptorName $mastercert.Name -Force + Context "When enabling encryption via pipeline" { + It "Should enable encryption on a database" { + $results = $testDb | Enable-DbaDbEncryption -EncryptorName $mastercert.Name -Force $results.EncryptionEnabled | Should -Be $true } - It "should enable encryption on a database" { - $null = Disable-DbaDbEncryption -SqlInstance $TestConfig.instance2 -Database $db.Name - $results = Enable-DbaDbEncryption -SqlInstance $TestConfig.instance2 -EncryptorName $mastercert.Name -Database $db.Name -Force + } + + Context "When enabling encryption directly" { + BeforeAll { + $null = Disable-DbaDbEncryption -SqlInstance $TestConfig.instance2 -Database $testDb.Name + } + + It "Should enable encryption on a database" { + $results = Enable-DbaDbEncryption -SqlInstance $TestConfig.instance2 -EncryptorName $mastercert.Name -Database $testDb.Name -Force $results.EncryptionEnabled | Should -Be $true } } diff --git a/tests/Enable-DbaFilestream.Tests.ps1 b/tests/Enable-DbaFilestream.Tests.ps1 index 7b4d52747e..10ecb5574a 100644 --- a/tests/Enable-DbaFilestream.Tests.ps1 +++ b/tests/Enable-DbaFilestream.Tests.ps1 @@ -1,37 +1,59 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Credential', 'FileStreamLevel', 'ShareName', 'Force', '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 "Enable-DbaFilestream" -Tag "UnitTests" { + Context "Parameter validation" { + BeforeAll { + $command = Get-Command Enable-DbaFilestream + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "Credential", + "FileStreamLevel", + "ShareName", + "Force", + "EnableException", + "Confirm", + "WhatIf" + ) + } + + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -<# -Describe "$commandname Integration Tests" -Tag "IntegrationTests" { +Describe "Enable-DbaFilestream" -Tag "IntegrationTests" { BeforeAll { - $OriginalFileStream = Get-DbaFilestream -SqlInstance $TestConfig.instance1 + $global:OriginalFileStream = Get-DbaFilestream -SqlInstance $TestConfig.instance1 } + AfterAll { - if ($OriginalFileStream.InstanceAccessLevel -eq 0) { + if ($global:OriginalFileStream.InstanceAccessLevel -eq 0) { Disable-DbaFilestream -SqlInstance $TestConfig.instance1 -Confirm:$false } else { - Enable-DbaFilestream -SqlInstance $TestConfig.instance1 -FileStreamLevel $OriginalFileStream.InstanceAccessLevel -Confirm:$false + Enable-DbaFilestream -SqlInstance $TestConfig.instance1 -FileStreamLevel $global:OriginalFileStream.InstanceAccessLevel -Confirm:$false } } - Context "Changing FileStream Level" { - $NewLevel = ($OriginalFileStream.FileStreamStateId + 1) % 3 #Move it on one, but keep it less than 4 with modulo division - $results = Enable-DbaFilestream -SqlInstance $TestConfig.instance1 -FileStreamLevel $NewLevel -Confirm:$false - It "Should have changed the FileStream Level" { - $results.InstanceAccessLevel | Should be $NewLevel + Context "When changing FileStream Level" { + BeforeAll { + $NewLevel = ($global:OriginalFileStream.FileStreamStateId + 1) % 3 #Move it on one, but keep it less than 4 with modulo division + $results = Enable-DbaFilestream -SqlInstance $TestConfig.instance1 -FileStreamLevel $NewLevel -Confirm:$false + } + + It "Should change the FileStream Level to the new value" { + $results.InstanceAccessLevel | Should -Be $NewLevel } } } -#> diff --git a/tests/Enable-DbaForceNetworkEncryption.Tests.ps1 b/tests/Enable-DbaForceNetworkEncryption.Tests.ps1 index aa4dd9a6c4..a67b8dd32c 100644 --- a/tests/Enable-DbaForceNetworkEncryption.Tests.ps1 +++ b/tests/Enable-DbaForceNetworkEncryption.Tests.ps1 @@ -1,22 +1,42 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'Credential', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe "Enable-DbaForceNetworkEncryption" -Tag "UnitTests" { + Context "Parameter validation" { + BeforeAll { + $command = Get-Command Enable-DbaForceNetworkEncryption + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "Credential", + "EnableException", + "Confirm", + "WhatIf" + ) + } + + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasParams = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasParams | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { - $results = Enable-DbaForceNetworkEncryption $TestConfig.instance1 -EnableException +Describe "Enable-DbaForceNetworkEncryption" -Tag "IntegrationTests" { + Context "When enabling force network encryption" { + BeforeAll { + $results = Enable-DbaForceNetworkEncryption -SqlInstance $TestConfig.instance1 -EnableException + } - It "returns true" { - $results.ForceEncryption -eq $true + It "Should enable force encryption" { + $results.ForceEncryption | Should -BeTrue + } } } diff --git a/tests/Enable-DbaHideInstance.Tests.ps1 b/tests/Enable-DbaHideInstance.Tests.ps1 index db6cbf16ae..d5f9bac77a 100644 --- a/tests/Enable-DbaHideInstance.Tests.ps1 +++ b/tests/Enable-DbaHideInstance.Tests.ps1 @@ -1,26 +1,46 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'SqlInstance', 'Credential', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 +Describe "Enable-DbaHideInstance" -Tag "UnitTests" { + Context "Parameter validation" { + BeforeAll { + $command = Get-Command Enable-DbaHideInstance + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "Credential", + "EnableException", + "Confirm", + "WhatIf" + ) + } + + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { - AfterAll { - $null = Disable-DbaHideInstance $TestConfig.instance1 +Describe "Enable-DbaHideInstance" -Tag "IntegrationTests" { + BeforeAll { + $instance = $TestConfig.instance1 + $results = Enable-DbaHideInstance -SqlInstance $instance -EnableException } - $results = Enable-DbaHideInstance $TestConfig.instance1 -EnableException + AfterAll { + $null = Disable-DbaHideInstance -SqlInstance $instance + } - It "returns true" { - $results.HideInstance -eq $true + It "Returns an object with HideInstance property set to true" { + $results | Should -Not -BeNullOrEmpty + $results.HideInstance | Should -BeTrue } } diff --git a/tests/Enable-DbaReplDistributor.Tests.ps1 b/tests/Enable-DbaReplDistributor.Tests.ps1 index ecec1f8b34..e9de66c058 100644 --- a/tests/Enable-DbaReplDistributor.Tests.ps1 +++ b/tests/Enable-DbaReplDistributor.Tests.ps1 @@ -1,20 +1,33 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig - +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) Add-ReplicationLibrary -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', 'DistributionDatabase', '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 "Enable-DbaReplDistributor" -Tag "UnitTests" { + Context "Parameter validation" { + BeforeAll { + $command = Get-Command Enable-DbaReplDistributor + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "DistributionDatabase", + "EnableException", + "Confirm", + "WhatIf" + ) + } + + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } -} -<# - Integration tests for replication are in GitHub Actions and run from \tests\gh-actions-repl-*.ps1.ps1 -#> \ No newline at end of file +} \ No newline at end of file diff --git a/tests/Enable-DbaReplPublishing.Tests.ps1 b/tests/Enable-DbaReplPublishing.Tests.ps1 index e0c51d1827..ab45b3a37e 100644 --- a/tests/Enable-DbaReplPublishing.Tests.ps1 +++ b/tests/Enable-DbaReplPublishing.Tests.ps1 @@ -1,20 +1,34 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig - +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) Add-ReplicationLibrary -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', 'SnapshotShare', 'PublisherSqlLogin', '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 "Enable-DbaReplPublishing" -Tag "UnitTests" { + Context "Parameter validation" { + BeforeAll { + $command = Get-Command Enable-DbaReplPublishing + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "SnapshotShare", + "PublisherSqlLogin", + "EnableException", + "Confirm", + "WhatIf" + ) + } + + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } -} -<# - Integration tests for replication are in GitHub Actions and run from \tests\gh-actions-repl-*.ps1.ps1 -#> \ No newline at end of file +} \ No newline at end of file diff --git a/tests/Enable-DbaStartupProcedure.Tests.ps1 b/tests/Enable-DbaStartupProcedure.Tests.ps1 index 59cc961b04..28db6e14ae 100644 --- a/tests/Enable-DbaStartupProcedure.Tests.ps1 +++ b/tests/Enable-DbaStartupProcedure.Tests.ps1 @@ -1,21 +1,38 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('WhatIf', 'Confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'StartupProcedure', '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 "Enable-DbaStartupProcedure" -Tag "UnitTests" { + Context "Parameter validation" { + BeforeAll { + $command = Get-Command Enable-DbaStartupProcedure + $expected = ($TestConfig = Get-TestConfig).CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "StartupProcedure", + "EnableException", + "WhatIf", + "Confirm" + ) } + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasParams = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasParams | Should -BeNullOrEmpty + } } } -Describe "$commandname Integration Test" -Tag "IntegrationTests" { + +Describe "Enable-DbaStartupProcedure" -Tag "IntegrationTests" { BeforeAll { - $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 + $server = Connect-DbaInstance -SqlInstance $TestConfig.Instance2 $random = Get-Random $startupProcName = "StartUpProc$random" $startupProc = "dbo.$startupProcName" @@ -23,47 +40,56 @@ Describe "$commandname Integration Test" -Tag "IntegrationTests" { $null = $server.Query("CREATE PROCEDURE $startupProc AS Select 1", $dbname) } + AfterAll { $null = $server.Query("DROP PROCEDURE $startupProc", $dbname) } - Context "Validate returns correct output for enable" { - $result = Enable-DbaStartupProcedure -SqlInstance $TestConfig.instance2 -StartupProcedure $startupProc -Confirm:$false + Context "When enabling a startup procedure" { + BeforeAll { + $result = Enable-DbaStartupProcedure -SqlInstance $TestConfig.Instance2 -StartupProcedure $startupProc -Confirm:$false + } - It "returns correct results" { - $result.Schema -eq "dbo" | Should Be $true - $result.Name -eq "$startupProcName" | Should Be $true - $result.Action -eq "Enable" | Should Be $true - $result.Status | Should Be $true - $result.Note -eq "Enable succeded" | Should Be $true + It "Should return successful enable results" { + $result.Schema | Should -Be "dbo" + $result.Name | Should -Be $startupProcName + $result.Action | Should -Be "Enable" + $result.Status | Should -Be $true + $result.Note | Should -Be "Enable succeded" } } - Context "Validate returns correct output for already existing state" { - $result = Enable-DbaStartupProcedure -SqlInstance $TestConfig.instance2 -StartupProcedure $startupProc -Confirm:$false + Context "When enabling an already enabled procedure" { + BeforeAll { + $result = Enable-DbaStartupProcedure -SqlInstance $TestConfig.Instance2 -StartupProcedure $startupProc -Confirm:$false + } - It "returns correct results" { - $result.Schema -eq "dbo" | Should Be $true - $result.Name -eq "$startupProcName" | Should Be $true - $result.Action -eq "Enable" | Should Be $true - $result.Status | Should Be $false - $result.Note -eq "Action Enable already performed" | Should Be $true + It "Should return already enabled status" { + $result.Schema | Should -Be "dbo" + $result.Name | Should -Be $startupProcName + $result.Action | Should -Be "Enable" + $result.Status | Should -Be $false + $result.Note | Should -Be "Action Enable already performed" } } - Context "Validate returns correct output for missing procedures" { - $result = Enable-DbaStartupProcedure -SqlInstance $TestConfig.instance2 -StartupProcedure "Unknown.NotHere" -Confirm:$false + Context "When enabling a non-existent procedure" { + BeforeAll { + $result = Enable-DbaStartupProcedure -SqlInstance $TestConfig.Instance2 -StartupProcedure "Unknown.NotHere" -Confirm:$false + } - It "returns correct results" { - $null -eq $result | Should Be $true + It "Should return null" { + $result | Should -BeNull } } - Context "Validate returns correct output for incorrectly formed procedures" { - $result = Enable-DbaStartupProcedure -SqlInstance $TestConfig.instance2 -StartupProcedure "Four.Part.Schema.Name" -Confirm:$false + Context "When using an invalid procedure name format" { + BeforeAll { + $result = Enable-DbaStartupProcedure -SqlInstance $TestConfig.Instance2 -StartupProcedure "Four.Part.Schema.Name" -Confirm:$false + } - It "returns correct results" { - $null -eq $result | Should Be $true + It "Should return null" { + $result | Should -BeNull } } } diff --git a/tests/Enable-DbaTraceFlag.Tests.ps1 b/tests/Enable-DbaTraceFlag.Tests.ps1 index 9b27794711..07e95d32e7 100644 --- a/tests/Enable-DbaTraceFlag.Tests.ps1 +++ b/tests/Enable-DbaTraceFlag.Tests.ps1 @@ -1,39 +1,57 @@ -$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', 'TraceFlag', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + +Describe "Enable-DbaTraceFlag" -Tag "UnitTests" { + Context "Parameter validation" { + BeforeAll { + $command = Get-Command Enable-DbaTraceFlag + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "TraceFlag", + "EnableException" + ) + } + + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasParams = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasParams | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { - Context "Verifying TraceFlag output" { - BeforeAll { - $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 - $startingtfs = Get-DbaTraceFlag -SqlInstance $TestConfig.instance2 - $safetraceflag = 3226 +Describe "Enable-DbaTraceFlag" -Tag "IntegrationTests" { + BeforeAll { + $instance = Connect-DbaInstance -SqlInstance $TestConfig.instance2 + $safeTraceFlag = 3226 + $startingTraceFlags = Get-DbaTraceFlag -SqlInstance $TestConfig.instance2 - if ($startingtfs.TraceFlag -contains $safetraceflag) { - $server.Query("DBCC TRACEOFF($safetraceflag,-1)") - } + if ($startingTraceFlags.TraceFlag -contains $safeTraceFlag) { + $instance.Query("DBCC TRACEOFF($safeTraceFlag,-1)") } - AfterAll { - if ($startingtfs.TraceFlag -notcontains $safetraceflag) { - $server.Query("DBCC TRACEOFF($safetraceflag,-1)") - } + } + + AfterAll { + if ($startingTraceFlags.TraceFlag -notcontains $safeTraceFlag) { + $instance.Query("DBCC TRACEOFF($safeTraceFlag,-1)") } + } - $results = Enable-DbaTraceFlag -SqlInstance $server -TraceFlag $safetraceflag + Context "When enabling a trace flag" { + BeforeAll { + $results = Enable-DbaTraceFlag -SqlInstance $instance -TraceFlag $safeTraceFlag + } - It "Return $safetraceflag as enabled" { - $results.TraceFlag -contains $safetraceflag | Should Be $true + It "Should enable the specified trace flag" { + $results.TraceFlag -contains $safeTraceFlag | Should -BeTrue } } } diff --git a/tests/pester.groups.ps1 b/tests/pester.groups.ps1 index b50102d51b..395802529e 100644 --- a/tests/pester.groups.ps1 +++ b/tests/pester.groups.ps1 @@ -32,6 +32,7 @@ $TestsRunGroups = @{ 'Remove-DbaAvailabilityGroup', 'Remove-DbaDatabaseSafely', 'Sync-DbaLoginPermission', + 'Dismount-DbaDatabase', # tests that fail locally against SQL Server 2022 instances and fail on AppVeyor 'Set-DbaAgentJobStep', 'New-DbaLogin',