diff --git a/tests/Add-DbaAgDatabase.Tests.ps1 b/tests/Add-DbaAgDatabase.Tests.ps1 index 516fff4283c..84215a158a7 100644 --- a/tests/Add-DbaAgDatabase.Tests.ps1 +++ b/tests/Add-DbaAgDatabase.Tests.ps1 @@ -10,10 +10,10 @@ param( $PSDefaultParameterValues = $TestConfig.Defaults ) -Describe $CommandName -Tag "UnitTests" { +Describe $CommandName -Tag UnitTests { Context "Parameter validation" { BeforeAll { - $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $_ -notin ('WhatIf', 'Confirm') } + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } $expectedParameters = $TestConfig.CommonParameters $expectedParameters += @( "SqlInstance", @@ -37,10 +37,10 @@ Describe $CommandName -Tag "UnitTests" { } } -Describe $CommandName -Tag "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. - $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true # For all the backups that we want to clean up after the test, we create a directory that we can delete at the end. # Other files can be written there as well, maybe we change the name of that variable later. But for now we focus on backups. @@ -52,20 +52,21 @@ Describe $CommandName -Tag "IntegrationTests" { # For negative tests, we need a database without a backup and a non existing database. # Set variables. They are available in all the It blocks. - $agName = "addagdb_group" - $existingDbWithBackup = "dbWithBackup" + $agName = "addagdb_group" + $existingDbWithBackup = "dbWithBackup" $existingDbWithoutBackup = "dbWithoutBackup" - $nonexistingDb = "dbdoesnotexist" + $nonexistingDb = "dbdoesnotexist" # Create the objects. - $splat = @{ + $splatAg = @{ Primary = $TestConfig.instance3 Name = $agName ClusterType = "None" FailoverMode = "Manual" Certificate = "dbatoolsci_AGCert" + Confirm = $false } - $null = New-DbaAvailabilityGroup @splat + $null = New-DbaAvailabilityGroup @splatAg $null = New-DbaDatabase -SqlInstance $TestConfig.instance3 -Name $existingDbWithBackup $null = Backup-DbaDatabase -SqlInstance $TestConfig.instance3 -Database $existingDbWithBackup -Path $backupPath @@ -73,12 +74,12 @@ Describe $CommandName -Tag "IntegrationTests" { $null = New-DbaDatabase -SqlInstance $TestConfig.instance3 -Name $existingDbWithoutBackup # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. - $PSDefaultParameterValues.Remove('*-Dba*:EnableException') + $PSDefaultParameterValues.Remove("*-Dba*:EnableException") } AfterAll { # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. - $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true # Cleanup all created object. $null = Remove-DbaAvailabilityGroup -SqlInstance $TestConfig.instance3 -AvailabilityGroup $agName @@ -86,7 +87,7 @@ Describe $CommandName -Tag "IntegrationTests" { $null = Remove-DbaDatabase -SqlInstance $TestConfig.instance3 -Database $existingDbWithBackup, $existingDbWithoutBackup # Remove the backup directory. - Remove-Item -Path $backupPath -Recurse + Remove-Item -Path $backupPath -Recurse -ErrorAction SilentlyContinue # As this is the last block we do not need to reset the $PSDefaultParameterValues. } @@ -95,12 +96,13 @@ Describe $CommandName -Tag "IntegrationTests" { # We use the BeforeAll to run the test itself. # Results are saved in $results. BeforeAll { - $splat = @{ + $splatAddAgDatabase = @{ SqlInstance = $TestConfig.instance3 AvailabilityGroup = $agName Database = $existingDbWithBackup + Confirm = $false } - $results = Add-DbaAgDatabase @splat + $results = Add-DbaAgDatabase @splatAddAgDatabase } # Always include this test to be sure that the command runs without warnings. @@ -123,7 +125,8 @@ Describe $CommandName -Tag "IntegrationTests" { Database = $existingDbWithoutBackup # As we don't want an output, we suppress the warning. # But we can still test the warning because WarningVariable is set globally to WarnVar. - WarningAction = 'SilentlyContinue' + WarningAction = "SilentlyContinue" + Confirm = $false } $results = Add-DbaAgDatabase @splatAddAgDb } @@ -143,7 +146,8 @@ Describe $CommandName -Tag "IntegrationTests" { SqlInstance = $TestConfig.instance3 AvailabilityGroup = $agName Database = $nonexistingDb - WarningAction = 'SilentlyContinue' + WarningAction = "SilentlyContinue" + Confirm = $false } $results = Add-DbaAgDatabase @splatAddAgDb } diff --git a/tests/Add-DbaAgListener.Tests.ps1 b/tests/Add-DbaAgListener.Tests.ps1 index 761431c368d..3d2f9b55ab6 100644 --- a/tests/Add-DbaAgListener.Tests.ps1 +++ b/tests/Add-DbaAgListener.Tests.ps1 @@ -1,14 +1,14 @@ #Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } param( - $ModuleName = "dbatools", - $CommandName = "Add-DbaAgListener", + $ModuleName = "dbatools", + $CommandName = "Add-DbaAgListener", $PSDefaultParameterValues = $TestConfig.Defaults ) -Describe $CommandName -Tag "UnitTests" { +Describe $CommandName -Tag UnitTests { Context "Parameter validation" { BeforeAll { - $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $_ -notin ('WhatIf', 'Confirm') } + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } $expectedParameters = $TestConfig.CommonParameters $expectedParameters += @( "SqlInstance", @@ -32,50 +32,62 @@ Describe $CommandName -Tag "UnitTests" { } } -Describe $CommandName -Tag "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { - $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true + # For all the backups that we want to clean up after the test, we create a directory that we can delete at the end. + # Other files can be written there as well, maybe we change the name of that variable later. But for now we focus on backups. $backupPath = "$($TestConfig.Temp)\$CommandName-$(Get-Random)" $null = New-Item -Path $backupPath -ItemType Directory + # Explain what needs to be set up for the test: # To add a listener to an availablity group, we need an availability group, an ip address and a port. # TODO: Add some negative tests. - $agName = "addagdb_group" + # Set variables. They are available in all the It blocks. + $agName = "addagdb_group" $listenerName = "listener" - $listenerIp = "127.0.20.1" + $listenerIp = "127.0.20.1" $listenerPort = 14330 - $splat = @{ + # Create the objects. + $splatAg = @{ Primary = $TestConfig.instance3 Name = $agName ClusterType = "None" FailoverMode = "Manual" Certificate = "dbatoolsci_AGCert" } - $ag = New-DbaAvailabilityGroup @splat + $ag = New-DbaAvailabilityGroup @splatAg - $PSDefaultParameterValues.Remove('*-Dba*:EnableException') + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove("*-Dba*:EnableException") } AfterAll { - $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true + # Cleanup all created objects. $null = Remove-DbaAvailabilityGroup -SqlInstance $TestConfig.instance3 -AvailabilityGroup $agName $null = Get-DbaEndpoint -SqlInstance $TestConfig.instance3 -Type DatabaseMirroring | Remove-DbaEndpoint - Remove-Item -Path $backupPath -Recurse + # Remove the backup directory. + Remove-Item -Path $backupPath -Recurse -ErrorAction SilentlyContinue + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } Context "When creating a listener" { BeforeAll { - $splat = @{ + $splatListener = @{ Name = $listenerName IPAddress = $listenerIp Port = $listenerPort } - $results = $ag | Add-DbaAgListener @splat + $results = $ag | Add-DbaAgListener @splatListener } It "Does not warn" { @@ -86,4 +98,4 @@ Describe $CommandName -Tag "IntegrationTests" { $results.PortNumber | Should -Be $listenerPort } } -} #$TestConfig.instance2 for appveyor +} #$TestConfig.instance2 for appveyor \ No newline at end of file diff --git a/tests/Add-DbaAgReplica.Tests.ps1 b/tests/Add-DbaAgReplica.Tests.ps1 index a8170d77342..3f1ad5e67c3 100644 --- a/tests/Add-DbaAgReplica.Tests.ps1 +++ b/tests/Add-DbaAgReplica.Tests.ps1 @@ -1,14 +1,14 @@ #Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } param( - $ModuleName = "dbatools", - $CommandName = [System.IO.Path]::GetFileName($PSCommandPath.Replace('.Tests.ps1', '')), + $ModuleName = "dbatools", + $CommandName = "Add-DbaAgReplica", $PSDefaultParameterValues = $TestConfig.Defaults ) -Describe $CommandName -Tag "UnitTests" { +Describe $CommandName -Tag UnitTests { Context "Parameter validation" { BeforeAll { - $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $_ -notin ('WhatIf', 'Confirm') } + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } $expectedParameters = $TestConfig.CommonParameters $expectedParameters += @( "SqlInstance", @@ -40,33 +40,49 @@ Describe $CommandName -Tag "UnitTests" { } } -Describe $CommandName -Tag "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { - $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true + # Explain what needs to be set up for the test: + # To add an availability group replica, we need an availability group to work with. + + # Set variables. They are available in all the It blocks. $primaryAgName = "dbatoolsci_agroup" - $splat = @{ + + # Create the objects. + $splatPrimary = @{ Primary = $TestConfig.instance3 Name = $primaryAgName ClusterType = "None" FailoverMode = "Manual" Certificate = "dbatoolsci_AGCert" + Confirm = $false } - $primaryAg = New-DbaAvailabilityGroup @splat + $primaryAg = New-DbaAvailabilityGroup @splatPrimary $replicaName = $primaryAg.PrimaryReplica - $PSDefaultParameterValues.Remove('*-Dba*:EnableException') + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove("*-Dba*:EnableException") } AfterAll { - $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true + + # Cleanup all created objects. + $null = Remove-DbaAvailabilityGroup -SqlInstance $TestConfig.instance3 -AvailabilityGroup $primaryAgName -Confirm:$false -ErrorAction SilentlyContinue + $null = Get-DbaEndpoint -SqlInstance $TestConfig.instance3 -Type DatabaseMirroring | Remove-DbaEndpoint -Confirm:$false -ErrorAction SilentlyContinue - $null = Remove-DbaAvailabilityGroup -SqlInstance $TestConfig.instance3 -AvailabilityGroup $primaryAgName - $null = Get-DbaEndpoint -SqlInstance $TestConfig.instance3 -Type DatabaseMirroring | Remove-DbaEndpoint + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } Context "When adding AG replicas" { BeforeAll { + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true + $replicaAgName = "dbatoolsci_add_replicagroup" $splatRepAg = @{ Primary = $TestConfig.instance3 @@ -74,28 +90,36 @@ Describe $CommandName -Tag "IntegrationTests" { ClusterType = "None" FailoverMode = "Manual" Certificate = "dbatoolsci_AGCert" + Confirm = $false } $replicaAg = New-DbaAvailabilityGroup @splatRepAg + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove("*-Dba*:EnableException") } AfterAll { - $null = Remove-DbaAvailabilityGroup -SqlInstance $TestConfig.instance3 -AvailabilityGroup $replicaAgName + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true + + # Cleanup all created objects. + $null = Remove-DbaAvailabilityGroup -SqlInstance $TestConfig.instance3 -AvailabilityGroup $replicaAgName -Confirm:$false -ErrorAction SilentlyContinue } It "Returns results with proper data" { $results = Get-DbaAgReplica -SqlInstance $TestConfig.instance3 $results.AvailabilityGroup | Should -Contain $replicaAgName - $results.Role | Should -Contain 'Primary' - $results.AvailabilityMode | Should -Contain 'SynchronousCommit' - $results.FailoverMode | Should -Contain 'Manual' + $results.Role | Should -Contain "Primary" + $results.AvailabilityMode | Should -Contain "SynchronousCommit" + $results.FailoverMode | Should -Contain "Manual" } It "Returns just one result for a specific replica" { $results = Get-DbaAgReplica -SqlInstance $TestConfig.instance3 -Replica $replicaName -AvailabilityGroup $replicaAgName $results.AvailabilityGroup | Should -Be $replicaAgName - $results.Role | Should -Be 'Primary' - $results.AvailabilityMode | Should -Be 'SynchronousCommit' - $results.FailoverMode | Should -Be 'Manual' + $results.Role | Should -Be "Primary" + $results.AvailabilityMode | Should -Be "SynchronousCommit" + $results.FailoverMode | Should -Be "Manual" } } -} #$TestConfig.instance2 for appveyor +} #$TestConfig.instance2 for appveyor \ No newline at end of file diff --git a/tests/Add-DbaComputerCertificate.Tests.ps1 b/tests/Add-DbaComputerCertificate.Tests.ps1 index 74774c53743..23ff7181dd7 100644 --- a/tests/Add-DbaComputerCertificate.Tests.ps1 +++ b/tests/Add-DbaComputerCertificate.Tests.ps1 @@ -1,14 +1,14 @@ #Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } param( - $ModuleName = "dbatools", - $CommandName = [System.IO.Path]::GetFileName($PSCommandPath.Replace('.Tests.ps1', '')), + $ModuleName = "dbatools", + $CommandName = "Add-DbaComputerCertificate", $PSDefaultParameterValues = $TestConfig.Defaults ) -Describe $CommandName -Tag "UnitTests" { +Describe $CommandName -Tag UnitTests { Context "Parameter validation" { BeforeAll { - $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $_ -notin ('WhatIf', 'Confirm') } + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } $expectedParameters = $TestConfig.CommonParameters $expectedParameters += @( "ComputerName", @@ -29,16 +29,25 @@ Describe $CommandName -Tag "UnitTests" { } } -Describe $CommandName -Tag "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { + BeforeAll { + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true + + $certPath = "$($TestConfig.AppveyorLabRepo)\certificates\localhost.crt" + $certThumbprint = "29C469578D6C6211076A09CEE5C5797EEA0C2713" + } + + AfterAll { + $PSDefaultParameterValues.Remove("*-Dba*:EnableException") + } + Context "Certificate is added properly" { BeforeAll { - $certPath = "$($TestConfig.appveyorlabrepo)\certificates\localhost.crt" - $certThumbprint = "29C469578D6C6211076A09CEE5C5797EEA0C2713" $results = Add-DbaComputerCertificate -Path $certPath } AfterAll { - Remove-DbaComputerCertificate -Thumbprint $certThumbprint + Remove-DbaComputerCertificate -Thumbprint $certThumbprint -ErrorAction SilentlyContinue } It "Should show the proper thumbprint has been added" { @@ -49,4 +58,4 @@ Describe $CommandName -Tag "IntegrationTests" { $results.PSParentPath | Should -Be "Microsoft.PowerShell.Security\Certificate::LocalMachine\My" } } -} +} \ No newline at end of file diff --git a/tests/Add-DbaDbMirrorMonitor.Tests.ps1 b/tests/Add-DbaDbMirrorMonitor.Tests.ps1 index 5da763090f4..0684b3b9de5 100644 --- a/tests/Add-DbaDbMirrorMonitor.Tests.ps1 +++ b/tests/Add-DbaDbMirrorMonitor.Tests.ps1 @@ -1,14 +1,14 @@ #Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } param( - $ModuleName = "dbatools", - $CommandName = [System.IO.Path]::GetFileName($PSCommandPath.Replace('.Tests.ps1', '')), + $ModuleName = "dbatools", + $CommandName = "Add-DbaDbMirrorMonitor", $PSDefaultParameterValues = $TestConfig.Defaults ) -Describe $CommandName -Tag "UnitTests" { +Describe $CommandName -Tag UnitTests { Context "Parameter validation" { BeforeAll { - $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $_ -notin ('WhatIf', 'Confirm') } + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } $expectedParameters = $TestConfig.CommonParameters $expectedParameters += @( "SqlInstance", @@ -23,7 +23,7 @@ Describe $CommandName -Tag "UnitTests" { } } -Describe $CommandName -Tag "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { Context "When adding mirror monitor" { BeforeAll { $results = Add-DbaDbMirrorMonitor -SqlInstance $TestConfig.instance2 @@ -34,7 +34,7 @@ Describe $CommandName -Tag "IntegrationTests" { } It "Adds the mirror monitor" { - $results.MonitorStatus | Should -Be 'Added' + $results.MonitorStatus | Should -Be "Added" } } -} +} \ No newline at end of file diff --git a/tests/Add-DbaDbRoleMember.Tests.ps1 b/tests/Add-DbaDbRoleMember.Tests.ps1 index 842be2844a5..2a042c1e879 100644 --- a/tests/Add-DbaDbRoleMember.Tests.ps1 +++ b/tests/Add-DbaDbRoleMember.Tests.ps1 @@ -1,14 +1,14 @@ #Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } param( - $ModuleName = "dbatools", - $CommandName = [System.IO.Path]::GetFileName($PSCommandPath.Replace('.Tests.ps1', '')), + $ModuleName = "dbatools", + $CommandName = "Add-DbaDbRoleMember", $PSDefaultParameterValues = $TestConfig.Defaults ) -Describe "Add-DbaDbRoleMember" -Tag "UnitTests" { +Describe $CommandName -Tag UnitTests { Context "Parameter validation" { BeforeAll { - $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $_ -notin ('WhatIf', 'Confirm') } + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } $expectedParameters = $TestConfig.CommonParameters $expectedParameters += @( "SqlInstance", @@ -27,41 +27,93 @@ Describe "Add-DbaDbRoleMember" -Tag "UnitTests" { } } -Describe "Add-DbaDbRoleMember" -Tag "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { - $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 $user1 = "dbatoolssci_user1_$(Get-Random)" $user2 = "dbatoolssci_user2_$(Get-Random)" $role = "dbatoolssci_role_$(Get-Random)" - $null = New-DbaLogin -SqlInstance $TestConfig.instance2 -Login $user1 -Password ('Password1234!' | ConvertTo-SecureString -asPlainText -Force) - $null = New-DbaLogin -SqlInstance $TestConfig.instance2 -Login $user2 -Password ('Password1234!' | ConvertTo-SecureString -asPlainText -Force) + $splatLoginUser1 = @{ + SqlInstance = $TestConfig.instance2 + Login = $user1 + Password = ("Password1234!" | ConvertTo-SecureString -asPlainText -Force) + } + $null = New-DbaLogin @splatLoginUser1 + $splatLoginUser2 = @{ + SqlInstance = $TestConfig.instance2 + Login = $user2 + Password = ("Password1234!" | ConvertTo-SecureString -asPlainText -Force) + } + $null = New-DbaLogin @splatLoginUser2 $dbname = "dbatoolsci_$(Get-Random)" $null = New-DbaDatabase -SqlInstance $TestConfig.instance2 -Name $dbname -Owner sa - $null = New-DbaDbUser -SqlInstance $TestConfig.instance2 -Database $dbname -Login $user1 -Username $user1 - $null = New-DbaDbUser -SqlInstance $TestConfig.instance2 -Database $dbname -Login $user2 -Username $user2 - $null = New-DbaDbUser -SqlInstance $TestConfig.instance2 -Database msdb -Login $user1 -Username $user1 -IncludeSystem - $null = New-DbaDbUser -SqlInstance $TestConfig.instance2 -Database msdb -Login $user2 -Username $user2 -IncludeSystem + $splatDbUser1 = @{ + SqlInstance = $TestConfig.instance2 + Database = $dbname + Login = $user1 + Username = $user1 + } + $null = New-DbaDbUser @splatDbUser1 + $splatDbUser2 = @{ + SqlInstance = $TestConfig.instance2 + Database = $dbname + Login = $user2 + Username = $user2 + } + $null = New-DbaDbUser @splatDbUser2 + $splatDbUser1Msdb = @{ + SqlInstance = $TestConfig.instance2 + Database = "msdb" + Login = $user1 + Username = $user1 + IncludeSystem = $true + } + $null = New-DbaDbUser @splatDbUser1Msdb + $splatDbUser2Msdb = @{ + SqlInstance = $TestConfig.instance2 + Database = "msdb" + Login = $user2 + Username = $user2 + IncludeSystem = $true + } + $null = New-DbaDbUser @splatDbUser2Msdb $null = $server.Query("CREATE ROLE $role", $dbname) - $PSDefaultParameterValues.Remove('*-Dba*:EnableException') + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove("*-Dba*:EnableException") } AfterAll { - $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 - $null = $server.Query("DROP USER $user1", 'msdb') - $null = $server.Query("DROP USER $user2", 'msdb') - $null = Remove-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname - $null = Remove-DbaLogin -SqlInstance $TestConfig.instance2 -Login $user1, $user2 + $null = $server.Query("DROP USER $user1", "msdb") + $null = $server.Query("DROP USER $user2", "msdb") + $null = Remove-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname -Confirm:$false + $null = Remove-DbaLogin -SqlInstance $TestConfig.instance2 -Login $user1, $user2 -Confirm:$false + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } Context "When adding a user to a role" { BeforeAll { - $result = Add-DbaDbRoleMember -SqlInstance $TestConfig.instance2 -Role $role -Member $user1 -Database $dbname - $roleDBAfter = Get-DbaDbRoleMember -SqlInstance $server -Database $dbname -Role $role + $splatAddRoleMember = @{ + SqlInstance = $TestConfig.instance2 + Role = $role + Member = $user1 + Database = $dbname + } + $result = Add-DbaDbRoleMember @splatAddRoleMember + $splatGetRoleMember = @{ + SqlInstance = $server + Database = $dbname + Role = $role + } + $roleDBAfter = Get-DbaDbRoleMember @splatGetRoleMember } It "Adds the user to the role" { @@ -73,9 +125,25 @@ Describe "Add-DbaDbRoleMember" -Tag "IntegrationTests" { Context "When adding a user to multiple roles" { BeforeAll { - $roleDB = Get-DbaDbRoleMember -SqlInstance $server -Database msdb -Role db_datareader, SQLAgentReaderRole - $result = Add-DbaDbRoleMember -SqlInstance $TestConfig.instance2 -Role db_datareader, SQLAgentReaderRole -Member $user1 -Database msdb - $roleDBAfter = Get-DbaDbRoleMember -SqlInstance $server -Database msdb -Role db_datareader, SQLAgentReaderRole + $splatGetRoleMemberBefore = @{ + SqlInstance = $server + Database = "msdb" + Role = @("db_datareader", "SQLAgentReaderRole") + } + $roleDB = Get-DbaDbRoleMember @splatGetRoleMemberBefore + $splatAddMultipleRoles = @{ + SqlInstance = $TestConfig.instance2 + Role = @("db_datareader", "SQLAgentReaderRole") + Member = $user1 + Database = "msdb" + } + $result = Add-DbaDbRoleMember @splatAddMultipleRoles + $splatGetRoleMemberAfter = @{ + SqlInstance = $server + Database = "msdb" + Role = @("db_datareader", "SQLAgentReaderRole") + } + $roleDBAfter = Get-DbaDbRoleMember @splatGetRoleMemberAfter } It "Adds the user to multiple roles" { @@ -87,10 +155,25 @@ Describe "Add-DbaDbRoleMember" -Tag "IntegrationTests" { Context "When adding a user to roles via piped input from Get-DbaDbRole" { BeforeAll { - $roleInput = Get-DbaDbRole -SqlInstance $server -Database msdb -Role db_datareader, SQLAgentReaderRole - $roleDB = Get-DbaDbRoleMember -SqlInstance $server -Database msdb -Role db_datareader, SQLAgentReaderRole + $splatGetDbRole = @{ + SqlInstance = $server + Database = "msdb" + Role = @("db_datareader", "SQLAgentReaderRole") + } + $roleInput = Get-DbaDbRole @splatGetDbRole + $splatGetRoleMemberPipe = @{ + SqlInstance = $server + Database = "msdb" + Role = @("db_datareader", "SQLAgentReaderRole") + } + $roleDB = Get-DbaDbRoleMember @splatGetRoleMemberPipe $result = $roleInput | Add-DbaDbRoleMember -User $user2 - $roleDBAfter = Get-DbaDbRoleMember -SqlInstance $server -Database msdb -Role db_datareader, SQLAgentReaderRole + $splatGetRoleMemberPipeAfter = @{ + SqlInstance = $server + Database = "msdb" + Role = @("db_datareader", "SQLAgentReaderRole") + } + $roleDBAfter = Get-DbaDbRoleMember @splatGetRoleMemberPipeAfter } It "Adds the user to roles via piped input" { @@ -101,23 +184,40 @@ Describe "Add-DbaDbRoleMember" -Tag "IntegrationTests" { Context "When adding a user to a role they are already a member of" { BeforeAll { - $messages = Add-DbaDbRoleMember -SqlInstance $TestConfig.instance2 -Role $role -Member $user1 -Database $dbname + $splatAddExistingMember = @{ + SqlInstance = $TestConfig.instance2 + Role = $role + Member = $user1 + Database = $dbname + } + $messages = Add-DbaDbRoleMember @splatAddExistingMember } It "Skips adding the user and outputs appropriate message" { - $messageCount = ($messages -match 'Adding user').Count + $messageCount = ($messages -match "Adding user").Count $messageCount | Should -Be 0 } } Context "When adding a role to another role" { BeforeAll { - $result = Add-DbaDbRoleMember -SqlInstance $TestConfig.instance2 -Role db_datawriter -Member $role -Database $dbname - $roleDBAfter = Get-DbaDbRoleMember -SqlInstance $server -Database $dbname -Role db_datawriter + $splatAddRoleToRole = @{ + SqlInstance = $TestConfig.instance2 + Role = "db_datawriter" + Member = $role + Database = $dbname + } + $result = Add-DbaDbRoleMember @splatAddRoleToRole + $splatGetRoleToRole = @{ + SqlInstance = $server + Database = $dbname + Role = "db_datawriter" + } + $roleDBAfter = Get-DbaDbRoleMember @splatGetRoleToRole } It "Adds the role to another role" { $roleDBAfter.MemberRole | Should -Contain $role } } -} +} \ No newline at end of file diff --git a/tests/Add-DbaExtendedProperty.Tests.ps1 b/tests/Add-DbaExtendedProperty.Tests.ps1 index e665b36172b..3c27180c4d8 100644 --- a/tests/Add-DbaExtendedProperty.Tests.ps1 +++ b/tests/Add-DbaExtendedProperty.Tests.ps1 @@ -1,14 +1,14 @@ #Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } param( - $ModuleName = "dbatools", - $CommandName = [System.IO.Path]::GetFileName($PSCommandPath.Replace('.Tests.ps1', '')), + $ModuleName = "dbatools", + $CommandName = "Add-DbaExtendedProperty", $PSDefaultParameterValues = $TestConfig.Defaults ) -Describe "Add-DbaExtendedProperty" -Tag "UnitTests" { +Describe $CommandName -Tag UnitTests { Context "Parameter validation" { BeforeAll { - $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $_ -notin ('WhatIf', 'Confirm') } + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } $expectedParameters = $TestConfig.CommonParameters $expectedParameters += @( "SqlInstance", @@ -27,17 +27,34 @@ Describe "Add-DbaExtendedProperty" -Tag "UnitTests" { } } -Describe "Add-DbaExtendedProperty" -Tag "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # Create unique database name for this test run $random = Get-Random + $newDbName = "dbatoolsci_newdb_$random" + + # Connect to instance and clean up any existing connections $server2 = Connect-DbaInstance -SqlInstance $TestConfig.instance2 $null = Get-DbaProcess -SqlInstance $server2 | Where-Object Program -match dbatools | Stop-DbaProcess -Confirm:$false -WarningAction SilentlyContinue - $newDbName = "dbatoolsci_newdb_$random" + + # Create test database $db = New-DbaDatabase -SqlInstance $server2 -Name $newDbName + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } AfterAll { + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # Cleanup the test database $null = $db | Remove-DbaDatabase -Confirm:$false + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } Context "When adding extended properties" { @@ -52,4 +69,4 @@ Describe "Add-DbaExtendedProperty" -Tag "IntegrationTests" { $ep.Value | Should -Be "Sup" } } -} +} \ No newline at end of file diff --git a/tests/Add-DbaPfDataCollectorCounter.Tests.ps1 b/tests/Add-DbaPfDataCollectorCounter.Tests.ps1 index 6b8d922a511..635493218d6 100644 --- a/tests/Add-DbaPfDataCollectorCounter.Tests.ps1 +++ b/tests/Add-DbaPfDataCollectorCounter.Tests.ps1 @@ -1,14 +1,14 @@ #Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } param( - $ModuleName = "dbatools", - $CommandName = [System.IO.Path]::GetFileName($PSCommandPath.Replace('.Tests.ps1', '')), + $ModuleName = "dbatools", + $CommandName = "Add-DbaPfDataCollectorCounter", $PSDefaultParameterValues = $TestConfig.Defaults ) -Describe "Add-DbaPfDataCollectorCounter" -Tag "UnitTests" { +Describe $CommandName -Tag UnitTests { Context "Parameter validation" { BeforeAll { - $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $_ -notin ('WhatIf', 'Confirm') } + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } $expectedParameters = $TestConfig.CommonParameters $expectedParameters += @( "ComputerName", @@ -27,34 +27,38 @@ Describe "Add-DbaPfDataCollectorCounter" -Tag "UnitTests" { } } -Describe "Add-DbaPfDataCollectorCounter" -Tag "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { - $PSDefaultParameterValues['*:Confirm'] = $false + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true } - BeforeEach { - $null = Get-DbaPfDataCollectorSetTemplate -Template 'Long Running Queries' | - Import-DbaPfDataCollectorSetTemplate | - Get-DbaPfDataCollector | - Get-DbaPfDataCollectorCounter -Counter '\LogicalDisk(*)\Avg. Disk Queue Length' | - Remove-DbaPfDataCollectorCounter + AfterAll { + $PSDefaultParameterValues.Remove("*-Dba*:EnableException") + } + + Context "When adding a counter to a data collector" { + BeforeAll { + $null = Get-DbaPfDataCollectorSetTemplate -Template "Long Running Queries" | + Import-DbaPfDataCollectorSetTemplate | + Get-DbaPfDataCollector | + Get-DbaPfDataCollectorCounter -Counter "\LogicalDisk(*)\Avg. Disk Queue Length" | + Remove-DbaPfDataCollectorCounter - $results = Get-DbaPfDataCollectorSet -CollectorSet 'Long Running Queries' | Get-DbaPfDataCollector | - Add-DbaPfDataCollectorCounter -Counter '\LogicalDisk(*)\Avg. Disk Queue Length' + $results = Get-DbaPfDataCollectorSet -CollectorSet "Long Running Queries" | Get-DbaPfDataCollector | + Add-DbaPfDataCollectorCounter -Counter "\LogicalDisk(*)\Avg. Disk Queue Length" } AfterAll { - $null = Get-DbaPfDataCollectorSet -CollectorSet 'Long Running Queries' | - Remove-DbaPfDataCollectorSet + $null = Get-DbaPfDataCollectorSet -CollectorSet "Long Running Queries" | + Remove-DbaPfDataCollectorSet -ErrorAction SilentlyContinue } - Context "When adding a counter to a data collector" { - It "Returns the correct DataCollectorSet" { - $results.DataCollectorSet | Should -Be 'Long Running Queries' - } + It "Returns the correct DataCollectorSet" { + $results.DataCollectorSet | Should -Be "Long Running Queries" + } - It "Returns the correct counter name" { - $results.Name | Should -Be '\LogicalDisk(*)\Avg. Disk Queue Length' - } + It "Returns the correct counter name" { + $results.Name | Should -Be "\LogicalDisk(*)\Avg. Disk Queue Length" } } +} \ No newline at end of file diff --git a/tests/Add-DbaRegServer.Tests.ps1 b/tests/Add-DbaRegServer.Tests.ps1 index 7a24bf9d9bc..470e0ebbaa4 100644 --- a/tests/Add-DbaRegServer.Tests.ps1 +++ b/tests/Add-DbaRegServer.Tests.ps1 @@ -1,14 +1,14 @@ #Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } param( - $ModuleName = "dbatools", - $CommandName = [System.IO.Path]::GetFileName($PSCommandPath.Replace('.Tests.ps1', '')), + $ModuleName = "dbatools", + $CommandName = "Add-DbaRegServer", $PSDefaultParameterValues = $TestConfig.Defaults ) -Describe "Add-DbaRegServer" -Tag "UnitTests" { +Describe $CommandName -Tag UnitTests { Context "Parameter validation" { BeforeAll { - $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $_ -notin ('WhatIf', 'Confirm') } + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } $expectedParameters = $TestConfig.CommonParameters $expectedParameters += @( "SqlInstance", @@ -33,18 +33,29 @@ Describe "Add-DbaRegServer" -Tag "UnitTests" { } } -Describe "Add-DbaRegServer" -Tag "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + $srvName = "dbatoolsci-server1" $group = "dbatoolsci-group1" $regSrvName = "dbatoolsci-server12" $regSrvDesc = "dbatoolsci-server123" $groupobject = Add-DbaRegServerGroup -SqlInstance $TestConfig.instance1 -Name $group + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } AfterAll { + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + Get-DbaRegServer -SqlInstance $TestConfig.instance1, $TestConfig.instance2 | Where-Object Name -match dbatoolsci | Remove-DbaRegServer -Confirm:$false Get-DbaRegServerGroup -SqlInstance $TestConfig.instance1, $TestConfig.instance2 | Where-Object Name -match dbatoolsci | Remove-DbaRegServerGroup -Confirm:$false + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } Context "When adding a registered server" { @@ -67,7 +78,7 @@ Describe "Add-DbaRegServer" -Tag "IntegrationTests" { Context "When adding a registered server with extended properties" { BeforeAll { - $splat = @{ + $splatRegServer = @{ SqlInstance = $TestConfig.instance1 ServerName = $regSrvName Name = $srvName @@ -75,7 +86,7 @@ Describe "Add-DbaRegServer" -Tag "IntegrationTests" { Description = $regSrvDesc } - $results2 = Add-DbaRegServer @splat + $results2 = Add-DbaRegServer @splatRegServer } It "Adds a registered server with correct server name" { @@ -94,4 +105,4 @@ Describe "Add-DbaRegServer" -Tag "IntegrationTests" { $results2.SqlInstance | Should -Not -BeNullOrEmpty } } -} +} \ No newline at end of file diff --git a/tests/Add-DbaRegServerGroup.Tests.ps1 b/tests/Add-DbaRegServerGroup.Tests.ps1 index 0d1402a24b7..fdf27ebcda6 100644 --- a/tests/Add-DbaRegServerGroup.Tests.ps1 +++ b/tests/Add-DbaRegServerGroup.Tests.ps1 @@ -1,14 +1,14 @@ #Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } param( - $ModuleName = "dbatools", - $CommandName = [System.IO.Path]::GetFileName($PSCommandPath.Replace('.Tests.ps1', '')), + $ModuleName = "dbatools", + $CommandName = "Add-DbaRegServerGroup", $PSDefaultParameterValues = $TestConfig.Defaults ) -Describe "Add-DbaRegServerGroup" -Tag "UnitTests" { +Describe $CommandName -Tag UnitTests { Context "Parameter validation" { BeforeAll { - $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $_ -notin ('WhatIf', 'Confirm') } + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } $expectedParameters = $TestConfig.CommonParameters $expectedParameters += @( "SqlInstance", @@ -27,26 +27,49 @@ Describe "Add-DbaRegServerGroup" -Tag "UnitTests" { } } -Describe "Add-DbaRegServerGroup" -Tag "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { - $group = "dbatoolsci-group1" - $group2 = "dbatoolsci-group2" - $description = "group description" + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # Set variables. They are available in all the It blocks. + $group = "dbatoolsci-group1" + $group2 = "dbatoolsci-group2" + $description = "group description" $descriptionUpdated = "group description updated" + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } + AfterAll { + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # Cleanup all created objects. Get-DbaRegServerGroup -SqlInstance $TestConfig.instance1 | Where-Object Name -match dbatoolsci | Remove-DbaRegServerGroup -Confirm:$false + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } Context "When adding a registered server group" { It "adds a registered server group" { - $results = Add-DbaRegServerGroup -SqlInstance $TestConfig.instance1 -Name $group + $splatAddGroup = @{ + SqlInstance = $TestConfig.instance1 + Name = $group + } + $results = Add-DbaRegServerGroup @splatAddGroup $results.Name | Should -Be $group $results.SqlInstance | Should -Not -BeNullOrEmpty } It "adds a registered server group with extended properties" { - $results = Add-DbaRegServerGroup -SqlInstance $TestConfig.instance1 -Name $group2 -Description $description + $splatAddGroupExtended = @{ + SqlInstance = $TestConfig.instance1 + Name = $group2 + Description = $description + } + $results = Add-DbaRegServerGroup @splatAddGroupExtended $results.Name | Should -Be $group2 $results.Description | Should -Be $description $results.SqlInstance | Should -Not -BeNullOrEmpty @@ -60,22 +83,32 @@ Describe "Add-DbaRegServerGroup" -Tag "IntegrationTests" { Add-DbaRegServerGroup -Name dbatoolsci-second | Add-DbaRegServerGroup -Name dbatoolsci-third | Add-DbaRegServer -ServerName dbatoolsci-test -Description ridiculous - $results.Group | Should -Be 'dbatoolsci-first\dbatoolsci-second\dbatoolsci-third' + $results.Group | Should -Be "dbatoolsci-first\dbatoolsci-second\dbatoolsci-third" } } Context "When adding nested groups" { It "adds a registered server group and sub-group when not exists" { - $results = Add-DbaRegServerGroup -SqlInstance $TestConfig.instance1 -Name "$group\$group2" -Description $description + $splatAddNested = @{ + SqlInstance = $TestConfig.instance1 + Name = "$group\$group2" + Description = $description + } + $results = Add-DbaRegServerGroup @splatAddNested $results.Name | Should -Be $group2 $results.SqlInstance | Should -Not -BeNullOrEmpty } It "updates description of sub-group when it already exists" { - $results = Add-DbaRegServerGroup -SqlInstance $TestConfig.instance1 -Name "$group\$group2" -Description $descriptionUpdated + $splatUpdateNested = @{ + SqlInstance = $TestConfig.instance1 + Name = "$group\$group2" + Description = $descriptionUpdated + } + $results = Add-DbaRegServerGroup @splatUpdateNested $results.Name | Should -Be $group2 $results.Description | Should -Be $descriptionUpdated $results.SqlInstance | Should -Not -BeNullOrEmpty } } -} +} \ No newline at end of file diff --git a/tests/Add-DbaReplArticle.Tests.ps1 b/tests/Add-DbaReplArticle.Tests.ps1 index f8bd9825563..5634aa9dd9a 100644 --- a/tests/Add-DbaReplArticle.Tests.ps1 +++ b/tests/Add-DbaReplArticle.Tests.ps1 @@ -1,14 +1,14 @@ #Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } param( - $ModuleName = "dbatools", - $CommandName = [System.IO.Path]::GetFileName($PSCommandPath.Replace('.Tests.ps1', '')), + $ModuleName = "dbatools", + $CommandName = "Add-DbaReplArticle", $PSDefaultParameterValues = $TestConfig.Defaults ) -Describe "Add-DbaReplArticle" -Tag "UnitTests" { +Describe $CommandName -Tag UnitTests { Context "Parameter validation" { BeforeAll { - $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $_ -notin ('WhatIf', 'Confirm') } + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } $expectedParameters = $TestConfig.CommonParameters $expectedParameters += @( "SqlInstance", @@ -31,4 +31,4 @@ Describe "Add-DbaReplArticle" -Tag "UnitTests" { <# 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/Add-DbaServerRoleMember.Tests.ps1 b/tests/Add-DbaServerRoleMember.Tests.ps1 index be498fcc980..90da8a5ad98 100644 --- a/tests/Add-DbaServerRoleMember.Tests.ps1 +++ b/tests/Add-DbaServerRoleMember.Tests.ps1 @@ -1,14 +1,14 @@ #Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } param( - $ModuleName = "dbatools", - $CommandName = [System.IO.Path]::GetFileName($PSCommandPath.Replace('.Tests.ps1', '')), + $ModuleName = "dbatools", + $CommandName = "Add-DbaServerRoleMember", $PSDefaultParameterValues = $TestConfig.Defaults ) -Describe "Add-DbaServerRoleMember" -Tag "UnitTests" { +Describe $CommandName -Tag UnitTests { Context "Parameter validation" { BeforeAll { - $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $_ -notin ('WhatIf', 'Confirm') } + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } $expectedParameters = $TestConfig.CommonParameters $expectedParameters += @( "SqlInstance", @@ -27,8 +27,11 @@ Describe "Add-DbaServerRoleMember" -Tag "UnitTests" { } } -Describe "Add-DbaServerRoleMember" -Tag "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 $login1 = "dbatoolsci_login1_$(Get-Random)" $login2 = "dbatoolsci_login2_$(Get-Random)" @@ -39,28 +42,37 @@ Describe "Add-DbaServerRoleMember" -Tag "IntegrationTests" { ) $splatNewLogin = @{ SqlInstance = $TestConfig.instance2 - Password = ('Password1234!' | ConvertTo-SecureString -asPlainText -Force) + Password = ("Password1234!" | ConvertTo-SecureString -asPlainText -Force) } $null = New-DbaLogin @splatNewLogin -Login $login1 $null = New-DbaLogin @splatNewLogin -Login $login2 $null = New-DbaServerRole -SqlInstance $TestConfig.instance2 -ServerRole $customServerRole -Owner sa + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } AfterAll { + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + $splatRemoveLogin = @{ SqlInstance = $TestConfig.instance2 - Login = $login1, $login2 - Confirm = $false + Login = $login1, $login2 + Confirm = $false } $null = Remove-DbaLogin @splatRemoveLogin + $null = Remove-DbaServerRole -SqlInstance $TestConfig.instance2 -ServerRole $customServerRole -Confirm:$false + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } Context "Functionality" { - It 'Adds Login to Role' { + It "Adds Login to Role" { $splatAddRole = @{ SqlInstance = $TestConfig.instance2 - ServerRole = $fixedServerRoles[0] - Login = $login1 - Confirm = $false + ServerRole = $fixedServerRoles[0] + Login = $login1 + Confirm = $false } Add-DbaServerRoleMember @splatAddRole $roleAfter = Get-DbaServerRole -SqlInstance $server -ServerRole $fixedServerRoles[0] @@ -69,13 +81,13 @@ Describe "Add-DbaServerRoleMember" -Tag "IntegrationTests" { $roleAfter.EnumMemberNames() | Should -Contain $login1 } - It 'Adds Login to Multiple Roles' { + It "Adds Login to Multiple Roles" { $serverRoles = Get-DbaServerRole -SqlInstance $server -ServerRole $fixedServerRoles $splatAddRoles = @{ SqlInstance = $TestConfig.instance2 - ServerRole = $serverRoles - Login = $login1 - Confirm = $false + ServerRole = $serverRoles + Login = $login1 + Confirm = $false } Add-DbaServerRoleMember @splatAddRoles @@ -84,12 +96,12 @@ Describe "Add-DbaServerRoleMember" -Tag "IntegrationTests" { $roleDBAfter.Login | Should -Contain $login1 } - It 'Adds Customer Server-Level Role Membership' { + It "Adds Customer Server-Level Role Membership" { $splatAddCustomRole = @{ SqlInstance = $TestConfig.instance2 - ServerRole = $customServerRole - Role = $fixedServerRoles[-1] - Confirm = $false + ServerRole = $customServerRole + Role = $fixedServerRoles[-1] + Confirm = $false } Add-DbaServerRoleMember @splatAddCustomRole $roleAfter = Get-DbaServerRole -SqlInstance $server -ServerRole $fixedServerRoles[-1] @@ -98,7 +110,7 @@ Describe "Add-DbaServerRoleMember" -Tag "IntegrationTests" { $roleAfter.EnumMemberNames() | Should -Contain $customServerRole } - It 'Adds Login to Roles via piped input from Get-DbaServerRole' { + It "Adds Login to Roles via piped input from Get-DbaServerRole" { $serverRole = Get-DbaServerRole -SqlInstance $server -ServerRole $fixedServerRoles[0] $serverRole | Add-DbaServerRoleMember -Login $login2 -Confirm:$false @@ -106,4 +118,4 @@ Describe "Add-DbaServerRoleMember" -Tag "IntegrationTests" { $roleAfter.EnumMemberNames() | Should -Contain $login2 } } -} +} \ No newline at end of file diff --git a/tests/Backup-DbaComputerCertificate.Tests.ps1 b/tests/Backup-DbaComputerCertificate.Tests.ps1 index 3cd68f1caf0..08efb56c47e 100644 --- a/tests/Backup-DbaComputerCertificate.Tests.ps1 +++ b/tests/Backup-DbaComputerCertificate.Tests.ps1 @@ -1,15 +1,16 @@ #Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} param( - $ModuleName = "dbatools", + $ModuleName = "dbatools", + $CommandName = "Backup-DbaComputerCertificate", $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults ) -Describe "Backup-DbaComputerCertificate" -Tag "UnitTests" { +Describe $CommandName -Tag UnitTests { Context "Parameter validation" { BeforeAll { - $command = Get-Command Backup-DbaComputerCertificate - $expected = $TestConfig.CommonParameters - $expected += @( + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( "SecurePassword", "InputObject", "Path", @@ -19,47 +20,56 @@ Describe "Backup-DbaComputerCertificate" -Tag "UnitTests" { ) } - 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 + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "Backup-DbaComputerCertificate" -Tag "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { - $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true + + # For all the backups that we want to clean up after the test, we create a directory that we can delete at the end. + # Other files can be written there as well, maybe we change the name of that variable later. But for now we focus on backups. + $backupPath = "$($TestConfig.Temp)\$CommandName-$(Get-Random)" + $null = New-Item -Path $backupPath -ItemType Directory + # Explain what needs to be set up for the test: + # To test certificate backup, we need a certificate installed on the computer. + + # Set variables. They are available in all the It blocks. $certThumbprint = "29C469578D6C6211076A09CEE5C5797EEA0C2713" - $certPath = "$($TestConfig.appveyorlabrepo)\certificates\localhost.crt" - $backupPath = $TestConfig.Temp + $certPath = "$($TestConfig.appveyorlabrepo)\certificates\localhost.crt" + # Create the objects. $null = Add-DbaComputerCertificate -Path $certPath - $PSDefaultParameterValues.Remove('*-Dba*:EnableException') + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove("*-Dba*:EnableException") } AfterAll { - $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true + + # Cleanup all created object. + $null = Remove-DbaComputerCertificate -Thumbprint $certThumbprint -ErrorAction SilentlyContinue - $null = Remove-DbaComputerCertificate -Thumbprint $certThumbprint + # Remove the backup directory. + Remove-Item -Path $backupPath -Recurse -ErrorAction SilentlyContinue + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } Context "Certificate is backed up properly" { BeforeAll { - $result = Get-DbaComputerCertificate -Thumbprint $certThumbprint | Backup-DbaComputerCertificate -Path $backupPath - } - - AfterAll { - Get-ChildItem -Path $result.FullName | Remove-Item + $backupResult = Get-DbaComputerCertificate -Thumbprint $certThumbprint | Backup-DbaComputerCertificate -Path $backupPath } It "Returns the proper results" { - $result.Name | Should -Match "$certThumbprint.cer" + $backupResult.Name | Should -Match "$certThumbprint.cer" } } -} +} \ No newline at end of file diff --git a/tests/Backup-DbaDatabase.Tests.ps1 b/tests/Backup-DbaDatabase.Tests.ps1 index 71e2e5d4527..b64a67b4796 100644 --- a/tests/Backup-DbaDatabase.Tests.ps1 +++ b/tests/Backup-DbaDatabase.Tests.ps1 @@ -1,83 +1,83 @@ #Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} param( - $ModuleName = "dbatools", + $ModuleName = "dbatools", + $CommandName = "Backup-DbaDatabase", $PSDefaultParameterValues = $TestConfig.Defaults ) -Describe "Backup-DbaDatabase" -Tag 'UnitTests' { +Describe $CommandName -Tag UnitTests { Context "Validate parameters" { BeforeAll { - $command = Get-Command Backup-DbaDatabase + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } $expectedParameters = $TestConfig.CommonParameters $expectedParameters += @( - 'SqlInstance', - 'SqlCredential', - 'Database', - 'ExcludeDatabase', - 'Path', - 'FilePath', - 'ReplaceInName', - 'NoAppendDbNameInPath', - 'CopyOnly', - 'Type', - 'InputObject', - 'CreateFolder', - 'FileCount', - 'CompressBackup', - 'Checksum', - 'Verify', - 'MaxTransferSize', - 'BlockSize', - 'BufferCount', - 'AzureBaseUrl', - 'AzureCredential', - 'NoRecovery', - 'BuildPath', - 'WithFormat', - 'Initialize', - 'SkipTapeHeader', - 'TimeStampFormat', - 'IgnoreFileChecks', - 'OutputScriptOnly', - 'EnableException', - 'EncryptionAlgorithm', - 'EncryptionCertificate', - 'IncrementPrefix', - 'Description' + "SqlInstance", + "SqlCredential", + "Database", + "ExcludeDatabase", + "Path", + "FilePath", + "ReplaceInName", + "NoAppendDbNameInPath", + "CopyOnly", + "Type", + "InputObject", + "CreateFolder", + "FileCount", + "CompressBackup", + "Checksum", + "Verify", + "MaxTransferSize", + "BlockSize", + "BufferCount", + "AzureBaseUrl", + "AzureCredential", + "NoRecovery", + "BuildPath", + "WithFormat", + "Initialize", + "SkipTapeHeader", + "TimeStampFormat", + "IgnoreFileChecks", + "OutputScriptOnly", + "EnableException", + "EncryptionAlgorithm", + "EncryptionCertificate", + "IncrementPrefix", + "Description" ) } - It "Should only contain our specific parameters" { - $actualParameters = $command.Parameters.Keys | Where-Object { $PSItem -notin "WhatIf", "Confirm" } - Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $actualParameters | Should -BeNullOrEmpty - } - - It "Has parameter: <_>" -ForEach $expectedParameters { - $command | Should -HaveParameter $PSItem + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "Backup-DbaDatabase" -Tag "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. $PSDefaultParameterValues['*-Dba*:EnableException'] = $true - $DestBackupDir = "$($TestConfig.Temp)\backups" - if (-Not (Test-Path $DestBackupDir)) { - New-Item -Type Container -Path $DestBackupDir - } + # For all the backups that we want to clean up after the test, we create a directory that we can delete at the end. + $DestBackupDir = "$($TestConfig.Temp)\$CommandName-$(Get-Random)" + $null = New-Item -Type Container -Path $DestBackupDir # Write all files to the same backup destination if not otherwise specified $PSDefaultParameterValues['Backup-DbaDatabase:BackupDirectory'] = $DestBackupDir + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } AfterAll { + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + $PSDefaultParameterValues.Remove('Backup-DbaDatabase:BackupDirectory') - if (Test-Path $DestBackupDir) { - Remove-Item -Path $DestBackupDir -Force -Recurse - } + # Remove the backup directory. + Remove-Item -Path $DestBackupDir -Force -Recurse -ErrorAction SilentlyContinue + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } Context "Properly backups all databases" { @@ -86,11 +86,11 @@ Describe "Backup-DbaDatabase" -Tag "IntegrationTests" { } It "Should return a database name, specifically master" { - $results.DatabaseName | Should -Contain 'master' + $results.DatabaseName | Should -Contain "master" } - It "Should return successful restore for <_.DatabaseName>" -ForEach $results { - $PSItem.BackupComplete | Should -BeTrue + It "Should return successful restore for all databases" { + $results | ForEach-Object { $PSItem.BackupComplete | Should -BeTrue } } } @@ -146,11 +146,11 @@ Describe "Backup-DbaDatabase" -Tag "IntegrationTests" { Context "Should take path and filename" { BeforeAll { - $results = Backup-DbaDatabase -SqlInstance $TestConfig.instance1 -Database master -BackupFileName 'PesterTest.bak' + $results = Backup-DbaDatabase -SqlInstance $TestConfig.instance1 -Database master -BackupFileName "PesterTest.bak" } It "Should report it has backed up to the path with the correct name" { - $results.Fullname | Should -BeLike "$DestBackupDir*PesterTest.bak" + $results.FullName | Should -BeLike "$DestBackupDir*PesterTest.bak" } It "Should have backed up to the path with the correct name" { @@ -164,7 +164,7 @@ Describe "Backup-DbaDatabase" -Tag "IntegrationTests" { } It "Should report it has backed up to the path with the correct name" { - $results.Fullname | Should -BeLike "$DestBackupDir*PesterTest.bak" + $results.FullName | Should -BeLike "$DestBackupDir*PesterTest.bak" } It "Should have backed up to the path with the correct name" { @@ -210,7 +210,7 @@ Describe "Backup-DbaDatabase" -Tag "IntegrationTests" { It "Should have backed up to $MissingPath" { $results.BackupFolder | Should -Be "$MissingPath" - $results.Path | Should -Not -BeLike '*\\*' + $results.Path | Should -Not -BeLike "*\\*" } } @@ -232,7 +232,7 @@ Describe "Backup-DbaDatabase" -Tag "IntegrationTests" { It "Should have appended master to all backup paths" { foreach ($path in $results.BackupFolder) { - ($results.BackupFolder | Sort-Object) | Should -Be ($backupPaths | Sort-Object | ForEach-Object { [IO.Path]::Combine($_, 'master') }) + ($results.BackupFolder | Sort-Object) | Should -Be ($backupPaths | Sort-Object | ForEach-Object { [IO.Path]::Combine($PSItem, "master") }) } } } @@ -248,7 +248,7 @@ Describe "Backup-DbaDatabase" -Tag "IntegrationTests" { } It "Should have backuped up to $DestBackupDir\PesterTest2.bak" { - Test-Path "$DestBackupDir\PesterTest2.bak" | Should -Be $true + Test-Path "$DestBackupDir\PesterTest2.bak" | Should -BeTrue } } @@ -265,13 +265,13 @@ Describe "Backup-DbaDatabase" -Tag "IntegrationTests" { It "Should have written to all 3 folders" { $backupPaths | ForEach-Object { - $_ | Should -BeIn ($results.BackupFolder) + $PSItem | Should -BeIn ($results.BackupFolder) } } It "Should have written files with extensions" { foreach ($path in $results.BackupFile) { - [IO.Path]::GetExtension($path) | Should -Be '.bak' + [IO.Path]::GetExtension($path) | Should -Be ".bak" } } } @@ -299,7 +299,7 @@ Describe "Backup-DbaDatabase" -Tag "IntegrationTests" { It "Should have 1 period in file extension" { foreach ($path in $results.BackupFile) { - [IO.Path]::GetExtension($path) | Should -Not -BeLike '*..*' + [IO.Path]::GetExtension($path) | Should -Not -BeLike "*..*" } } } @@ -323,18 +323,18 @@ Describe "Backup-DbaDatabase" -Tag "IntegrationTests" { Context "Should Backup to default path if none specified" { BeforeAll { - $PSDefaultParameterValues.Remove('Backup-DbaDatabase:BackupDirectory') + $PSDefaultParameterValues.Remove("Backup-DbaDatabase:BackupDirectory") $defaultBackupPath = (Get-DbaDefaultPath -SqlInstance $TestConfig.instance1).Backup - $results = Backup-DbaDatabase -SqlInstance $TestConfig.instance1 -Database master -BackupFileName 'PesterTest.bak' + $results = Backup-DbaDatabase -SqlInstance $TestConfig.instance1 -Database master -BackupFileName "PesterTest.bak" } AfterAll { - Get-ChildItem -Path $results.Fullname | Remove-Item - $PSDefaultParameterValues['Backup-DbaDatabase:BackupDirectory'] = $DestBackupDir + Get-ChildItem -Path $results.FullName | Remove-Item -ErrorAction SilentlyContinue + $PSDefaultParameterValues["Backup-DbaDatabase:BackupDirectory"] = $DestBackupDir } It "Should report it has backed up to the path with the corrrect name" { - $results.Fullname | Should -BeLike "$defaultBackupPath*PesterTest.bak" + $results.FullName | Should -BeLike "$defaultBackupPath*PesterTest.bak" } It "Should have backed up to the path with the corrrect name" { @@ -386,7 +386,7 @@ Describe "Backup-DbaDatabase" -Tag "IntegrationTests" { } It "Should return successful restore" { - $results.RestoreComplete | Should -Be $true + $results.RestoreComplete | Should -BeTrue } } @@ -411,15 +411,15 @@ Describe "Backup-DbaDatabase" -Tag "IntegrationTests" { } AfterAll { - $PSDefaultParameterValues['Backup-DbaDatabase:BackupDirectory'] = $DestBackupDir + $PSDefaultParameterValues["Backup-DbaDatabase:BackupDirectory"] = $DestBackupDir } It "Should return succesful backup" { - $results.BackupComplete | Should -Be $true + $results.BackupComplete | Should -BeTrue } It "Should have backed up to NUL:" { - $results.FullName[0] | Should -Be 'NUL:' + $results.FullName[0] | Should -Be "NUL:" } } @@ -429,7 +429,7 @@ Describe "Backup-DbaDatabase" -Tag "IntegrationTests" { } It "Should return a string" { - $results.GetType().ToString() | Should -Be 'System.String' + $results.GetType().ToString() | Should -Be "System.String" } It "Should return BACKUP DATABASE [master] TO DISK = N'c:\notexists\file.bak' WITH NOFORMAT, NOINIT, NOSKIP, REWIND, NOUNLOAD, STATS = 1" { @@ -447,7 +447,7 @@ go CREATE DATABASE encrypted go "@ - $null = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Query $sqlencrypt -Database Master + $null = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Query $sqlencrypt -Database master $createdb = @" CREATE DATABASE ENCRYPTION KEY WITH ALGORITHM = AES_128 @@ -466,13 +466,13 @@ GO drop certificate MyServerCert go "@ - $null = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Query $sqldrop -Database Master + $null = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Query $sqldrop -Database master } It "Should compress an encrypted db" { $results = Backup-DbaDatabase -SqlInstance $TestConfig.instance2 -Database encrypted -Compress Invoke-Command2 -ComputerName $TestConfig.instance2 -ScriptBlock { Remove-Item -Path $args[0] } -ArgumentList $results.FullName - $results.script | Should -BeLike '*D, COMPRESSION,*' + $results.script | Should -BeLike "*D, COMPRESSION,*" } } @@ -483,7 +483,7 @@ go } It "Should apply the corect custom Timestamp" { - ($results | Where-Object { $_.BackupPath -like '*bobob*' }).count | Should -Be $results.count + ($results | Where-Object { $PSItem.BackupPath -like "*bobob*" }).Count | Should -Be $results.Count } } @@ -501,7 +501,7 @@ go Context "Test Backup templating when db object piped in issue 8100" { BeforeAll { - $results = Get-DbaDatabase -SqlInstance $TestConfig.instance1 -Database master,msdb | Backup-DbaDatabase -BackupDirectory $DestBackupDir\db2\dbname\instancename\backuptype\ -BackupFileName dbname-backuptype.bak -ReplaceInName -BuildPath + $results = Get-DbaDatabase -SqlInstance $TestConfig.instance1 -Database master, msdb | Backup-DbaDatabase -BackupDirectory $DestBackupDir\db2\dbname\instancename\backuptype\ -BackupFileName dbname-backuptype.bak -ReplaceInName -BuildPath $instanceName = ([DbaInstanceParameter]$TestConfig.instance1).InstanceName } @@ -514,16 +514,16 @@ go Context "Test Backup Encryption with Certificate" { # TODO: Should the master key be created at lab startup like in instance3? BeforeAll { - $securePass = ConvertTo-SecureString "estBackupDir\master\script:instance1).split('\')[1])\Full\master-Full.bak" -AsPlainText -Force - New-DbaDbMasterKey -SqlInstance $TestConfig.instance2 -Database Master -SecurePassword $securePass -ErrorAction SilentlyContinue -WarningAction SilentlyContinue + $securePass = ConvertTo-SecureString "MyStrongPassword123!" -AsPlainText -Force + New-DbaDbMasterKey -SqlInstance $TestConfig.instance2 -Database master -SecurePassword $securePass -ErrorAction SilentlyContinue -WarningAction SilentlyContinue $cert = New-DbaDbCertificate -SqlInstance $TestConfig.instance2 -Database master -Name BackupCertt -Subject BackupCertt - $encBackupResults = Backup-DbaDatabase -SqlInstance $TestConfig.instance2 -Database master -EncryptionAlgorithm AES128 -EncryptionCertificate BackupCertt -BackupFileName 'encryptiontest.bak' -Description "Encrypted backup" + $encBackupResults = Backup-DbaDatabase -SqlInstance $TestConfig.instance2 -Database master -EncryptionAlgorithm AES128 -EncryptionCertificate BackupCertt -BackupFileName "encryptiontest.bak" -Description "Encrypted backup" Invoke-Command2 -ComputerName $TestConfig.instance2 -ScriptBlock { Remove-Item -Path $args[0] } -ArgumentList $encBackupResults.FullName } AfterAll { Remove-DbaDbCertificate -SqlInstance $TestConfig.instance2 -Database master -Certificate BackupCertt - Remove-DbaDbMasterKey -SqlInstance $TestConfig.instance2 -Database Master -WarningAction SilentlyContinue -ErrorAction SilentlyContinue + Remove-DbaDbMasterKey -SqlInstance $TestConfig.instance2 -Database master -WarningAction SilentlyContinue -ErrorAction SilentlyContinue } It "Should encrypt the backup" { @@ -551,14 +551,14 @@ go $sql = "DROP CREDENTIAL [$TestConfig.azureblob]" $server.Query($sql) } - $sql = "CREATE CREDENTIAL [$TestConfig.azureblob] WITH IDENTITY = N'SHARED ACCESS SIGNATURE', SECRET = N'$env:azurepasswd'" + $sql = "CREATE CREDENTIAL [$($TestConfig.azureblob)] WITH IDENTITY = N'SHARED ACCESS SIGNATURE', SECRET = N'$($env:azurepasswd)'" $server.Query($sql) $server.Query("CREATE DATABASE dbatoolsci_azure") if (Get-DbaCredential -SqlInstance $TestConfig.instance2 -name dbatools_ci) { $sql = "DROP CREDENTIAL dbatools_ci" $server.Query($sql) } - $sql = "CREATE CREDENTIAL [dbatools_ci] WITH IDENTITY = N'$TestConfig.azureblobaccount', SECRET = N'$env:azurelegacypasswd'" + $sql = "CREATE CREDENTIAL [dbatools_ci] WITH IDENTITY = N'$($TestConfig.azureblobaccount)', SECRET = N'$($env:azurelegacypasswd)'" $server.Query($sql) } @@ -569,17 +569,17 @@ go It "backs up to Azure properly using SHARED ACCESS SIGNATURE" { $results = Backup-DbaDatabase -SqlInstance $TestConfig.instance2 -AzureBaseUrl $TestConfig.azureblob -Database dbatoolsci_azure -BackupFileName dbatoolsci_azure.bak -WithFormat - $results.Database | Should -Be 'dbatoolsci_azure' - $results.DeviceType | Should -Be 'URL' - $results.BackupFile | Should -Be 'dbatoolsci_azure.bak' + $results.Database | Should -Be "dbatoolsci_azure" + $results.DeviceType | Should -Be "URL" + $results.BackupFile | Should -Be "dbatoolsci_azure.bak" } It "backs up to Azure properly using legacy credential" { $results = Backup-DbaDatabase -SqlInstance $TestConfig.instance2 -AzureBaseUrl $TestConfig.azureblob -Database dbatoolsci_azure -BackupFileName dbatoolsci_azure2.bak -WithFormat -AzureCredential dbatools_ci - $results.Database | Should -Be 'dbatoolsci_azure' - $results.DeviceType | Should -Be 'URL' - $results.BackupFile | Should -Be 'dbatoolsci_azure2.bak' + $results.Database | Should -Be "dbatoolsci_azure" + $results.DeviceType | Should -Be "URL" + $results.BackupFile | Should -Be "dbatoolsci_azure2.bak" } } } -} +} \ No newline at end of file diff --git a/tests/Backup-DbaDbCertificate.Tests.ps1 b/tests/Backup-DbaDbCertificate.Tests.ps1 index 4896e5565ba..4726452abac 100644 --- a/tests/Backup-DbaDbCertificate.Tests.ps1 +++ b/tests/Backup-DbaDbCertificate.Tests.ps1 @@ -1,15 +1,16 @@ -#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } param( - $ModuleName = "dbatools", + $ModuleName = "dbatools", + $CommandName = "Backup-DbaDbCertificate", $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults ) -Describe "Backup-DbaDbCertificate" -Tag "UnitTests" { +Describe $CommandName -Tag UnitTests { Context "Parameter validation" { BeforeAll { - $command = Get-Command Backup-DbaDbCertificate - $expected = $TestConfig.CommonParameters - $expected += @( + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( "SqlInstance", "SqlCredential", "Certificate", @@ -21,26 +22,20 @@ Describe "Backup-DbaDbCertificate" -Tag "UnitTests" { "Suffix", "FileBaseName", "InputObject", - "EnableException", - "Confirm", - "WhatIf" + "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 + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "Backup-DbaDbCertificate" -Tag "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { - $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true $random = Get-Random $db1Name = "dbatoolscli_db1_$random" @@ -53,48 +48,67 @@ Describe "Backup-DbaDbCertificate" -Tag "IntegrationTests" { $db2 = New-DbaDatabase -SqlInstance $TestConfig.instance1 -Name $db2Name $null = New-DbaDbMasterKey -SqlInstance $TestConfig.instance1 -Database $db2Name -Password $pw - $cert1 = New-DbaDbCertificate -SqlInstance $TestConfig.instance1 -Database $db1Name -Password $pw -Name dbatoolscli_cert1_$random - $cert2 = New-DbaDbCertificate -SqlInstance $TestConfig.instance1 -Database $db1Name -Password $pw -Name dbatoolscli_cert2_$random - $cert3 = New-DbaDbCertificate -SqlInstance $TestConfig.instance1 -Database $db2Name -Password $pw -Name dbatoolscli_cert3_$random + $cert1 = New-DbaDbCertificate -SqlInstance $TestConfig.instance1 -Database $db1Name -Password $pw -Name "dbatoolscli_cert1_$random" + $cert2 = New-DbaDbCertificate -SqlInstance $TestConfig.instance1 -Database $db1Name -Password $pw -Name "dbatoolscli_cert2_$random" + $cert3 = New-DbaDbCertificate -SqlInstance $TestConfig.instance1 -Database $db2Name -Password $pw -Name "dbatoolscli_cert3_$random" - $PSDefaultParameterValues.Remove('*-Dba*:EnableException') + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove("*-Dba*:EnableException") } AfterAll { - $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true - Remove-DbaDatabase -SqlInstance $TestConfig.instance1 -Database $db1Name, $db2Name + Remove-DbaDatabase -SqlInstance $TestConfig.instance1 -Database $db1Name, $db2Name -Confirm:$false + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } Context "Can backup a database certificate" { BeforeAll { - $results = Backup-DbaDbCertificate -SqlInstance $TestConfig.instance1 -Database $db1Name -Certificate $cert1.Name -EncryptionPassword $pw -DecryptionPassword $pw + $splatBackupCert = @{ + SqlInstance = $TestConfig.instance1 + Database = $db1Name + Certificate = $cert1.Name + EncryptionPassword = $pw + DecryptionPassword = $pw + } + $results = Backup-DbaDbCertificate @splatBackupCert } AfterAll { - Remove-Item -Path $results.Path - Remove-Item -Path $results.Key + Remove-Item -Path $results.Path -ErrorAction SilentlyContinue + Remove-Item -Path $results.Key -ErrorAction SilentlyContinue } It "Returns results with proper data" { $results.Certificate | Should -Be $cert1.Name - $results.Status | Should -Match "Success" + $results.Status | Should -BeExactly "Success" $results.DatabaseID | Should -Be $db1.ID } } Context "Can backup a database certificate with a filename (see #9485)" { BeforeAll { - $results = Backup-DbaDbCertificate -SqlInstance $TestConfig.instance1 -Database $db1Name -Certificate $cert1.Name -EncryptionPassword $pw -DecryptionPassword $pw -FileBaseName "dbatoolscli_cert1_$random" + $splatBackupCertWithName = @{ + SqlInstance = $TestConfig.instance1 + Database = $db1Name + Certificate = $cert1.Name + EncryptionPassword = $pw + DecryptionPassword = $pw + FileBaseName = "dbatoolscli_cert1_$random" + } + $results = Backup-DbaDbCertificate @splatBackupCertWithName } AfterAll { - Remove-Item -Path $results.Path - Remove-Item -Path $results.Key + Remove-Item -Path $results.Path -ErrorAction SilentlyContinue + Remove-Item -Path $results.Key -ErrorAction SilentlyContinue } It "Returns results with proper data" { $results.Certificate | Should -Be $cert1.Name - $results.Status | Should -Match "Success" + $results.Status | Should -BeExactly "Success" $results.DatabaseID | Should -Be $db1.ID [IO.Path]::GetFileNameWithoutExtension($results.Path) | Should -Be "dbatoolscli_cert1_$random" } @@ -102,29 +116,43 @@ Describe "Backup-DbaDbCertificate" -Tag "IntegrationTests" { Context "Warns the caller if the cert cannot be found" { BeforeAll { - $invalidDBCertName = "dbatoolscli_invalidCertName" + $invalidDBCertName = "dbatoolscli_invalidCertName" $invalidDBCertName2 = "dbatoolscli_invalidCertName2" - $results = Backup-DbaDbCertificate -SqlInstance $TestConfig.instance1 -Database $db1Name -Certificate $invalidDBCertName, $invalidDBCertName2, $cert2.Name -EncryptionPassword $pw -DecryptionPassword $pw -WarningAction SilentlyContinue + $splatBackupInvalidCert = @{ + SqlInstance = $TestConfig.instance1 + Database = $db1Name + Certificate = @($invalidDBCertName, $invalidDBCertName2, $cert2.Name) + EncryptionPassword = $pw + DecryptionPassword = $pw + WarningAction = "SilentlyContinue" + } + $results = Backup-DbaDbCertificate @splatBackupInvalidCert } AfterAll { - Remove-Item -Path $results.Path - Remove-Item -Path $results.Key + Remove-Item -Path $results.Path -ErrorAction SilentlyContinue + Remove-Item -Path $results.Key -ErrorAction SilentlyContinue } It "Does warn" { - $WarnVar | Should -BeLike "*Database certificate(s) * not found*" + $WarnVar | Should -Match "Database certificate\(s\) .* not found" } } Context "Backs up all db certs for a database" { BeforeAll { - $results = Backup-DbaDbCertificate -SqlInstance $TestConfig.instance1 -Database $db1Name -EncryptionPassword $pw -DecryptionPassword $pw + $splatBackupDbCerts = @{ + SqlInstance = $TestConfig.instance1 + Database = $db1Name + EncryptionPassword = $pw + DecryptionPassword = $pw + } + $results = Backup-DbaDbCertificate @splatBackupDbCerts } AfterAll { - Remove-Item -Path $results.Path - Remove-Item -Path $results.Key + Remove-Item -Path $results.Path -ErrorAction SilentlyContinue + Remove-Item -Path $results.Key -ErrorAction SilentlyContinue } It "Returns results with proper data" { @@ -135,12 +163,17 @@ Describe "Backup-DbaDbCertificate" -Tag "IntegrationTests" { Context "Backs up all db certs for an instance" { BeforeAll { - $results = Backup-DbaDbCertificate -SqlInstance $TestConfig.instance1 -EncryptionPassword $pw -DecryptionPassword $pw + $splatBackupAllCerts = @{ + SqlInstance = $TestConfig.instance1 + EncryptionPassword = $pw + DecryptionPassword = $pw + } + $results = Backup-DbaDbCertificate @splatBackupAllCerts } AfterAll { - Remove-Item -Path $results.Path - Remove-Item -Path $results.Key + Remove-Item -Path $results.Path -ErrorAction SilentlyContinue + Remove-Item -Path $results.Key -ErrorAction SilentlyContinue } It "Returns results with proper data" { @@ -148,4 +181,4 @@ Describe "Backup-DbaDbCertificate" -Tag "IntegrationTests" { $results.Certificate | Should -Be $cert1.Name, $cert2.Name, $cert3.Name } } -} +} \ No newline at end of file diff --git a/tests/Backup-DbaDbMasterKey.Tests.ps1 b/tests/Backup-DbaDbMasterKey.Tests.ps1 index 83de988e6d9..708f05e60f3 100644 --- a/tests/Backup-DbaDbMasterKey.Tests.ps1 +++ b/tests/Backup-DbaDbMasterKey.Tests.ps1 @@ -1,15 +1,16 @@ -#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } param( - $ModuleName = "dbatools", - $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults + $ModuleName = "dbatools", + $CommandName = "Backup-DbaDbMasterKey", + $PSDefaultParameterValues = $TestConfig.Defaults ) -Describe "Backup-DbaDbMasterKey" -Tag "UnitTests" { +Describe $CommandName -Tag UnitTests { Context "Parameter validation" { BeforeAll { - $command = Get-Command Backup-DbaDbMasterKey - $expected = $TestConfig.CommonParameters - $expected += @( + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( "SqlInstance", "SqlCredential", "Credential", @@ -19,72 +20,103 @@ Describe "Backup-DbaDbMasterKey" -Tag "UnitTests" { "Path", "FileBaseName", "InputObject", - "EnableException", - "WhatIf", - "Confirm" + "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 + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "Backup-DbaDbMasterKey" -Tag "IntegrationTests" { - Context "Can backup a database master key" { - BeforeAll { - $instance = $TestConfig.instance1 - $database = "tempdb" - $password = ConvertTo-SecureString -String "GoodPass1234!" -AsPlainText -Force +Describe $CommandName -Tag IntegrationTests { + BeforeAll { + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # For all the backups that we want to clean up after the test, we create a directory that we can delete at the end. + # Other files can be written there as well, maybe we change the name of that variable later. But for now we focus on backups. + $backupPath = "$($TestConfig.Temp)\$CommandName-$(Get-Random)" + $null = New-Item -Path $backupPath -ItemType Directory + + # Explain what needs to be set up for the test: + # To test backing up a database master key, we need a database with a master key created. + # We'll create the master key if it doesn't exist, and track files created for cleanup. - if (-not (Get-DbaDbMasterKey -SqlInstance $instance -Database $database)) { - $null = New-DbaDbMasterKey -SqlInstance $instance -Database $database -Password $password -Confirm:$false + # Set variables. They are available in all the It blocks. + $testInstance = $TestConfig.instance1 + $testDatabase = "tempdb" + $masterKeyPass = ConvertTo-SecureString -String "GoodPass1234!" -AsPlainText -Force + $filesToRemove = @() + + # Create the objects. + if (-not (Get-DbaDbMasterKey -SqlInstance $testInstance -Database $testDatabase)) { + $splatNewKey = @{ + SqlInstance = $testInstance + Database = $testDatabase + Password = $masterKeyPass + Confirm = $false } + $null = New-DbaDbMasterKey @splatNewKey } - AfterAll { - Get-DbaDbMasterKey -SqlInstance $instance -Database $database | Remove-DbaDbMasterKey -Confirm:$false - } + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') + } + + AfterAll { + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # Cleanup all created objects. + Get-DbaDbMasterKey -SqlInstance $testInstance -Database $testDatabase | Remove-DbaDbMasterKey -Confirm:$false + # Remove the backup directory. + Remove-Item -Path $backupPath -Recurse -ErrorAction SilentlyContinue + + # Remove any tracked files. + Remove-Item -Path $filesToRemove -ErrorAction SilentlyContinue + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. + } + + Context "Can backup a database master key" { It "Backs up the database master key" { $splatBackup = @{ - SqlInstance = $instance - Database = $database - SecurePassword = $password - Confirm = $false + SqlInstance = $testInstance + Database = $testDatabase + SecurePassword = $masterKeyPass + Path = $backupPath + Confirm = $false } $results = Backup-DbaDbMasterKey @splatBackup $results | Should -Not -BeNullOrEmpty - $results.Database | Should -Be $database + $results.Database | Should -Be $testDatabase $results.Status | Should -Be "Success" - $results.DatabaseID | Should -Be (Get-DbaDatabase -SqlInstance $instance -Database $database).ID + $results.DatabaseID | Should -Be (Get-DbaDatabase -SqlInstance $testInstance -Database $testDatabase).ID - $null = Remove-Item -Path $results.Path -ErrorAction SilentlyContinue -Confirm:$false + # File will be cleaned up with the backupPath directory in AfterAll } It "Backs up the database master key with a specific filename (see #9484)" { $random = Get-Random - $splatBackup = @{ - SqlInstance = $instance - Database = $database - SecurePassword = $password - FileBaseName = "dbatoolscli_dbmasterkey_$random" - Confirm = $false + $splatBackupWithName = @{ + SqlInstance = $testInstance + Database = $testDatabase + SecurePassword = $masterKeyPass + Path = $backupPath + FileBaseName = "dbatoolscli_dbmasterkey_$random" + Confirm = $false } - $results = Backup-DbaDbMasterKey @splatBackup + $results = Backup-DbaDbMasterKey @splatBackupWithName $results | Should -Not -BeNullOrEmpty - $results.Database | Should -Be $database + $results.Database | Should -Be $testDatabase $results.Status | Should -Be "Success" - $results.DatabaseID | Should -Be (Get-DbaDatabase -SqlInstance $instance -Database $database).ID + $results.DatabaseID | Should -Be (Get-DbaDatabase -SqlInstance $testInstance -Database $testDatabase).ID [IO.Path]::GetFileNameWithoutExtension($results.Path) | Should -Be "dbatoolscli_dbmasterkey_$random" - $null = Remove-Item -Path $results.Path -ErrorAction SilentlyContinue -Confirm:$false - } + # File will be cleaned up with the backupPath directory in AfterAll + } } -} +} \ No newline at end of file diff --git a/tests/Backup-DbaServiceMasterKey.Tests.ps1 b/tests/Backup-DbaServiceMasterKey.Tests.ps1 index 1145578f5f3..8d5091b0ba2 100644 --- a/tests/Backup-DbaServiceMasterKey.Tests.ps1 +++ b/tests/Backup-DbaServiceMasterKey.Tests.ps1 @@ -1,56 +1,96 @@ -#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } param( - $ModuleName = "dbatools", - $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults + $ModuleName = "dbatools", + $CommandName = "Backup-DbaServiceMasterKey", + $PSDefaultParameterValues = $TestConfig.Defaults ) -Describe "Backup-DbaServiceMasterKey" -Tag "UnitTests" { +Describe $CommandName -Tag UnitTests { Context "Parameter validation" { BeforeAll { - $command = Get-Command Backup-DbaServiceMasterKey - $expected = $TestConfig.CommonParameters - $expected += @( + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( "SqlInstance", "SqlCredential", "KeyCredential", "SecurePassword", "Path", "FileBaseName", - "EnableException", - "Confirm", - "WhatIf" + "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 + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "Backup-DbaServiceMasterKey" -Tag "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { + BeforeAll { + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true + + # For all the backups that we want to clean up after the test, we create a directory that we can delete at the end. + # Other files can be written there as well, maybe we change the name of that variable later. But for now we focus on backups. + $backupPath = "$($TestConfig.Temp)\$CommandName-$(Get-Random)" + $null = New-Item -Path $backupPath -ItemType Directory + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove("*-Dba*:EnableException") + } + + AfterAll { + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true + + # Remove the backup directory. + Remove-Item -Path $backupPath -Recurse -ErrorAction SilentlyContinue + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. + } + Context "Can backup a service master key" { BeforeAll { $securePassword = ConvertTo-SecureString -String "GoodPass1234!" -AsPlainText -Force } + AfterAll { + # Clean up any remaining files that weren't in the backup directory + if ($smkBackupPath) { + Remove-Item -Path $smkBackupPath -ErrorAction SilentlyContinue + } + if ($fileBackupPath) { + Remove-Item -Path $fileBackupPath -ErrorAction SilentlyContinue + } + } + It "backs up the SMK" { - $results = Backup-DbaServiceMasterKey -SqlInstance $TestConfig.instance1 -SecurePassword $securePassword -Confirm:$false - $results.Status | Should -Be "Success" - $null = Remove-Item -Path $results.Path -ErrorAction SilentlyContinue -Confirm:$false + $splatBackup = @{ + SqlInstance = $TestConfig.instance1 + SecurePassword = $securePassword + Path = $backupPath + Confirm = $false + } + $backupResults = Backup-DbaServiceMasterKey @splatBackup + $backupResults.Status | Should -Be "Success" + $smkBackupPath = $backupResults.Path } It "backs up the SMK with a specific filename (see #9483)" { - $random = Get-Random - $results = Backup-DbaServiceMasterKey -SqlInstance $TestConfig.instance1 -SecurePassword $securePassword -FileBaseName "smk($random)" -Confirm:$false - [IO.Path]::GetFileNameWithoutExtension($results.Path) | Should -Be "smk($random)" - $results.Status | Should -Be "Success" - $null = Remove-Item -Path $results.Path -ErrorAction SilentlyContinue -Confirm:$false + $randomNum = Get-Random + $splatFileBackup = @{ + SqlInstance = $TestConfig.instance1 + SecurePassword = $securePassword + Path = $backupPath + FileBaseName = "smk($randomNum)" + Confirm = $false + } + $fileBackupResults = Backup-DbaServiceMasterKey @splatFileBackup + [IO.Path]::GetFileNameWithoutExtension($fileBackupResults.Path) | Should -Be "smk($randomNum)" + $fileBackupResults.Status | Should -Be "Success" + $fileBackupPath = $fileBackupResults.Path } } -} +} \ No newline at end of file diff --git a/tests/Clear-DbaConnectionPool.Tests.ps1 b/tests/Clear-DbaConnectionPool.Tests.ps1 index cd92862fd72..42aee5f2a54 100644 --- a/tests/Clear-DbaConnectionPool.Tests.ps1 +++ b/tests/Clear-DbaConnectionPool.Tests.ps1 @@ -1,36 +1,32 @@ -#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } param( - $ModuleName = "dbatools", - $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults + $ModuleName = "dbatools", + $CommandName = "Clear-DbaConnectionPool", + $PSDefaultParameterValues = $TestConfig.Defaults ) -Describe "Clear-DbaConnectionPool" -Tag "UnitTests" { +Describe $CommandName -Tag UnitTests { Context "Parameter validation" { BeforeAll { - $command = Get-Command Clear-DbaConnectionPool - $expected = $TestConfig.CommonParameters - $expected += @( + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( "ComputerName", "Credential", "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 + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "Clear-DbaConnectionPool" -Tag "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { Context "When clearing connection pool" { It "Doesn't throw" { { Clear-DbaConnectionPool } | Should -Not -Throw } } -} +} \ No newline at end of file diff --git a/tests/Clear-DbaLatchStatistics.Tests.ps1 b/tests/Clear-DbaLatchStatistics.Tests.ps1 index 77d72e213c8..1a6a40f1137 100644 --- a/tests/Clear-DbaLatchStatistics.Tests.ps1 +++ b/tests/Clear-DbaLatchStatistics.Tests.ps1 @@ -1,46 +1,48 @@ -#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } param( - $ModuleName = "dbatools", - $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults + $ModuleName = "dbatools", + $CommandName = "Clear-DbaLatchStatistics", + $PSDefaultParameterValues = $TestConfig.Defaults ) -Describe "Clear-DbaLatchStatistics" -Tag "UnitTests" { +Describe $CommandName -Tag UnitTests { Context "Parameter validation" { BeforeAll { - $command = Get-Command Clear-DbaLatchStatistics - $expected = $TestConfig.CommonParameters - $expected += @( + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( "SqlInstance", "SqlCredential", - "EnableException", - "Confirm", - "WhatIf" + "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 + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "Clear-DbaLatchStatistics" -Tag "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { + BeforeAll { + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true + } + + AfterAll { + $PSDefaultParameterValues.Remove("*-Dba*:EnableException") + } + Context "Command executes properly and returns proper info" { BeforeAll { $splatClearLatch = @{ SqlInstance = $TestConfig.instance1 - Confirm = $false + Confirm = $false } $results = Clear-DbaLatchStatistics @splatClearLatch } It "Returns success" { - $results.Status | Should -Be 'Success' + $results.Status | Should -Be "Success" } } -} +} \ No newline at end of file diff --git a/tests/Clear-DbaPlanCache.Tests.ps1 b/tests/Clear-DbaPlanCache.Tests.ps1 index de7e1ef729b..573a1faab9c 100644 --- a/tests/Clear-DbaPlanCache.Tests.ps1 +++ b/tests/Clear-DbaPlanCache.Tests.ps1 @@ -1,37 +1,31 @@ -#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } param( - $ModuleName = "dbatools", - $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults + $ModuleName = "dbatools", + $CommandName = "Clear-DbaPlanCache", + $PSDefaultParameterValues = $TestConfig.Defaults ) -Describe "Clear-DbaPlanCache" -Tag "UnitTests" { +Describe $CommandName -Tag UnitTests { Context "Parameter validation" { BeforeAll { - $command = Get-Command Clear-DbaPlanCache - $expected = $TestConfig.CommonParameters - $expected += @( + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( "SqlInstance", "SqlCredential", "Threshold", "InputObject", - "EnableException", - "Confirm", - "WhatIf" + "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 + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "Clear-DbaPlanCache" -Tag "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { Context "When not clearing plan cache" { BeforeAll { # Make plan cache way higher than likely for a test rig @@ -41,13 +35,13 @@ Describe "Clear-DbaPlanCache" -Tag "IntegrationTests" { It "Returns correct datatypes" { $results = Clear-DbaPlanCache -SqlInstance $TestConfig.instance1 -Threshold $threshold $results.Size | Should -BeOfType [dbasize] - $results.Status | Should -Match 'below' + $results.Status | Should -Match "below" } It "Supports piping" { $results = Get-DbaPlanCache -SqlInstance $TestConfig.instance1 | Clear-DbaPlanCache -Threshold $threshold $results.Size | Should -BeOfType [dbasize] - $results.Status | Should -Match 'below' + $results.Status | Should -Match "below" } } -} +} \ No newline at end of file diff --git a/tests/Clear-DbaWaitStatistics.Tests.ps1 b/tests/Clear-DbaWaitStatistics.Tests.ps1 index 4014ee4a8ec..fc9e042ae5a 100644 --- a/tests/Clear-DbaWaitStatistics.Tests.ps1 +++ b/tests/Clear-DbaWaitStatistics.Tests.ps1 @@ -1,42 +1,48 @@ -#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } param( - $ModuleName = "dbatools", + $ModuleName = "dbatools", + $CommandName = "Clear-DbaWaitStatistics", $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults ) -Describe "Clear-DbaWaitStatistics" -Tag "UnitTests" { +Describe $CommandName -Tag UnitTests { Context "Parameter validation" { BeforeAll { - $command = Get-Command Clear-DbaWaitStatistics - $expected = $TestConfig.CommonParameters - $expected += @( + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( "SqlInstance", "SqlCredential", - "EnableException", - "Confirm", - "WhatIf" + "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 + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "Clear-DbaWaitStatistics" -Tag "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { + BeforeAll { + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true + } + + AfterAll { + $PSDefaultParameterValues.Remove("*-Dba*:EnableException") + } + Context "Command executes properly and returns proper info" { BeforeAll { - $results = Clear-DbaWaitStatistics -SqlInstance $TestConfig.instance1 -Confirm:$false + $splatClearStats = @{ + SqlInstance = $TestConfig.instance1 + Confirm = $false + } + $clearResults = Clear-DbaWaitStatistics @splatClearStats } It "Returns success" { - $results.Status | Should -Be 'Success' + $clearResults.Status | Should -Be "Success" } } -} +} \ No newline at end of file diff --git a/tests/Connect-DbaInstance.Tests.ps1 b/tests/Connect-DbaInstance.Tests.ps1 index cb7365c8e72..a59cebb9790 100644 --- a/tests/Connect-DbaInstance.Tests.ps1 +++ b/tests/Connect-DbaInstance.Tests.ps1 @@ -1,16 +1,59 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Connect-DbaInstance", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'ApplicationIntent', 'AzureUnsupported', 'BatchSeparator', 'ClientName', 'ConnectTimeout', 'EncryptConnection', 'FailoverPartner', 'LockTimeout', 'MaxPoolSize', 'MinPoolSize', 'MinimumVersion', 'MultipleActiveResultSets', 'MultiSubnetFailover', 'NetworkProtocol', 'NonPooledConnection', 'PacketSize', 'PooledConnectionLifetime', 'SqlExecutionModes', 'StatementTimeout', 'TrustServerCertificate', 'WorkstationId', 'AlwaysEncrypted', 'AppendConnectionString', 'SqlConnectionOnly', 'AzureDomain', 'Tenant', 'AccessToken', 'DedicatedAdminConnection', 'DisableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Database", + "ApplicationIntent", + "AzureUnsupported", + "BatchSeparator", + "ClientName", + "ConnectTimeout", + "EncryptConnection", + "FailoverPartner", + "LockTimeout", + "MaxPoolSize", + "MinPoolSize", + "MinimumVersion", + "MultipleActiveResultSets", + "MultiSubnetFailover", + "NetworkProtocol", + "NonPooledConnection", + "PacketSize", + "PooledConnectionLifetime", + "SqlExecutionModes", + "StatementTimeout", + "TrustServerCertificate", + "WorkstationId", + "AlwaysEncrypted", + "AppendConnectionString", + "SqlConnectionOnly", + "AzureDomain", + "Tenant", + "AccessToken", + "DedicatedAdminConnection", + "DisableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } + Context "Validate alias" { It "Should contain the alias: cdi" { (Get-Alias cdi) | Should -Not -BeNullOrEmpty @@ -18,7 +61,7 @@ Describe "$CommandName Unit Tests" -Tag 'UnitTests' { } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { AfterAll { Get-DbaConnectedInstance | Disconnect-DbaInstance Clear-DbaConnectionPool @@ -26,33 +69,35 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { if ($env:azuredbpasswd -eq "failstoooften") { Context "Connect to Azure" { - $securePassword = ConvertTo-SecureString $env:azuredbpasswd -AsPlainText -Force - $cred = New-Object System.Management.Automation.PSCredential ($TestConfig.azuresqldblogin, $securePassword) + BeforeAll { + $securePassword = ConvertTo-SecureString $env:azuredbpasswd -AsPlainText -Force + $cred = New-Object System.Management.Automation.PSCredential ($TestConfig.azuresqldblogin, $securePassword) + } It "Should login to Azure" { $s = Connect-DbaInstance -SqlInstance psdbatools.database.windows.net -SqlCredential $cred -Database test - $s.Name | Should -match 'psdbatools.database.windows.net' - $s.DatabaseEngineType | Should -Be 'SqlAzureDatabase' + $s.Name | Should -match "psdbatools.database.windows.net" + $s.DatabaseEngineType | Should -Be "SqlAzureDatabase" } It "Should keep the same database context" { $s = Connect-DbaInstance -SqlInstance psdbatools.database.windows.net -SqlCredential $cred -Database test $results = Invoke-DbaQuery -SqlInstance $s -Query "select db_name() as dbname" - $results.dbname | Should -Be 'test' + $results.dbname | Should -Be "test" } It "Should keep the same database context again" { $s = Connect-DbaInstance -SqlInstance psdbatools.database.windows.net -SqlCredential $cred -Database test $results = Invoke-DbaQuery -SqlInstance $s -Query "select db_name() as dbname" - $results.dbname | Should -Be 'test' + $results.dbname | Should -Be "test" $results = Invoke-DbaQuery -SqlInstance $s -Query "select db_name() as dbname" - $results.dbname | Should -Be 'test' + $results.dbname | Should -Be "test" } It "Should keep the same database context" { $s = Connect-DbaInstance -SqlInstance psdbatools.database.windows.net -SqlCredential $cred -Database test $server = Connect-DbaInstance -SqlInstance $s - $server.Query("select db_name() as dbname").dbname | Should -Be 'test' + $server.Query("select db_name() as dbname").dbname | Should -Be "test" } } } @@ -60,19 +105,19 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { Context "connection is properly made using a string" { BeforeAll { $params = @{ - 'BatchSeparator' = 'GO' - 'ConnectTimeout' = 1 - 'Database' = 'tempdb' - 'LockTimeout' = 1 - 'MaxPoolSize' = 20 - 'MinPoolSize' = 1 - 'NetworkProtocol' = 'TcpIp' - 'PacketSize' = 4096 - 'PooledConnectionLifetime' = 600 - 'WorkstationId' = 'MadeUpServer' - 'SqlExecutionModes' = 'ExecuteSql' - 'StatementTimeout' = 0 - 'ApplicationIntent' = 'ReadOnly' + BatchSeparator = "GO" + ConnectTimeout = 1 + Database = "tempdb" + LockTimeout = 1 + MaxPoolSize = 20 + MinPoolSize = 1 + NetworkProtocol = "TcpIp" + PacketSize = 4096 + PooledConnectionLifetime = 600 + WorkstationId = "MadeUpServer" + SqlExecutionModes = "ExecuteSql" + StatementTimeout = 0 + ApplicationIntent = "ReadOnly" } $server = Connect-DbaInstance -SqlInstance $TestConfig.instance1 @params } @@ -83,12 +128,12 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { It "sets connectioncontext parameters that are provided" { foreach ($param in $params.GetEnumerator()) { - if ($param.Key -eq 'Database') { - $propName = 'DatabaseName' + if ($param.Key -eq "Database") { + $propName = "DatabaseName" } else { $propName = $param.Key } - $server.ConnectionContext.$propName | Should -Be $param.Value + $server.ConnectionContext.PSObject.Properties[$propName].Value | Should -Be $param.Value } } @@ -101,8 +146,8 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { } It "keeps the same database context" { - $null = $server.Databases['msdb'].Tables.Count - $server.ConnectionContext.ExecuteScalar("select db_name()") | Should -Be 'tempdb' + $null = $server.Databases["msdb"].Tables.Count + $server.ConnectionContext.ExecuteScalar("select db_name()") | Should -Be "tempdb" } It "sets StatementTimeout to 0" { @@ -125,12 +170,12 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { It "keeps the same database context" { # Before #8962 this changed the context to msdb - $null = $server.Databases['msdb'].Tables.Count - $server.ConnectionContext.ExecuteScalar("select db_name()") | Should -Be 'tempdb' + $null = $server.Databases["msdb"].Tables.Count + $server.ConnectionContext.ExecuteScalar("select db_name()") | Should -Be "tempdb" } } - if ($TestConfig.instance1 -match 'localhost') { + if ($TestConfig.instance1 -match "localhost") { Context "connection is properly made using a dot" { BeforeAll { $newinstance = $TestConfig.instance1.Replace("localhost", ".") @@ -146,16 +191,16 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { } It "keeps the same database context" { - $null = $server.Databases['msdb'].Tables.Count + $null = $server.Databases["msdb"].Tables.Count # This currently fails! - #$server.ConnectionContext.ExecuteScalar("select db_name()") | Should -Be 'tempdb' + #$server.ConnectionContext.ExecuteScalar("select db_name()") | Should -Be "tempdb" } } } Context "connection is properly made using a connection object" { BeforeAll { - Set-DbatoolsConfig -FullName commands.connect-dbainstance.smo.computername.source -Value 'instance.ComputerName' + Set-DbatoolsConfig -FullName commands.connect-dbainstance.smo.computername.source -Value "instance.ComputerName" [Microsoft.Data.SqlClient.SqlConnection]$sqlconnection = "Data Source=$($TestConfig.instance1);Initial Catalog=tempdb;Integrated Security=True;Encrypt=False;Trust Server Certificate=True" $server = Connect-DbaInstance -SqlInstance $sqlconnection Set-DbatoolsConfig -FullName commands.connect-dbainstance.smo.computername.source -Value $null @@ -170,9 +215,9 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { } It "keeps the same database context" { - $null = $server.Databases['msdb'].Tables.Count + $null = $server.Databases["msdb"].Tables.Count # This currently fails! - #$server.ConnectionContext.ExecuteScalar("select db_name()") | Should -Be 'tempdb' + #$server.ConnectionContext.ExecuteScalar("select db_name()") | Should -Be "tempdb" } } @@ -187,14 +232,14 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { It "clones when using parameter Database" { $serverClone = Connect-DbaInstance -SqlInstance $server -Database tempdb - $server.ConnectionContext.ExecuteScalar("select db_name()") | Should -Be 'master' - $serverClone.ConnectionContext.ExecuteScalar("select db_name()") | Should -Be 'tempdb' + $server.ConnectionContext.ExecuteScalar("select db_name()") | Should -Be "master" + $serverClone.ConnectionContext.ExecuteScalar("select db_name()") | Should -Be "tempdb" } It "clones when using parameter ApplicationIntent" { $serverClone = Connect-DbaInstance -SqlInstance $server -ApplicationIntent ReadOnly $server.ConnectionContext.ApplicationIntent | Should -BeNullOrEmpty - $serverClone.ConnectionContext.ApplicationIntent | Should -Be 'ReadOnly' + $serverClone.ConnectionContext.ApplicationIntent | Should -Be "ReadOnly" } It "clones when using parameter NonPooledConnection" { @@ -205,24 +250,30 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { It "clones when using parameter StatementTimeout" { $serverClone = Connect-DbaInstance -SqlInstance $server -StatementTimeout 123 - $server.ConnectionContext.StatementTimeout | Should -Be (Get-DbatoolsConfigValue -FullName 'sql.execution.timeout') + $server.ConnectionContext.StatementTimeout | Should -Be (Get-DbatoolsConfigValue -FullName "sql.execution.timeout") $serverClone.ConnectionContext.StatementTimeout | Should -Be 123 } It "clones when using parameter DedicatedAdminConnection" { $serverClone = Connect-DbaInstance -SqlInstance $server -DedicatedAdminConnection - $server.ConnectionContext.ServerInstance | Should -Not -Match '^ADMIN:' - $serverClone.ConnectionContext.ServerInstance | Should -Match '^ADMIN:' + $server.ConnectionContext.ServerInstance | Should -Not -Match "^ADMIN:" + $serverClone.ConnectionContext.ServerInstance | Should -Match "^ADMIN:" $serverClone | Disconnect-DbaInstance } It "clones when using Backup-DabInstace" { $server = Connect-DbaInstance -SqlInstance $TestConfig.instance1 -Database tempdb $results = Backup-DbaDatabase -SqlInstance $server -Database msdb - Remove-Item -Path $results.FullName + if ($results.FullName) { + Remove-Item -Path $results.FullName -ErrorAction SilentlyContinue + } + $results = Backup-DbaDatabase -SqlInstance $server -Database msdb -WarningVariable warn $warn | Should -BeNullOrEmpty - Remove-Item -Path $results.FullName + + if ($results.FullName) { + Remove-Item -Path $results.FullName -ErrorAction SilentlyContinue + } } } @@ -248,4 +299,4 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { $null = $server | Disconnect-DbaInstance } } -} +} \ No newline at end of file diff --git a/tests/Convert-DbaLsn.Tests.ps1 b/tests/Convert-DbaLsn.Tests.ps1 index 65108cbf282..2dd7cec5531 100644 --- a/tests/Convert-DbaLsn.Tests.ps1 +++ b/tests/Convert-DbaLsn.Tests.ps1 @@ -1,66 +1,62 @@ -#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } param( - $ModuleName = "dbatools", + $ModuleName = "dbatools", + $CommandName = "Convert-DbaLSN", $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults ) -Describe "Convert-DbaLSN" -Tag "UnitTests" { +Describe $CommandName -Tag UnitTests { Context "Parameter validation" { BeforeAll { - $command = Get-Command Convert-DbaLSN - $expected = $TestConfig.CommonParameters - $expected += @( + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( "LSN", "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 + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } Context "Converts Numeric LSN to Hex" { BeforeAll { - $LSN = '00000000020000000024300001' - $result = Convert-DbaLSN -Lsn $LSN + $numericLSN = "00000000020000000024300001" + $convertResults = Convert-DbaLSN -LSN $numericLSN } It "Should convert to 00000014:000000f3:0001" { - $result.Hexadecimal | Should -Be '00000014:000000f3:0001' + $convertResults.Hexadecimal | Should -Be "00000014:000000f3:0001" } } Context "Converts Numeric LSN to Hex without leading 0s" { BeforeAll { - $LSN = '20000000024300001' - $result = Convert-DbaLSN -Lsn $LSN + $shortLSN = "20000000024300001" + $shortResults = Convert-DbaLSN -LSN $shortLSN } It "Should convert to 00000014:000000f3:0001" { - $result.Hexadecimal | Should -Be '00000014:000000f3:0001' + $shortResults.Hexadecimal | Should -Be "00000014:000000f3:0001" } } Context "Converts Hex LSN to Numeric" { BeforeAll { - $LSN = '00000014:000000f3:0001' - $result = Convert-DbaLSN -Lsn $LSN + $hexLSN = "00000014:000000f3:0001" + $hexResults = Convert-DbaLSN -LSN $hexLSN } It "Should convert to 20000000024300001" { - $result.Numeric | Should -Be 20000000024300001 + $hexResults.Numeric | Should -Be 20000000024300001 } } } -<# - Integration test should appear below and are custom to the command you are writing. - Read https://github.com/dataplat/dbatools/blob/development/contributing.md#tests - for more guidance. -#> +# +# Integration test should appear below and are custom to the command you are writing. +# Read https://github.com/dataplat/dbatools/blob/development/contributing.md#tests +# for more guidance. +# \ No newline at end of file diff --git a/tests/Convert-DbaMaskingValue.Tests.ps1 b/tests/Convert-DbaMaskingValue.Tests.ps1 index f21519aed24..770455de172 100644 --- a/tests/Convert-DbaMaskingValue.Tests.ps1 +++ b/tests/Convert-DbaMaskingValue.Tests.ps1 @@ -1,15 +1,16 @@ #Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} param( - $ModuleName = "dbatools", + $ModuleName = "dbatools", + $CommandName = "Convert-DbaMaskingValue", $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults ) -Describe "Convert-DbaMaskingValue" -Tag "UnitTests" { +Describe $CommandName -Tag UnitTests { Context "Parameter validation" { BeforeAll { - $command = Get-Command Convert-DbaMaskingValue - $expected = $TestConfig.CommonParameters - $expected += @( + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( "Value", "DataType", "Nullable", @@ -17,30 +18,25 @@ Describe "Convert-DbaMaskingValue" -Tag "UnitTests" { ) } - 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 + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "Convert-DbaMaskingValue" -Tag "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { Context "Null values" { It "Should return a single 'NULL' value" { $value = $null $convertedValue = Convert-DbaMaskingValue -Value $value -Nullable:$true - $convertedValue.NewValue | Should -Be 'NULL' + $convertedValue.NewValue | Should -Be "NULL" } It "Should return multiple 'NULL' values" { $value = @($null, $null) $convertedValues = Convert-DbaMaskingValue -Value $value -Nullable:$true - $convertedValues[0].NewValue | Should -Be 'NULL' - $convertedValues[1].NewValue | Should -Be 'NULL' + $convertedValues[0].NewValue | Should -Be "NULL" + $convertedValues[1].NewValue | Should -Be "NULL" } } @@ -106,7 +102,7 @@ Describe "Convert-DbaMaskingValue" -Tag "IntegrationTests" { It "Should return a NULL value and text value" { $value = @($null, "this is just text") $convertedValues = Convert-DbaMaskingValue -Value $value -Nullable:$true - $convertedValues[0].NewValue | Should -Be 'NULL' + $convertedValues[0].NewValue | Should -Be "NULL" $convertedValues[1].NewValue | Should -Be "'this is just text'" } } @@ -120,4 +116,4 @@ Describe "Convert-DbaMaskingValue" -Tag "IntegrationTests" { { Convert-DbaMaskingValue -Value "whatever" -EnableException } | Should -Throw "Please enter a data type" } } -} +} \ No newline at end of file diff --git a/tests/ConvertTo-DbaDataTable.Tests.ps1 b/tests/ConvertTo-DbaDataTable.Tests.ps1 index dcb2f1eb1a0..35468356f52 100644 --- a/tests/ConvertTo-DbaDataTable.Tests.ps1 +++ b/tests/ConvertTo-DbaDataTable.Tests.ps1 @@ -1,69 +1,86 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "ConvertTo-DbaDataTable", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { +Describe $CommandName -Tag UnitTests { Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('WhatIf', 'Confirm') } - [object[]]$knownParameters = 'InputObject', 'TimeSpanType', 'SizeType', 'IgnoreNull', 'Raw', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should -Be 0 + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "InputObject", + "TimeSpanType", + "SizeType", + "IgnoreNull", + "Raw", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "Testing data table output when using a complex object" { - $obj = New-Object -TypeName psobject -Property @{ - guid = [system.guid]'32ccd4c4-282a-4c0d-997c-7b5deb97f9e0' - timespan = New-TimeSpan -Start 2016-10-30 -End 2017-04-30 - datetime = Get-Date -Year 2016 -Month 10 -Day 30 -Hour 5 -Minute 52 -Second 0 -Millisecond 0 - char = [System.Char]'T' - true = $true - false = $false - null = $null - string = "it's a boy." - UInt64 = [System.UInt64]123456 - dbadatetime = [dbadatetime[]]$(Get-Date -Year 2024 -Month 05 -Day 19 -Hour 5 -Minute 52 -Second 0 -Millisecond 0) - dbadatetimeArray = [dbadatetime[]]($(Get-Date -Year 2024 -Month 05 -Day 19 -Hour 5 -Minute 52 -Second 0 -Millisecond 0), $(Get-Date -Year 2024 -Month 05 -Day 19 -Hour 5 -Minute 52 -Second 0 -Millisecond 0).AddHours(1)) - inlining = [pscustomobject]@{Mission = 'Keep Hank alive'} - inlining2 = [psobject]@{Mission = 'Keep Hank alive'} - } +Describe $CommandName -Tag UnitTests, "DataTableOutput" { + BeforeAll { + $obj = New-Object -TypeName psobject -Property @{ + guid = [system.guid]"32ccd4c4-282a-4c0d-997c-7b5deb97f9e0" + timespan = New-TimeSpan -Start 2016-10-30 -End 2017-04-30 + datetime = Get-Date -Year 2016 -Month 10 -Day 30 -Hour 5 -Minute 52 -Second 0 -Millisecond 0 + char = [System.Char]"T" + true = $true + false = $false + null = $null + string = "it's a boy." + UInt64 = [System.UInt64]123456 + dbadatetime = [dbadatetime[]]$(Get-Date -Year 2024 -Month 05 -Day 19 -Hour 5 -Minute 52 -Second 0 -Millisecond 0) + dbadatetimeArray = [dbadatetime[]]($(Get-Date -Year 2024 -Month 05 -Day 19 -Hour 5 -Minute 52 -Second 0 -Millisecond 0), $(Get-Date -Year 2024 -Month 05 -Day 19 -Hour 5 -Minute 52 -Second 0 -Millisecond 0).AddHours(1)) + inlining = [PSCustomObject]@{Mission = "Keep Hank alive" } + inlining2 = [psobject]@{Mission = "Keep Hank alive" } + } - $innedobj = New-Object -TypeName psobject -Property @{ - Mission = 'Keep Hank alive' - } + $innedobj = New-Object -TypeName psobject -Property @{ + Mission = "Keep Hank alive" + } - Add-Member -Force -InputObject $obj -MemberType NoteProperty -Name myObject -Value $innedobj - $result = ConvertTo-DbaDataTable -InputObject $obj + Add-Member -Force -InputObject $obj -MemberType NoteProperty -Name myObject -Value $innedobj + $result = ConvertTo-DbaDataTable -InputObject $obj - $firstRow = $result[0].Rows[0] + $firstRow = $result[0].Rows[0] + } Context "Lengths" { - It 'Count of the Rows' { + It "Count of the Rows" { $result.Rows.Count | Should -Be 1 } } Context "Property: guid" { - It 'Has a column called "guid"' { - $result.Columns.ColumnName | Should -Contain 'guid' + It "Has a column called 'guid'" { + $result.Columns.ColumnName | Should -Contain "guid" } - It 'Has a [guid] data type on the column "guid"' { + It "Has a [guid] data type on the column 'guid'" { $firstRow.guid | Should -BeOfType [System.guid] } - It 'Has the following guid: "32ccd4c4-282a-4c0d-997c-7b5deb97f9e0"' { - $firstRow.guid | Should -Be '32ccd4c4-282a-4c0d-997c-7b5deb97f9e0' + It "Has the following guid: '32ccd4c4-282a-4c0d-997c-7b5deb97f9e0'" { + $firstRow.guid | Should -Be "32ccd4c4-282a-4c0d-997c-7b5deb97f9e0" } } Context "Property: timespan" { - It 'Has a column called "timespan"' { - $result.Columns.ColumnName | Should -Contain 'timespan' + It "Has a column called 'timespan'" { + $result.Columns.ColumnName | Should -Contain "timespan" } - It 'Has a [long] data type on the column "timespan"' { + It "Has a [long] data type on the column 'timespan'" { $firstRow.timespan | Should -BeOfType [System.Int64] - } It "Has the following timespan: 15724800000" { $firstRow.timespan | Should -Be 15724800000 @@ -71,10 +88,10 @@ Describe "Testing data table output when using a complex object" { } Context "Property: datetime" { - It 'Has a column called "datetime"' { - $result.Columns.ColumnName | Should -Contain 'datetime' + It "Has a column called 'datetime'" { + $result.Columns.ColumnName | Should -Contain "datetime" } - It 'Has a [datetime] data type on the column "datetime"' { + It "Has a [datetime] data type on the column 'datetime'" { $firstRow.datetime | Should -BeOfType [System.DateTime] } It "Has the following datetime: 2016-10-30 05:52:00.000" { @@ -84,10 +101,10 @@ Describe "Testing data table output when using a complex object" { } Context "Property: char" { - It 'Has a column called "char"' { - $result.Columns.ColumnName | Should -Contain 'char' + It "Has a column called 'char'" { + $result.Columns.ColumnName | Should -Contain "char" } - It 'Has a [char] data type on the column "char"' { + It "Has a [char] data type on the column 'char'" { $firstRow.char | Should -BeOfType [System.Char] } It "Has the following char: T" { @@ -96,10 +113,10 @@ Describe "Testing data table output when using a complex object" { } Context "Property: true" { - It 'Has a column called "true"' { - $result.Columns.ColumnName | Should -Contain 'true' + It "Has a column called 'true'" { + $result.Columns.ColumnName | Should -Contain "true" } - It 'Has a [bool] data type on the column "true"' { + It "Has a [bool] data type on the column 'true'" { $firstRow.true | Should -BeOfType [System.Boolean] } It "Has the following bool: true" { @@ -108,10 +125,10 @@ Describe "Testing data table output when using a complex object" { } Context "Property: false" { - It 'Has a column called "false"' { - $result.Columns.ColumnName | Should -Contain 'false' + It "Has a column called 'false'" { + $result.Columns.ColumnName | Should -Contain "false" } - It 'Has a [bool] data type on the column "false"' { + It "Has a [bool] data type on the column 'false'" { $firstRow.false | Should -BeOfType [System.Boolean] } It "Has the following bool: false" { @@ -120,10 +137,10 @@ Describe "Testing data table output when using a complex object" { } Context "Property: null" { - It 'Has a column called "null"' { - $result.Columns.ColumnName | Should -Contain 'null' + It "Has a column called 'null'" { + $result.Columns.ColumnName | Should -Contain "null" } - It 'Has a [null] data type on the column "null"' { + It "Has a [null] data type on the column 'null'" { $firstRow.null | Should -BeOfType [System.DBNull] } It "Has no value" { @@ -132,10 +149,10 @@ Describe "Testing data table output when using a complex object" { } Context "Property: string" { - It 'Has a column called "string"' { - $result.Columns.ColumnName | Should -Contain 'string' + It "Has a column called 'string'" { + $result.Columns.ColumnName | Should -Contain "string" } - It 'Has a [string] data type on the column "string"' { + It "Has a [string] data type on the column 'string'" { $firstRow.string | Should -BeOfType [System.String] } It "Has the following string: it's a boy." { @@ -144,10 +161,10 @@ Describe "Testing data table output when using a complex object" { } Context "Property: UInt64" { - It 'Has a column called "UInt64"' { - $result.Columns.ColumnName | Should -Contain 'UInt64' + It "Has a column called 'UInt64'" { + $result.Columns.ColumnName | Should -Contain "UInt64" } - It 'Has a [UInt64] data type on the column "UInt64"' { + It "Has a [UInt64] data type on the column 'UInt64'" { $firstRow.UInt64 | Should -BeOfType [System.UInt64] } It "Has the following number: 123456" { @@ -156,16 +173,16 @@ Describe "Testing data table output when using a complex object" { } Context "Property: myObject" { - It 'Has a column called "myObject"' { - $result.Columns.ColumnName | Should -Contain 'myObject' + It "Has a column called 'myObject'" { + $result.Columns.ColumnName | Should -Contain "myObject" } } Context "Property: dbadatetime" { - It 'Has a column called "dbadatetime"' { - $result.Columns.ColumnName | Should -Contain 'dbadatetime' + It "Has a column called 'dbadatetime'" { + $result.Columns.ColumnName | Should -Contain "dbadatetime" } - It 'Has a [System.String] data type on the column "myObject"' { + It "Has a [System.String] data type on the column 'myObject'" { $firstRow.dbadatetime | Should -BeOfType [System.String] } It "Has the following dbadatetime: 2024-05-19 05:52:00.000" { @@ -175,27 +192,29 @@ Describe "Testing data table output when using a complex object" { } Context "Property: dbadatetimeArray" { - It 'Has a column called "dbadatetimeArray"' { - $result.Columns.ColumnName | Should -Contain 'dbadatetimeArray' + It "Has a column called 'dbadatetimeArray'" { + $result.Columns.ColumnName | Should -Contain "dbadatetimeArray" } - It 'Has a [System.String] data type on the column "myObject"' { + It "Has a [System.String] data type on the column 'myObject'" { $firstRow.dbadatetimeArray | Should -BeOfType [System.String] } It "Has the following dbadatetimeArray converted to strings: 2024-05-19 05:52:00.000, 2024-05-19 06:52:00.000" { - $string = '2024-05-19 05:52:00.000, 2024-05-19 06:52:00.000' + $string = "2024-05-19 05:52:00.000, 2024-05-19 06:52:00.000" $firstRow.dbadatetimeArray -eq $string | Should -Be $true } } } -Describe "Testing input parameters" { - $obj = New-Object -TypeName psobject -Property @{ - timespan = New-TimeSpan -Start 2017-01-01 -End 2017-01-02 +Describe $CommandName -Tag UnitTests, "InputParameters" { + BeforeAll { + $obj = New-Object -TypeName psobject -Property @{ + timespan = New-TimeSpan -Start 2017-01-01 -End 2017-01-02 + } } Context "Verifying TimeSpanType" { It "Should return '1.00:00:00' when String is used" { - (ConvertTo-DbaDataTable -InputObject $obj -TimeSpanType String).Timespan | Should -Be '1.00:00:00' + (ConvertTo-DbaDataTable -InputObject $obj -TimeSpanType String).Timespan | Should -Be "1.00:00:00" } It "Should return 864000000000 when Ticks is used" { (ConvertTo-DbaDataTable -InputObject $obj -TimeSpanType Ticks).Timespan | Should -Be 864000000000 @@ -218,19 +237,21 @@ Describe "Testing input parameters" { } Context "Verifying IgnoreNull" { - # To be able to force null - function returnnull { - [CmdletBinding()] - param () - New-Object -TypeName psobject -Property @{ Name = [int]1 } - $null - New-Object -TypeName psobject -Property @{ Name = [int]3 } - } - - function returnOnlynull { - [CmdletBinding()] - param () - $null + BeforeAll { + # To be able to force null + function returnnull { + [CmdletBinding()] + param () + New-Object -TypeName psobject -Property @{ Name = [int]1 } + $null + New-Object -TypeName psobject -Property @{ Name = [int]3 } + } + + function returnOnlynull { + [CmdletBinding()] + param () + $null + } } It "Does not create row if null is in array when IgnoreNull is set" { @@ -259,11 +280,13 @@ Describe "Testing input parameters" { } Context "Verifying Silent" { - # To be able to force null - function returnnull { - New-Object -TypeName psobject -Property @{ Name = 1 } - $null - New-Object -TypeName psobject -Property @{ Name = 3 } + BeforeAll { + # To be able to force null + function returnnull { + New-Object -TypeName psobject -Property @{ Name = 1 } + $null + New-Object -TypeName psobject -Property @{ Name = 3 } + } } It "Suppresses warning messages when Silent is used" { @@ -273,27 +296,28 @@ Describe "Testing input parameters" { } Context "Verifying script properties returning null" { - It "Returns string column if a script property returns null" { - $myobj = New-Object -TypeName psobject -Property @{ Name = 'Test' } + $myobj = New-Object -TypeName psobject -Property @{ Name = "Test" } $myobj | Add-Member -Force -MemberType ScriptProperty -Name ScriptNothing -Value { $null } $r = ConvertTo-DbaDataTable -InputObject $myobj - ($r.Columns | Where-Object ColumnName -eq ScriptNothing | Select-Object -ExpandProperty DataType).ToString() | Should -Be 'System.String' - + ($r.Columns | Where-Object ColumnName -eq ScriptNothing | Select-Object -ExpandProperty DataType).ToString() | Should -Be "System.String" } } Context "Verifying a datatable gets cloned when passed in" { - $obj = New-Object -TypeName psobject -Property @{ - col1 = 'col1' - col2 = 'col2' + BeforeAll { + $obj = New-Object -TypeName psobject -Property @{ + col1 = "col1" + col2 = "col2" + } + $first = $obj | ConvertTo-DbaDataTable + $second = $first | ConvertTo-DbaDataTable } - $first = $obj | ConvertTo-DbaDataTable - $second = $first | ConvertTo-DbaDataTable + It "Should have the same columns" { # does not add ugly RowError,RowState Table, ItemArray, HasErrors - $firstColumns = ($first.Columns.ColumnName | Sort-Object) -Join ',' - $secondColumns = ($second.Columns.ColumnName | Sort-Object) -Join ',' + $firstColumns = ($first.Columns.ColumnName | Sort-Object) -Join "," + $secondColumns = ($second.Columns.ColumnName | Sort-Object) -Join "," $firstColumns | Should -Be $secondColumns } } diff --git a/tests/ConvertTo-DbaTimeline.Tests.ps1 b/tests/ConvertTo-DbaTimeline.Tests.ps1 index b2feda33952..851822a08cd 100644 --- a/tests/ConvertTo-DbaTimeline.Tests.ps1 +++ b/tests/ConvertTo-DbaTimeline.Tests.ps1 @@ -1,28 +1,24 @@ -#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } param( - $ModuleName = "dbatools", - $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults + $ModuleName = "dbatools", + $CommandName = "ConvertTo-DbaTimeline", + $PSDefaultParameterValues = $TestConfig.Defaults ) -Describe "ConvertTo-DbaTimeline" -Tag "UnitTests" { +Describe $CommandName -Tag UnitTests { Context "Parameter validation" { BeforeAll { - $command = Get-Command ConvertTo-DbaTimeline - $expected = $TestConfig.CommonParameters - $expected += @( + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( "InputObject", "ExcludeRowLabel", "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 + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } @@ -31,4 +27,4 @@ Describe "ConvertTo-DbaTimeline" -Tag "UnitTests" { Integration test should appear below and are custom to the command you are writing. Read https://github.com/dataplat/dbatools/blob/development/contributing.md#tests for more guidance. -#> +#> \ No newline at end of file diff --git a/tests/ConvertTo-DbaXESession.Tests.ps1 b/tests/ConvertTo-DbaXESession.Tests.ps1 index 5022d184b56..e6a00921bbb 100644 --- a/tests/ConvertTo-DbaXESession.Tests.ps1 +++ b/tests/ConvertTo-DbaXESession.Tests.ps1 @@ -1,15 +1,16 @@ -#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } param( - $ModuleName = "dbatools", - $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults + $ModuleName = "dbatools", + $CommandName = "ConvertTo-DbaXESession", + $PSDefaultParameterValues = $TestConfig.Defaults ) -Describe "ConvertTo-DbaXESession" -Tag "UnitTests" { +Describe $CommandName -Tag UnitTests { Context "Parameter validation" { BeforeAll { - $command = Get-Command ConvertTo-DbaXESession - $expected = $TestConfig.CommonParameters - $expected += @( + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( "InputObject", "Name", "OutputScriptOnly", @@ -17,19 +18,17 @@ Describe "ConvertTo-DbaXESession" -Tag "UnitTests" { ) } - 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 + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "ConvertTo-DbaXESession" -Tag "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true + $sql = @" -- Create a Queue declare @rc int @@ -109,21 +108,48 @@ exec sp_trace_setstatus @TraceID, 1 -- display trace id for future references select TraceID=@TraceID "@ - $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 + $splatConnect = @{ + SqlInstance = $TestConfig.instance2 + } + $server = Connect-DbaInstance @splatConnect $traceid = ($server.Query($sql)).TraceID $sessionName = "dbatoolsci-session" + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove("*-Dba*:EnableException") } AfterAll { - $null = Remove-DbaXESession -SqlInstance $TestConfig.instance2 -Session $sessionName - $null = Remove-DbaTrace -SqlInstance $TestConfig.instance2 -Id $traceid + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true + + $splatRemoveSession = @{ + SqlInstance = $TestConfig.instance2 + Session = $sessionName + } + $null = Remove-DbaXESession @splatRemoveSession + $splatRemoveTrace = @{ + SqlInstance = $TestConfig.instance2 + Id = $traceid + } + $null = Remove-DbaTrace @splatRemoveTrace Remove-Item C:\windows\temp\temptrace.trc -ErrorAction SilentlyContinue + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } Context "Test Trace Conversion" { BeforeAll { - $null = Get-DbaTrace -SqlInstance $TestConfig.instance2 -Id $traceid | ConvertTo-DbaXESession -Name $sessionName - $results = Start-DbaXESession -SqlInstance $TestConfig.instance2 -Session $sessionName + $splatGetTrace = @{ + SqlInstance = $TestConfig.instance2 + Id = $traceid + } + $null = Get-DbaTrace @splatGetTrace | ConvertTo-DbaXESession -Name $sessionName + $splatStartSession = @{ + SqlInstance = $TestConfig.instance2 + Session = $sessionName + } + $results = Start-DbaXESession @splatStartSession } It "Returns the right results" { @@ -132,4 +158,4 @@ select TraceID=@TraceID $results.Targets.Name | Should -Be "package0.event_file" } } -} +} \ No newline at end of file diff --git a/tests/Copy-DbaAgentAlert.Tests.ps1 b/tests/Copy-DbaAgentAlert.Tests.ps1 index 075cfffb58b..370ea11b44e 100644 --- a/tests/Copy-DbaAgentAlert.Tests.ps1 +++ b/tests/Copy-DbaAgentAlert.Tests.ps1 @@ -1,15 +1,16 @@ -#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } param( - $ModuleName = "dbatools", - $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults + $ModuleName = "dbatools", + $CommandName = "Copy-DbaAgentAlert", + $PSDefaultParameterValues = $TestConfig.Defaults ) -Describe "Copy-DbaAgentAlert" -Tag "UnitTests" { +Describe $CommandName -Tag UnitTests { Context "Parameter validation" { BeforeAll { - $command = Get-Command Copy-DbaAgentAlert - $expected = $TestConfig.CommonParameters - $expected += @( + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( "Source", "SourceSqlCredential", "Destination", @@ -18,32 +19,31 @@ Describe "Copy-DbaAgentAlert" -Tag "UnitTests" { "ExcludeAlert", "IncludeDefaults", "Force", - "EnableException", - "Confirm", - "WhatIf" + "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 + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "Copy-DbaAgentAlert" -Tag "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { - $alert1 = 'dbatoolsci test alert' - $alert2 = 'dbatoolsci test alert 2' - $operatorName = 'Dan the man Levitan' - $operatorEmail = 'levitan@dbatools.io' - $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 -Database master + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # Set variables for test alerts and operator + $alert1 = "dbatoolsci test alert" + $alert2 = "dbatoolsci test alert 2" + $operatorName = "Dan the man Levitan" + $operatorEmail = "levitan@dbatools.io" - $server.Query("EXEC msdb.dbo.sp_add_alert @name=N'$($alert1)', + # Connect to instance and create test objects + $serverInstance2 = Connect-DbaInstance -SqlInstance $TestConfig.instance2 -Database master + + $serverInstance2.Query("EXEC msdb.dbo.sp_add_alert @name=N'$($alert1)', @message_id=0, @severity=6, @enabled=1, @@ -52,7 +52,7 @@ Describe "Copy-DbaAgentAlert" -Tag "IntegrationTests" { @category_name=N'[Uncategorized]', @job_id=N'00000000-0000-0000-0000-000000000000';") - $server.Query("EXEC msdb.dbo.sp_add_alert @name=N'$($alert2)', + $serverInstance2.Query("EXEC msdb.dbo.sp_add_alert @name=N'$($alert2)', @message_id=0, @severity=10, @enabled=1, @@ -60,64 +60,74 @@ Describe "Copy-DbaAgentAlert" -Tag "IntegrationTests" { @include_event_description_in=0, @job_id=N'00000000-0000-0000-0000-000000000000';") - $server.Query("EXEC msdb.dbo.sp_add_operator + $serverInstance2.Query("EXEC msdb.dbo.sp_add_operator @name = N'$operatorName', @enabled = 1, @email_address = N'$operatorEmail' ;") - $server.Query("EXEC msdb.dbo.sp_add_notification @alert_name = N'$($alert2)', + + $serverInstance2.Query("EXEC msdb.dbo.sp_add_notification @alert_name = N'$($alert2)', @operator_name = N'$operatorName', @notification_method = 1 ;") + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } AfterAll { - $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 -Database master - $server.Query("EXEC msdb.dbo.sp_delete_alert @name=N'$($alert1)'") - $server.Query("EXEC msdb.dbo.sp_delete_alert @name=N'$($alert2)'") - $server.Query("EXEC msdb.dbo.sp_delete_operator @name = '$($operatorName)'") + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # Clean up test objects + $serverCleanup2 = Connect-DbaInstance -SqlInstance $TestConfig.instance2 -Database master + $serverCleanup2.Query("EXEC msdb.dbo.sp_delete_alert @name=N'$($alert1)'") + $serverCleanup2.Query("EXEC msdb.dbo.sp_delete_alert @name=N'$($alert2)'") + $serverCleanup2.Query("EXEC msdb.dbo.sp_delete_operator @name = '$($operatorName)'") - $server = Connect-DbaInstance -SqlInstance $TestConfig.instance3 -Database master - $server.Query("EXEC msdb.dbo.sp_delete_alert @name=N'$($alert1)'") + $serverCleanup3 = Connect-DbaInstance -SqlInstance $TestConfig.instance3 -Database master + $serverCleanup3.Query("EXEC msdb.dbo.sp_delete_alert @name=N'$($alert1)'") + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } Context "When copying alerts" { It "Copies the sample alert" { - $splat = @{ + $splatCopyAlert = @{ Source = $TestConfig.instance2 Destination = $TestConfig.instance3 Alert = $alert1 } - $results = Copy-DbaAgentAlert @splat - $results.Name | Should -Be 'dbatoolsci test alert', 'dbatoolsci test alert' - $results.Type | Should -Be 'Agent Alert', 'Agent Alert Notification' - $results.Status | Should -Be 'Successful', 'Successful' + $results = Copy-DbaAgentAlert @splatCopyAlert + $results.Name | Should -Be "dbatoolsci test alert", "dbatoolsci test alert" + $results.Type | Should -Be "Agent Alert", "Agent Alert Notification" + $results.Status | Should -Be "Successful", "Successful" } It "Skips alerts where destination is missing the operator" { - $splatDupe = @{ + $splatCopySkip = @{ Source = $TestConfig.instance2 Destination = $TestConfig.instance3 Alert = $alert2 - WarningAction = 'SilentlyContinue' + WarningAction = "SilentlyContinue" } - $results = Copy-DbaAgentAlert @splatDupe - $results.Status | Should -Be Skipped - $results.Type | Should -Be 'Agent Alert' + $results = Copy-DbaAgentAlert @splatCopySkip + $results.Status | Should -Be "Skipped" + $results.Type | Should -Be "Agent Alert" } It "Doesn't overwrite existing alerts" { - $splat = @{ + $splatCopyExisting = @{ Source = $TestConfig.instance2 Destination = $TestConfig.instance3 Alert = $alert1 } - $results = Copy-DbaAgentAlert @splat - $results.Name | Should -Be 'dbatoolsci test alert' - $results.Status | Should -Be 'Skipped' + $results = Copy-DbaAgentAlert @splatCopyExisting + $results.Name | Should -Be "dbatoolsci test alert" + $results.Status | Should -Be "Skipped" } It "The newly copied alert exists" { $results = Get-DbaAgentAlert -SqlInstance $TestConfig.instance2 - $results.Name | Should -Contain 'dbatoolsci test alert' + $results.Name | Should -Contain "dbatoolsci test alert" } } -} +} \ No newline at end of file diff --git a/tests/Copy-DbaAgentJob.Tests.ps1 b/tests/Copy-DbaAgentJob.Tests.ps1 index 9e466da0132..d30dc27871e 100644 --- a/tests/Copy-DbaAgentJob.Tests.ps1 +++ b/tests/Copy-DbaAgentJob.Tests.ps1 @@ -1,26 +1,57 @@ -#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } param( - $ModuleName = "dbatools", + $ModuleName = "dbatools", + $CommandName = "Copy-DbaAgentJob", $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults ) -Describe "Copy-DbaAgentJob" -Tag "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { - $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_copyjob - $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_copyjob_disabled + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true + + # For all the backups that we want to clean up after the test, we create a directory that we can delete at the end. + # Other files can be written there as well, maybe we change the name of that variable later. But for now we focus on backups. + $backupPath = "$($TestConfig.Temp)\$CommandName-$(Get-Random)" + $null = New-Item -Path $backupPath -ItemType Directory + + # Explain what needs to be set up for the test: + # To test copying agent jobs, we need to create test jobs on the source instance that can be copied to the destination + + # Set variables. They are available in all the It blocks. + $sourceJobName = "dbatoolsci_copyjob" + $sourceJobDisabledName = "dbatoolsci_copyjob_disabled" + + # Create the objects. + $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job $sourceJobName + $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job $sourceJobDisabledName $sourcejobs = Get-DbaAgentJob -SqlInstance $TestConfig.instance2 $destjobs = Get-DbaAgentJob -SqlInstance $TestConfig.instance3 + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove("*-Dba*:EnableException") } + AfterAll { - $null = Remove-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_copyjob, dbatoolsci_copyjob_disabled -Confirm:$false - $null = Remove-DbaAgentJob -SqlInstance $TestConfig.instance3 -Job dbatoolsci_copyjob, dbatoolsci_copyjob_disabled -Confirm:$false + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true + + # Cleanup all created objects. + $null = Remove-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_copyjob, dbatoolsci_copyjob_disabled -Confirm:$false -ErrorAction SilentlyContinue + $null = Remove-DbaAgentJob -SqlInstance $TestConfig.instance3 -Job dbatoolsci_copyjob, dbatoolsci_copyjob_disabled -Confirm:$false -ErrorAction SilentlyContinue + + # Remove the backup directory. + Remove-Item -Path $backupPath -Recurse -ErrorAction SilentlyContinue + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } Context "Parameter validation" { BeforeAll { - $command = Get-Command Copy-DbaAgentJob - $expected = $TestConfig.CommonParameters - $expected += @( + $command = Get-Command $CommandName + $hasParameters = $command.Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( "Source", "SourceSqlCredential", "Destination", @@ -31,19 +62,12 @@ Describe "Copy-DbaAgentJob" -Tag "IntegrationTests" { "DisableOnDestination", "Force", "InputObject", - "EnableException", - "Confirm", - "WhatIf" + "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 + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } @@ -63,12 +87,12 @@ Describe "Copy-DbaAgentJob" -Tag "IntegrationTests" { It "disables jobs when requested" { $splatCopyJob = @{ - Source = $TestConfig.instance2 - Destination = $TestConfig.instance3 - Job = "dbatoolsci_copyjob_disabled" - DisableOnSource = $true + Source = $TestConfig.instance2 + Destination = $TestConfig.instance3 + Job = "dbatoolsci_copyjob_disabled" + DisableOnSource = $true DisableOnDestination = $true - Force = $true + Force = $true } $results = Copy-DbaAgentJob @splatCopyJob @@ -78,4 +102,4 @@ Describe "Copy-DbaAgentJob" -Tag "IntegrationTests" { (Get-DbaAgentJob -SqlInstance $TestConfig.instance3 -Job dbatoolsci_copyjob_disabled).Enabled | Should -BeFalse } } -} +} \ No newline at end of file diff --git a/tests/Copy-DbaAgentJobCategory.Tests.ps1 b/tests/Copy-DbaAgentJobCategory.Tests.ps1 index 241c5455373..5b3d51056cf 100644 --- a/tests/Copy-DbaAgentJobCategory.Tests.ps1 +++ b/tests/Copy-DbaAgentJobCategory.Tests.ps1 @@ -1,24 +1,38 @@ -#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } param( - $ModuleName = "dbatools", - $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults + $ModuleName = "dbatools", + $CommandName = "Copy-DbaAgentJobCategory", + $PSDefaultParameterValues = $TestConfig.Defaults ) -Describe "Copy-DbaAgentJobCategory" -Tag "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { - $null = New-DbaAgentJobCategory -SqlInstance $TestConfig.instance2 -Category 'dbatoolsci test category' + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true + + # Set up test category for the integration tests + $null = New-DbaAgentJobCategory -SqlInstance $TestConfig.instance2 -Category "dbatoolsci test category" + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove("*-Dba*:EnableException") } + AfterAll { - $null = Remove-DbaAgentJobCategory -SqlInstance $TestConfig.instance2 -Category 'dbatoolsci test category' -Confirm:$false - $null = Remove-DbaAgentJobCategory -SqlInstance $TestConfig.instance3 -Category 'dbatoolsci test category' -Confirm:$false + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true + + # Cleanup all created categories + $null = Remove-DbaAgentJobCategory -SqlInstance $TestConfig.instance2 -Category "dbatoolsci test category" -Confirm:$false + $null = Remove-DbaAgentJobCategory -SqlInstance $TestConfig.instance3 -Category "dbatoolsci test category" -Confirm:$false + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } Context "Parameter validation" { BeforeAll { - $command = Get-Command Copy-DbaAgentJobCategory - - $expected = $TestConfig.CommonParameters - $expected += @( + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( "Source", "SourceSqlCredential", "Destination", @@ -28,31 +42,24 @@ Describe "Copy-DbaAgentJobCategory" -Tag "IntegrationTests" { "AgentCategory", "OperatorCategory", "Force", - "EnableException", - "Confirm", - "WhatIf" + "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 + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } Context "When copying job categories" { It "Returns successful results" { - $splat = @{ + $splatCopyCategory = @{ Source = $TestConfig.instance2 Destination = $TestConfig.instance3 JobCategory = "dbatoolsci test category" } - $results = Copy-DbaAgentJobCategory @splat + $results = Copy-DbaAgentJobCategory @splatCopyCategory $results.Name | Should -Be "dbatoolsci test category" $results.Status | Should -Be "Successful" } @@ -69,4 +76,4 @@ Describe "Copy-DbaAgentJobCategory" -Tag "IntegrationTests" { $secondCopyResults.Status | Should -Be "Skipped" } } -} +} \ No newline at end of file diff --git a/tests/Copy-DbaAgentOperator.Tests.ps1 b/tests/Copy-DbaAgentOperator.Tests.ps1 index 846e46d8b17..50d80bf46b7 100644 --- a/tests/Copy-DbaAgentOperator.Tests.ps1 +++ b/tests/Copy-DbaAgentOperator.Tests.ps1 @@ -1,15 +1,16 @@ -#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } param( - $ModuleName = "dbatools", - $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults + $ModuleName = "dbatools", + $CommandName = "Copy-DbaAgentOperator", + $PSDefaultParameterValues = $TestConfig.Defaults ) -Describe "Copy-DbaAgentOperator" -Tag "UnitTests" { +Describe $CommandName -Tag UnitTests { Context "Parameter validation" { BeforeAll { - $command = Get-Command Copy-DbaAgentOperator - $expected = $TestConfig.CommonParameters - $expected += @( + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( "Source", "SourceSqlCredential", "Destination", @@ -17,65 +18,76 @@ Describe "Copy-DbaAgentOperator" -Tag "UnitTests" { "Operator", "ExcludeOperator", "Force", - "EnableException", - "Confirm", - "WhatIf" + "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 + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "Copy-DbaAgentOperator" -Tag "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { - $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 - $sql = "EXEC msdb.dbo.sp_add_operator @name=N'dbatoolsci_operator', @enabled=1, @pager_days=0" - $server.Query($sql) - $sql = "EXEC msdb.dbo.sp_add_operator @name=N'dbatoolsci_operator2', @enabled=1, @pager_days=0" - $server.Query($sql) + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true + + # Set variables. They are available in all the It blocks. + $operatorName1 = "dbatoolsci_operator" + $operatorName2 = "dbatoolsci_operator2" + + # Create the operators on the source server. + $sourceServer = Connect-DbaInstance -SqlInstance $TestConfig.instance2 + $sqlAddOperator1 = "EXEC msdb.dbo.sp_add_operator @name=N'$operatorName1', @enabled=1, @pager_days=0" + $null = $sourceServer.Query($sqlAddOperator1) + $sqlAddOperator2 = "EXEC msdb.dbo.sp_add_operator @name=N'$operatorName2', @enabled=1, @pager_days=0" + $null = $sourceServer.Query($sqlAddOperator2) + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove("*-Dba*:EnableException") } AfterAll { - $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 - $sql = "EXEC msdb.dbo.sp_delete_operator @name=N'dbatoolsci_operator'" - $server.Query($sql) - $sql = "EXEC msdb.dbo.sp_delete_operator @name=N'dbatoolsci_operator2'" - $server.Query($sql) + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true + + # Cleanup all created objects. + $sourceCleanupServer = Connect-DbaInstance -SqlInstance $TestConfig.instance2 -ErrorAction SilentlyContinue + $sqlDeleteOp1Source = "EXEC msdb.dbo.sp_delete_operator @name=N'$operatorName1'" + $null = $sourceCleanupServer.Query($sqlDeleteOp1Source) + $sqlDeleteOp2Source = "EXEC msdb.dbo.sp_delete_operator @name=N'$operatorName2'" + $null = $sourceCleanupServer.Query($sqlDeleteOp2Source) - $server = Connect-DbaInstance -SqlInstance $TestConfig.instance3 - $sql = "EXEC msdb.dbo.sp_delete_operator @name=N'dbatoolsci_operator'" - $server.Query($sql) - $sql = "EXEC msdb.dbo.sp_delete_operator @name=N'dbatoolsci_operator2'" - $server.Query($sql) + $destCleanupServer = Connect-DbaInstance -SqlInstance $TestConfig.instance3 -ErrorAction SilentlyContinue + $sqlDeleteOp1Dest = "EXEC msdb.dbo.sp_delete_operator @name=N'$operatorName1'" + $null = $destCleanupServer.Query($sqlDeleteOp1Dest) + $sqlDeleteOp2Dest = "EXEC msdb.dbo.sp_delete_operator @name=N'$operatorName2'" + $null = $destCleanupServer.Query($sqlDeleteOp2Dest) + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } Context "When copying operators" { It "Returns two copied operators" { - $splat = @{ + $splatCopyOperators = @{ Source = $TestConfig.instance2 Destination = $TestConfig.instance3 - Operator = 'dbatoolsci_operator', 'dbatoolsci_operator2' + Operator = @($operatorName1, $operatorName2) } - $results = Copy-DbaAgentOperator @splat + $results = Copy-DbaAgentOperator @splatCopyOperators $results.Status.Count | Should -Be 2 - $results.Status | Should -Be "Successful", "Successful" + $results.Status | Should -Be @("Successful", "Successful") } It "Returns one result that's skipped when copying an existing operator" { - $splet = @{ + $splatCopyExisting = @{ Source = $TestConfig.instance2 Destination = $TestConfig.instance3 - Operator = 'dbatoolsci_operator' + Operator = $operatorName1 } - (Copy-DbaAgentOperator @splet).Status | Should -Be "Skipped" + $copyResult = Copy-DbaAgentOperator @splatCopyExisting + $copyResult.Status | Should -Be "Skipped" } } -} +} \ No newline at end of file diff --git a/tests/Find-DbaUserObject.Tests.ps1 b/tests/Find-DbaUserObject.Tests.ps1 index 81c8741f000..fecd9acd965 100644 --- a/tests/Find-DbaUserObject.Tests.ps1 +++ b/tests/Find-DbaUserObject.Tests.ps1 @@ -1,39 +1,63 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Find-DbaUserObject", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Pattern', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Pattern", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { Context "Command finds User Objects for SA" { BeforeAll { - $null = New-DbaDatabase -SqlInstance $TestConfig.instance2 -Name 'dbatoolsci_userObject' -Owner 'sa' + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + $null = New-DbaDatabase -SqlInstance $TestConfig.instance2 -Name "dbatoolsci_userObject" -Owner "sa" + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') + + $results = Find-DbaUserObject -SqlInstance $TestConfig.instance2 -Pattern "sa" } + AfterAll { - $null = Remove-DbaDatabase -SqlInstance $TestConfig.instance2 -Database 'dbatoolsci_userObject' -Confirm:$false + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + $null = Remove-DbaDatabase -SqlInstance $TestConfig.instance2 -Database "dbatoolsci_userObject" -Confirm:$false } - $results = Find-DbaUserObject -SqlInstance $TestConfig.instance2 -Pattern sa It "Should find a specific Database Owned by sa" { - $results.Where( {$_.name -eq 'dbatoolsci_userobject'}).Type | Should Be "Database" + $results.Where( { $PSItem.name -eq "dbatoolsci_userobject" }).Type | Should -Be "Database" } + It "Should find more than 10 objects Owned by sa" { - $results.Count | Should BeGreaterThan 10 + $results.Count | Should -BeGreaterThan 10 } } + Context "Command finds User Objects" { - $results = Find-DbaUserObject -SqlInstance $TestConfig.instance2 - It "Should find resutls" { - $results | Should Not Be Null + BeforeAll { + $results = Find-DbaUserObject -SqlInstance $TestConfig.instance2 + } + + It "Should find results" { + $results | Should -Not -BeNull } } -} +} \ No newline at end of file