From 30f3a743ab03b08dec0cbdcf2a21efcddaf108de Mon Sep 17 00:00:00 2001 From: Chrissy LeMaire Date: Sun, 20 Oct 2024 18:23:38 +0200 Subject: [PATCH] first batch --- tests/Add-DbaAgDatabase.Tests.ps1 | 80 ++++--- tests/Add-DbaAgListener.Tests.ps1 | 69 +++--- tests/Add-DbaAgReplica.Tests.ps1 | 103 ++++++--- tests/Add-DbaComputerCertificate.Tests.ps1 | 51 +++-- tests/Add-DbaDbMirrorMonitor.Tests.ps1 | 51 +++-- tests/Add-DbaDbRoleMember.Tests.ps1 | 111 ++++----- tests/Add-DbaExtendedProperty.Tests.ps1 | 59 +++-- tests/Add-DbaPfDataCollectorCounter.Tests.ps1 | 66 ++++-- tests/Add-DbaRegServer.Tests.ps1 | 57 +++-- tests/Add-DbaRegServerGroup.Tests.ps1 | 61 +++-- tests/Add-DbaReplArticle.Tests.ps1 | 36 ++- tests/Add-DbaServerRoleMember.Tests.ps1 | 81 ++++--- tests/Backup-DbaComputerCertificate.Tests.ps1 | 44 ++-- tests/Backup-DbaDbCertificate.Tests.ps1 | 67 +++--- tests/Backup-DbaDbMasterKey.Tests.ps1 | 60 +++-- tests/Backup-DbaServiceMasterKey.Tests.ps1 | 46 ++-- tests/Clear-DbaConnectionPool.Tests.ps1 | 35 +-- tests/Clear-DbaLatchStatistics.Tests.ps1 | 41 ++-- tests/Clear-DbaPlanCache.Tests.ps1 | 50 +++-- tests/Clear-DbaWaitStatistics.Tests.ps1 | 37 +-- tests/Convert-DbaLsn.Tests.ps1 | 51 ++--- tests/Convert-DbaMaskingValue.Tests.ps1 | 106 ++++----- tests/ConvertTo-DbaTimeline.Tests.ps1 | 30 ++- tests/ConvertTo-DbaXESession.Tests.ps1 | 210 +++++++++--------- tests/Copy-DbaAgentAlert.Tests.ps1 | 148 ++++++------ tests/Copy-DbaAgentJob.Tests.ps1 | 68 +++--- tests/Copy-DbaAgentJobCategory.Tests.ps1 | 64 +++--- tests/Copy-DbaAgentOperator.Tests.ps1 | 86 +++---- tests/Copy-DbaAgentProxy.Tests.ps1 | 100 +++++---- tests/Copy-DbaAgentSchedule.Tests.ps1 | 78 ++++--- tests/Copy-DbaAgentServer.Tests.ps1 | 38 +++- tests/Copy-DbaBackupDevice.Tests.ps1 | 93 ++++---- tests/Copy-DbaCredential.Tests.ps1 | 163 +++++++------- tests/Copy-DbaCustomError.Tests.ps1 | 87 +++++--- tests/Copy-DbaDataCollector.Tests.ps1 | 42 ++-- tests/Copy-DbaDbCertificate.Tests.ps1 | 70 +++--- tests/Copy-DbaDbMail.Tests.ps1 | 169 +++++++------- tests/Copy-DbaDbQueryStoreOption.Tests.ps1 | 47 ++-- tests/Copy-DbaDbTableData.Tests.ps1 | 144 ++++++------ tests/Copy-DbaEndpoint.Tests.ps1 | 63 +++--- tests/Copy-DbaInstanceAudit.Tests.ps1 | 38 +++- ...py-DbaInstanceAuditSpecification.Tests.ps1 | 41 +++- tests/Copy-DbaInstanceTrigger.Tests.ps1 | 52 +++-- tests/Copy-DbaLinkedServer.Tests.ps1 | 101 +++++---- tests/Copy-DbaPolicyManagement.Tests.ps1 | 39 +++- tests/Copy-DbaRegServer.Tests.ps1 | 48 ++-- tests/Copy-DbaResourceGovernor.Tests.ps1 | 150 +++++++------ tests/Copy-DbaSpConfigure.Tests.ps1 | 72 +++--- tests/Copy-DbaSsisCatalog.Tests.ps1 | 40 +++- tests/Copy-DbaStartupProcedure.Tests.ps1 | 83 +++---- tests/Copy-DbaSystemDbUserObject.Tests.ps1 | 91 ++++---- tests/Copy-DbaXESession.Tests.ps1 | 37 ++- tests/Copy-DbaXESessionTemplate.Tests.ps1 | 38 ++-- tests/Disable-DbaAgHadr.Tests.ps1 | 51 +++-- tests/Disable-DbaDbEncryption.Tests.ps1 | 103 +++++---- tests/Disable-DbaFilestream.Tests.ps1 | 45 ++-- ...isable-DbaForceNetworkEncryption.Tests.ps1 | 41 ++-- tests/Disable-DbaHideInstance.Tests.ps1 | 41 ++-- tests/Disable-DbaReplDistributor.Tests.ps1 | 33 ++- tests/Disable-DbaReplPublishing.Tests.ps1 | 31 ++- tests/Disable-DbaStartupProcedure.Tests.ps1 | 111 ++++----- tests/Disable-DbaTraceFlag.Tests.ps1 | 43 ++-- tests/Disconnect-DbaInstance.Tests.ps1 | 39 ++-- tests/Dismount-DbaDatabase.Tests.ps1 | 141 ++++++------ tests/Enable-DbaAgHadr.Tests.ps1 | 48 ++-- tests/Enable-DbaDbEncryption.Tests.ps1 | 99 +++++---- tests/Enable-DbaFilestream.Tests.ps1 | 63 +++--- ...Enable-DbaForceNetworkEncryption.Tests.ps1 | 41 ++-- tests/Enable-DbaHideInstance.Tests.ps1 | 48 ++-- tests/Enable-DbaReplDistributor.Tests.ps1 | 33 ++- tests/Enable-DbaReplPublishing.Tests.ps1 | 34 ++- tests/Enable-DbaStartupProcedure.Tests.ps1 | 105 ++++----- tests/Enable-DbaTraceFlag.Tests.ps1 | 53 +++-- 73 files changed, 2954 insertions(+), 2141 deletions(-) diff --git a/tests/Add-DbaAgDatabase.Tests.ps1 b/tests/Add-DbaAgDatabase.Tests.ps1 index 77971674ab..1678cf38f0 100644 --- a/tests/Add-DbaAgDatabase.Tests.ps1 +++ b/tests/Add-DbaAgDatabase.Tests.ps1 @@ -1,41 +1,61 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') + +Describe "Add-DbaAgDatabase" { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" + } -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'AvailabilityGroup', 'Database', 'Secondary', 'SecondarySqlCredential', 'InputObject', 'SeedingMode', 'SharedPath', 'UseLastBackup', 'AdvancedBackupParams', '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 { + $command = Get-Command Add-DbaAgDatabase + } + $paramList = @( + 'SqlInstance', + 'SqlCredential', + 'AvailabilityGroup', + 'Database', + 'Secondary', + 'SecondarySqlCredential', + 'InputObject', + 'SeedingMode', + 'SharedPath', + 'UseLastBackup', + 'AdvancedBackupParams', + 'EnableException', + 'WhatIf', + 'Confirm' + ) + It "Should have parameter: <_>" -ForEach $paramList { + $command | Should -HaveParameter $PSItem } } -} -Describe "$commandname Integration Tests" -Tag "IntegrationTests" { - BeforeAll { - $null = Get-DbaProcess -SqlInstance $script:instance3 -Program 'dbatools PowerShell module - dbatools.io' | Stop-DbaProcess -WarningAction SilentlyContinue - $server = Connect-DbaInstance -SqlInstance $script:instance3 - $agname = "dbatoolsci_addagdb_agroup" - $dbname = "dbatoolsci_addagdb_agroupdb" - $newdbname = "dbatoolsci_addag_agroupdb_2" - $server.Query("create database $dbname") - $backup = Get-DbaDatabase -SqlInstance $script:instance3 -Database $dbname | Backup-DbaDatabase - $ag = New-DbaAvailabilityGroup -Primary $script:instance3 -Name $agname -ClusterType None -FailoverMode Manual -Database $dbname -Confirm:$false -Certificate dbatoolsci_AGCert - } - AfterAll { - $null = Remove-DbaAvailabilityGroup -SqlInstance $server -AvailabilityGroup $agname -Confirm:$false - $null = Remove-DbaDatabase -SqlInstance $server -Database $dbname, $newdbname -Confirm:$false - } - Context "adds ag db" { - It "returns proper results" { + Context "Integration Tests" -Tag "IntegrationTests" { + BeforeAll { + $null = Get-DbaProcess -SqlInstance $global:instance3 -Program 'dbatools PowerShell module - dbatools.io' | Stop-DbaProcess -WarningAction SilentlyContinue + $server = Connect-DbaInstance -SqlInstance $global:instance3 + $agname = "dbatoolsci_addagdb_agroup" + $dbname = "dbatoolsci_addagdb_agroupdb" + $newdbname = "dbatoolsci_addag_agroupdb_2" + $server.Query("create database $dbname") + $backup = Get-DbaDatabase -SqlInstance $global:instance3 -Database $dbname | Backup-DbaDatabase + $ag = New-DbaAvailabilityGroup -Primary $global:instance3 -Name $agname -ClusterType None -FailoverMode Manual -Database $dbname -Confirm:$false -Certificate dbatoolsci_AGCert + } + + AfterAll { + $null = Remove-DbaAvailabilityGroup -SqlInstance $server -AvailabilityGroup $agname -Confirm:$false + $null = Remove-DbaDatabase -SqlInstance $server -Database $dbname, $newdbname -Confirm:$false + } + + It "adds ag db and returns proper results" { $server.Query("create database $newdbname") - $backup = Get-DbaDatabase -SqlInstance $script:instance3 -Database $newdbname | Backup-DbaDatabase - $results = Add-DbaAgDatabase -SqlInstance $script:instance3 -AvailabilityGroup $agname -Database $newdbname -Confirm:$false + $backup = Get-DbaDatabase -SqlInstance $global:instance3 -Database $newdbname | Backup-DbaDatabase + $results = Add-DbaAgDatabase -SqlInstance $global:instance3 -AvailabilityGroup $agname -Database $newdbname -Confirm:$false $results.AvailabilityGroup | Should -Be $agname $results.Name | Should -Be $newdbname $results.IsJoined | Should -Be $true } } -} #$script:instance2 for appveyor \ No newline at end of file +} + +#$global:instance2 for appveyor diff --git a/tests/Add-DbaAgListener.Tests.ps1 b/tests/Add-DbaAgListener.Tests.ps1 index 1483f1519c..4295698f4a 100644 --- a/tests/Add-DbaAgListener.Tests.ps1 +++ b/tests/Add-DbaAgListener.Tests.ps1 @@ -1,34 +1,51 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') + +Describe "Add-DbaAgListener" { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" + } -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'AvailabilityGroup', 'Name', 'IPAddress', 'SubnetIP', 'SubnetMask', 'Port', 'Dhcp', 'Passthru', 'InputObject', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 + BeforeAll { + $command = Get-Command Add-DbaAgListener + } + $paramList = @( + 'SqlInstance', + 'SqlCredential', + 'AvailabilityGroup', + 'Name', + 'IPAddress', + 'SubnetIP', + 'SubnetMask', + 'Port', + 'Dhcp', + 'Passthru', + 'InputObject', + 'EnableException', + 'WhatIf', + 'Confirm' + ) + It "Should have parameter: <_>" -ForEach $paramList { + $command | Should -HaveParameter $PSItem } } -} -Describe "$commandname Integration Tests" -Tag "IntegrationTests" { - BeforeAll { - $agname = "dbatoolsci_ag_newlistener" - $listenerName = 'dbatoolsci_listener' - $ag = New-DbaAvailabilityGroup -Primary $script:instance3 -Name $agname -ClusterType None -FailoverMode Manual -Confirm:$false -Certificate dbatoolsci_AGCert - } - AfterEach { - $null = Remove-DbaAgListener -SqlInstance $script:instance3 -Listener $listenerName -AvailabilityGroup $agname -Confirm:$false - } - AfterAll { - $null = Remove-DbaAvailabilityGroup -SqlInstance $script:instance3 -AvailabilityGroup $agname -Confirm:$false - } - Context "creates a listener" { - It "returns results with proper data" { + Context "Integration Tests" -Tag "IntegrationTests" { + BeforeAll { + $agname = "dbatoolsci_ag_newlistener" + $listenerName = 'dbatoolsci_listener' + $ag = New-DbaAvailabilityGroup -Primary $global:instance3 -Name $agname -ClusterType None -FailoverMode Manual -Confirm:$false -Certificate dbatoolsci_AGCert + } + AfterAll { + Remove-DbaAvailabilityGroup -SqlInstance $global:instance3 -AvailabilityGroup $agname -Confirm:$false + } + + It "creates a listener and returns results with proper data" { $results = $ag | Add-DbaAgListener -Name $listenerName -IPAddress 127.0.20.1 -Port 14330 -Confirm:$false $results.PortNumber | Should -Be 14330 + + # Cleanup + Remove-DbaAgListener -SqlInstance $global:instance3 -Listener $listenerName -AvailabilityGroup $agname -Confirm:$false } - } -} #$script:instance2 for appveyor \ No newline at end of file + } #$global:instance2 for appveyor +} diff --git a/tests/Add-DbaAgReplica.Tests.ps1 b/tests/Add-DbaAgReplica.Tests.ps1 index 5a8c75c922..d5a4a01dab 100644 --- a/tests/Add-DbaAgReplica.Tests.ps1 +++ b/tests/Add-DbaAgReplica.Tests.ps1 @@ -1,45 +1,74 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') + +Describe "Add-DbaAgReplica" { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" + } -Describe "$commandname Unit Tests" -Tag 'UnitTests' { Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Name', 'ClusterType', 'AvailabilityMode', 'FailoverMode', 'BackupPriority', 'ConnectionModeInPrimaryRole', 'ConnectionModeInSecondaryRole', 'SeedingMode', 'Endpoint', 'EndpointUrl', 'Passthru', 'ReadOnlyRoutingList', 'ReadonlyRoutingConnectionUrl', 'Certificate', 'ConfigureXESession', 'SessionTimeout', 'InputObject', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 + BeforeAll { + $command = Get-Command Add-DbaAgReplica + } + $knownParameters = @( + 'SqlInstance', + 'SqlCredential', + 'Name', + 'ClusterType', + 'AvailabilityMode', + 'FailoverMode', + 'BackupPriority', + 'ConnectionModeInPrimaryRole', + 'ConnectionModeInSecondaryRole', + 'SeedingMode', + 'Endpoint', + 'EndpointUrl', + 'Passthru', + 'ReadOnlyRoutingList', + 'ReadonlyRoutingConnectionUrl', + 'Certificate', + 'ConfigureXESession', + 'SessionTimeout', + 'InputObject', + 'EnableException', + 'WhatIf', + 'Confirm' + ) + It "Should have the correct parameters" -ForEach $knownParameters { + $command | Should -HaveParameter $PSItem } } -} -Describe "$commandname Integration Tests" -Tag "IntegrationTests" { - BeforeAll { - $agname = "dbatoolsci_agroup" - $ag = New-DbaAvailabilityGroup -Primary $script:instance3 -Name $agname -ClusterType None -FailoverMode Manual -Certificate dbatoolsci_AGCert -Confirm:$false - $replicaName = $ag.PrimaryReplica - } - AfterAll { - $null = Remove-DbaAvailabilityGroup -SqlInstance $script:instance3 -AvailabilityGroup $agname -Confirm:$false - } - Context "gets ag replicas" { - # the only way to test, really, is to call New-DbaAvailabilityGroup which calls Add-DbaAgReplica - $agname = "dbatoolsci_add_replicagroup" - $ag = New-DbaAvailabilityGroup -Primary $script:instance3 -Name $agname -ClusterType None -FailoverMode Manual -Certificate dbatoolsci_AGCert -Confirm:$false - $replicaName = $ag.PrimaryReplica - It "returns results with proper data" { - $results = Get-DbaAgReplica -SqlInstance $script:instance3 - $results.AvailabilityGroup | Should -Contain $agname - $results.Role | Should -Contain 'Primary' - $results.AvailabilityMode | Should -Contain 'SynchronousCommit' - $results.FailoverMode | Should -Contain 'Manual' + Context "Integration Tests" -Tag "IntegrationTests" { + BeforeAll { + $agname = "dbatoolsci_agroup" + $ag = New-DbaAvailabilityGroup -Primary $global:instance3 -Name $agname -ClusterType None -FailoverMode Manual -Certificate dbatoolsci_AGCert -Confirm:$false + $replicaName = $ag.PrimaryReplica + } + AfterAll { + $null = Remove-DbaAvailabilityGroup -SqlInstance $global:instance3 -AvailabilityGroup $agname -Confirm:$false } - It "returns just one result" { - $results = Get-DbaAgReplica -SqlInstance $script:instance3 -Replica $replicaName -AvailabilityGroup $agname - $results.AvailabilityGroup | Should -Be $agname - $results.Role | Should -Be 'Primary' - $results.AvailabilityMode | Should -Be 'SynchronousCommit' - $results.FailoverMode | Should -Be 'Manual' + Context "gets ag replicas" { + BeforeAll { + $agname = "dbatoolsci_add_replicagroup" + $ag = New-DbaAvailabilityGroup -Primary $global:instance3 -Name $agname -ClusterType None -FailoverMode Manual -Certificate dbatoolsci_AGCert -Confirm:$false + $replicaName = $ag.PrimaryReplica + } + + It "returns results with proper data" { + $results = Get-DbaAgReplica -SqlInstance $global:instance3 + $results.AvailabilityGroup | Should -Contain $agname + $results.Role | Should -Contain 'Primary' + $results.AvailabilityMode | Should -Contain 'SynchronousCommit' + $results.FailoverMode | Should -Contain 'Manual' + } + It "returns just one result" { + $results = Get-DbaAgReplica -SqlInstance $global:instance3 -Replica $replicaName -AvailabilityGroup $agname + $results.AvailabilityGroup | Should -Be $agname + $results.Role | Should -Be 'Primary' + $results.AvailabilityMode | Should -Be 'SynchronousCommit' + $results.FailoverMode | Should -Be 'Manual' + } } } -} #$script:instance2 for appveyor +} +#$global:instance2 for appveyor diff --git a/tests/Add-DbaComputerCertificate.Tests.ps1 b/tests/Add-DbaComputerCertificate.Tests.ps1 index 316f03e0ce..11dbed33c6 100644 --- a/tests/Add-DbaComputerCertificate.Tests.ps1 +++ b/tests/Add-DbaComputerCertificate.Tests.ps1 @@ -1,30 +1,47 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') + +Describe "Add-DbaComputerCertificate" { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" + } -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'ComputerName', 'Credential', 'SecurePassword', 'Certificate', 'Path', 'Store', 'Folder', 'Flag', '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 { + $command = Get-Command Add-DbaComputerCertificate + } + $paramsList = @( + 'ComputerName', + 'Credential', + 'SecurePassword', + 'Certificate', + 'Path', + 'Store', + 'Folder', + 'Flag', + 'EnableException', + 'WhatIf', + 'Confirm' + ) + It "Should have parameter: <_>" -ForEach $paramsList { + $command | Should -HaveParameter $PSItem } } -} -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { Context "Certificate is added properly" { - $results = Add-DbaComputerCertificate -Path $script:appveyorlabrepo\certificates\localhost.crt -Confirm:$false + BeforeAll { + $results = Add-DbaComputerCertificate -Path $global:appveyorlabrepo\certificates\localhost.crt -Confirm:$false + } + + AfterAll { + Remove-DbaComputerCertificate -Thumbprint 29C469578D6C6211076A09CEE5C5797EEA0C2713 -Confirm:$false + } It "Should show the proper thumbprint has been added" { - $results.Thumbprint | Should Be "29C469578D6C6211076A09CEE5C5797EEA0C2713" + $results.Thumbprint | Should -Be "29C469578D6C6211076A09CEE5C5797EEA0C2713" } It "Should be in LocalMachine\My Cert Store" { - $results.PSParentPath | Should Be "Microsoft.PowerShell.Security\Certificate::LocalMachine\My" + $results.PSParentPath | Should -Be "Microsoft.PowerShell.Security\Certificate::LocalMachine\My" } - - Remove-DbaComputerCertificate -Thumbprint 29C469578D6C6211076A09CEE5C5797EEA0C2713 -Confirm:$false } -} \ No newline at end of file +} diff --git a/tests/Add-DbaDbMirrorMonitor.Tests.ps1 b/tests/Add-DbaDbMirrorMonitor.Tests.ps1 index f0b2ad6848..d761d9e9bf 100644 --- a/tests/Add-DbaDbMirrorMonitor.Tests.ps1 +++ b/tests/Add-DbaDbMirrorMonitor.Tests.ps1 @@ -1,28 +1,37 @@ -$commandname = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') + +Describe "Add-DbaDbMirrorMonitor" { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" + } -Describe "$CommandName Unit Tests" -Tags "UnitTests" { Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', '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 { + $command = Get-Command Add-DbaDbMirrorMonitor + } + $knownParameters = @( + 'SqlInstance', + 'SqlCredential', + 'EnableException', + 'WhatIf', + 'Confirm' + ) + It "Should have the required parameter: <_>" -ForEach $knownParameters { + $command | Should -HaveParameter $PSItem } } -} -Describe "$commandname Integration Tests" -Tag "IntegrationTests" { - BeforeAll { - $null = Remove-DbaDbMirrorMonitor -SqlInstance $script:instance2 -WarningAction SilentlyContinue - } - AfterAll { - $null = Remove-DbaDbMirrorMonitor -SqlInstance $script:instance2 -WarningAction SilentlyContinue - } + Context "Integration Tests" -Tag "IntegrationTests" { + BeforeAll { + $null = Remove-DbaDbMirrorMonitor -SqlInstance $global:instance2 -WarningAction SilentlyContinue + } + AfterAll { + $null = Remove-DbaDbMirrorMonitor -SqlInstance $global:instance2 -WarningAction SilentlyContinue + } - It "adds the mirror monitor" { - $results = Add-DbaDbMirrorMonitor -SqlInstance $script:instance2 -WarningAction SilentlyContinue - $results.MonitorStatus | Should -Be 'Added' + It "adds the mirror monitor" { + $results = Add-DbaDbMirrorMonitor -SqlInstance $global:instance2 -WarningAction SilentlyContinue + $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 9799d91aa3..395e5dd9f7 100644 --- a/tests/Add-DbaDbRoleMember.Tests.ps1 +++ b/tests/Add-DbaDbRoleMember.Tests.ps1 @@ -1,85 +1,96 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') + +Describe "Add-DbaDbRoleMember" { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" + } -Describe "$CommandName Unit Tests" -Tags "UnitTests" { Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'Role', 'Member', 'InputObject', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + BeforeAll { + $command = Get-Command Add-DbaDbRoleMember + } + $knownParameters = @( + 'SqlInstance', + 'SqlCredential', + 'Database', + 'Role', + 'Member', + 'InputObject', + 'EnableException', + 'WhatIf', + 'Confirm' + ) + It "Should have the correct parameters" -ForEach $knownParameters { + $command | Should -HaveParameter $PSItem } } -} -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { - BeforeAll { - $server = Connect-DbaInstance -SqlInstance $script:instance2 - $user1 = "dbatoolssci_user1_$(Get-Random)" - $user2 = "dbatoolssci_user2_$(Get-Random)" - $role = "dbatoolssci_role_$(Get-Random)" - $null = New-DbaLogin -SqlInstance $script:instance2 -Login $user1 -Password ('Password1234!' | ConvertTo-SecureString -asPlainText -Force) - $null = New-DbaLogin -SqlInstance $script:instance2 -Login $user2 -Password ('Password1234!' | ConvertTo-SecureString -asPlainText -Force) - $dbname = "dbatoolsci_$(Get-Random)" - $null = New-DbaDatabase -SqlInstance $script:instance2 -Name $dbname -Owner sa - $null = New-DbaDbUser -SqlInstance $script:instance2 -Database $dbname -Login $user1 -Username $user1 - $null = New-DbaDbUser -SqlInstance $script:instance2 -Database $dbname -Login $user2 -Username $user2 - $null = New-DbaDbUser -SqlInstance $script:instance2 -Database msdb -Login $user1 -Username $user1 -IncludeSystem - $null = New-DbaDbUser -SqlInstance $script:instance2 -Database msdb -Login $user2 -Username $user2 -IncludeSystem - $null = $server.Query("CREATE ROLE $role", $dbname) - } - AfterAll { - $server = Connect-DbaInstance -SqlInstance $script:instance2 - $null = $server.Query("DROP USER $user1", 'msdb') - $null = $server.Query("DROP USER $user2", 'msdb') - $null = Remove-DbaDatabase -SqlInstance $script:instance2 -Database $dbname -confirm:$false - $null = Remove-DbaLogin -SqlInstance $script:instance2 -Login $user1, $user2 -confirm:$false - } + Context "Integration Tests" -Tag "IntegrationTests" { + BeforeAll { + $server = Connect-DbaInstance -SqlInstance $script:instance2 + $user1 = "dbatoolssci_user1_$(Get-Random)" + $user2 = "dbatoolssci_user2_$(Get-Random)" + $role = "dbatoolssci_role_$(Get-Random)" + $null = New-DbaLogin -SqlInstance $script:instance2 -Login $user1 -Password ('Password1234!' | ConvertTo-SecureString -asPlainText -Force) + $null = New-DbaLogin -SqlInstance $script:instance2 -Login $user2 -Password ('Password1234!' | ConvertTo-SecureString -asPlainText -Force) + $dbname = "dbatoolsci_$(Get-Random)" + $null = New-DbaDatabase -SqlInstance $script:instance2 -Name $dbname -Owner sa + $null = New-DbaDbUser -SqlInstance $script:instance2 -Database $dbname -Login $user1 -Username $user1 + $null = New-DbaDbUser -SqlInstance $script:instance2 -Database $dbname -Login $user2 -Username $user2 + $null = New-DbaDbUser -SqlInstance $script:instance2 -Database msdb -Login $user1 -Username $user1 -IncludeSystem + $null = New-DbaDbUser -SqlInstance $script:instance2 -Database msdb -Login $user2 -Username $user2 -IncludeSystem + $null = $server.Query("CREATE ROLE $role", $dbname) + } + + AfterAll { + $server = Connect-DbaInstance -SqlInstance $script:instance2 + $null = $server.Query("DROP USER $user1", 'msdb') + $null = $server.Query("DROP USER $user2", 'msdb') + $null = Remove-DbaDatabase -SqlInstance $script:instance2 -Database $dbname -Confirm:$false + $null = Remove-DbaLogin -SqlInstance $script:instance2 -Login $user1, $user2 -Confirm:$false + } - Context "Functionality" { It 'Adds User to Role' { - Add-DbaDbRoleMember -SqlInstance $script:instance2 -Role $role -Member $user1 -Database $dbname -confirm:$false + Add-DbaDbRoleMember -SqlInstance $script:instance2 -Role $role -Member $user1 -Database $dbname -Confirm:$false $roleDBAfter = Get-DbaDbRoleMember -SqlInstance $server -Database $dbname -Role $role - $roleDBAfter.Role | Should Be $role - $roleDBAfter.Login | Should Be $user1 - $roleDBAfter.UserName | Should Be $user1 + $roleDBAfter.Role | Should -Be $role + $roleDBAfter.Login | Should -Be $user1 + $roleDBAfter.UserName | Should -Be $user1 } It 'Adds User to Multiple Roles' { $roleDB = Get-DbaDbRoleMember -SqlInstance $server -Database msdb -Role db_datareader, SQLAgentReaderRole - Add-DbaDbRoleMember -SqlInstance $script:instance2 -Role db_datareader, SQLAgentReaderRole -Member $user1 -Database msdb -confirm:$false + Add-DbaDbRoleMember -SqlInstance $script:instance2 -Role db_datareader, SQLAgentReaderRole -Member $user1 -Database msdb -Confirm:$false $roleDBAfter = Get-DbaDbRoleMember -SqlInstance $server -Database msdb -Role db_datareader, SQLAgentReaderRole - $roleDBAfter.Count | Should BeGreaterThan $roleDB.Count - $roleDB.UserName -contains $user1 | Should Be $false - $roleDBAfter.UserName -contains $user1 | Should Be $true - + $roleDBAfter.Count | Should -BeGreaterThan $roleDB.Count + $roleDB.UserName | Should -Not -Contain $user1 + $roleDBAfter.UserName | Should -Contain $user1 } It 'Adds User to Roles via piped input from Get-DbaDbRole' { $roleInput = Get-DbaDbRole -SqlInstance $server -Database msdb -Role db_datareader, SQLAgentReaderRole $roleDB = Get-DbaDbRoleMember -SqlInstance $server -Database msdb -Role db_datareader, SQLAgentReaderRole - $roleInput | Add-DbaDbRoleMember -User $user2 -confirm:$false + $roleInput | Add-DbaDbRoleMember -User $user2 -Confirm:$false $roleDBAfter = Get-DbaDbRoleMember -SqlInstance $server -Database msdb -Role db_datareader, SQLAgentReaderRole - $roleDB.UserName -contains $user2 | Should Be $false - $roleDBAfter.UserName -contains $user2 | Should Be $true + $roleDB.UserName | Should -Not -Contain $user2 + $roleDBAfter.UserName | Should -Contain $user2 } It 'Skip adding user to role if already a member' { - $messages = Add-DbaDbRoleMember -SqlInstance $script:instance2 -Role $role -Member $user1 -Database $dbname -confirm:$false -Verbose 4>&1 + $messages = Add-DbaDbRoleMember -SqlInstance $script:instance2 -Role $role -Member $user1 -Database $dbname -Confirm:$false -Verbose 4>&1 $messageCount = ($messages -match 'Adding user').Count - $messageCount | Should Be 0 + $messageCount | Should -Be 0 } It 'Adds Role to Role' { - Add-DbaDbRoleMember -SqlInstance $script:instance2 -Role db_datawriter -Member $role -Database $dbname -confirm:$false + Add-DbaDbRoleMember -SqlInstance $script:instance2 -Role db_datawriter -Member $role -Database $dbname -Confirm:$false $roleDBAfter = Get-DbaDbRoleMember -SqlInstance $server -Database $dbname -Role db_datawriter - $roleDBAfter.MemberRole | Should Contain $role + $roleDBAfter.MemberRole | Should -Contain $role } } } diff --git a/tests/Add-DbaExtendedProperty.Tests.ps1 b/tests/Add-DbaExtendedProperty.Tests.ps1 index 251328389c..e96a338686 100644 --- a/tests/Add-DbaExtendedProperty.Tests.ps1 +++ b/tests/Add-DbaExtendedProperty.Tests.ps1 @@ -1,37 +1,48 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') + +Describe "Add-DbaExtendedProperty" { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" + } -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { Context "Validate parameters" { - [array]$params = ([Management.Automation.CommandMetaData]$ExecutionContext.SessionState.InvokeCommand.GetCommand($CommandName, 'Function')).Parameters.Keys - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'Name', 'InputObject', 'EnableException', 'Value' - It "Should only contain our specific parameters" { - Compare-Object -ReferenceObject $knownParameters -DifferenceObject $params | Should -BeNullOrEmpty + BeforeAll { + $command = Get-Command Add-DbaExtendedProperty + } + $parms = @( + 'SqlInstance', + 'SqlCredential', + 'Database', + 'Name', + 'Value', + 'InputObject', + 'EnableException', + 'WhatIf', + 'Confirm' + ) + It "Has required parameter: <_>" -ForEach $parms { + $command | Should -HaveParameter $PSItem } } -} - -Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { - BeforeAll { - $random = Get-Random - $server2 = Connect-DbaInstance -SqlInstance $script:instance2 - $null = Get-DbaProcess -SqlInstance $server2 | Where-Object Program -match dbatools | Stop-DbaProcess -Confirm:$false - $newDbName = "dbatoolsci_newdb_$random" - $db = New-DbaDatabase -SqlInstance $server2 -Name $newDbName - } + Context "Integration Tests" -Tag "IntegrationTests" { + BeforeAll { + $random = Get-Random + $server2 = Connect-DbaInstance -SqlInstance $global:instance2 + $null = Get-DbaProcess -SqlInstance $server2 | Where-Object Program -match dbatools | Stop-DbaProcess -Confirm:$false + $newDbName = "dbatoolsci_newdb_$random" + $db = New-DbaDatabase -SqlInstance $server2 -Name $newDbName + } - AfterAll { - $null = $db | Remove-DbaDatabase -Confirm:$false - } + AfterAll { + $null = $db | Remove-DbaDatabase -Confirm:$false + } - Context "commands work as expected" { - It "works" { + It "adds an extended property to the database" { $ep = $db | Add-DbaExtendedProperty -Name "Test_Database_Name" -Value "Sup" $ep.Name | Should -Be "Test_Database_Name" $ep.ParentName | Should -Be $db.Name $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 69212aa44e..ccd56775ac 100644 --- a/tests/Add-DbaPfDataCollectorCounter.Tests.ps1 +++ b/tests/Add-DbaPfDataCollectorCounter.Tests.ps1 @@ -1,31 +1,51 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') + +Describe "Add-DbaPfDataCollectorCounter" { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" + } -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'ComputerName', 'Credential', 'CollectorSet', 'Collector', 'Counter', 'InputObject', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + BeforeAll { + $command = Get-Command Add-DbaPfDataCollectorCounter + } + $paramList = @( + 'ComputerName', + 'Credential', + 'CollectorSet', + 'Collector', + 'Counter', + 'InputObject', + 'EnableException', + 'WhatIf', + 'Confirm' + ) + It "Should have parameter: <_>" -ForEach $paramList { + $command | Should -HaveParameter $PSItem } } -} -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { - BeforeEach { - $null = Get-DbaPfDataCollectorSetTemplate -Template 'Long Running Queries' | Import-DbaPfDataCollectorSetTemplate | - Get-DbaPfDataCollector | Get-DbaPfDataCollectorCounter -Counter '\LogicalDisk(*)\Avg. Disk Queue Length' | Remove-DbaPfDataCollectorCounter -Confirm:$false - } - AfterAll { - $null = Get-DbaPfDataCollectorSet -CollectorSet 'Long Running Queries' | Remove-DbaPfDataCollectorSet -Confirm:$false - } - Context "Verifying command returns all the required results" { + Context "Integration Tests" -Tag "IntegrationTests" { + BeforeAll { + $null = Get-DbaPfDataCollectorSetTemplate -Template 'Long Running Queries' | + Import-DbaPfDataCollectorSetTemplate | + Get-DbaPfDataCollector | + Get-DbaPfDataCollectorCounter -Counter '\LogicalDisk(*)\Avg. Disk Queue Length' | + Remove-DbaPfDataCollectorCounter -Confirm:$false + } + + AfterAll { + $null = Get-DbaPfDataCollectorSet -CollectorSet 'Long Running Queries' | + Remove-DbaPfDataCollectorSet -Confirm:$false + } + It "returns the correct values" { - $results = Get-DbaPfDataCollectorSet -CollectorSet 'Long Running Queries' | Get-DbaPfDataCollector | Add-DbaPfDataCollectorCounter -Counter '\LogicalDisk(*)\Avg. Disk Queue Length' - $results.DataCollectorSet | Should Be 'Long Running Queries' - $results.Name | Should Be '\LogicalDisk(*)\Avg. Disk Queue Length' + $results = Get-DbaPfDataCollectorSet -CollectorSet 'Long Running Queries' | + Get-DbaPfDataCollector | + Add-DbaPfDataCollectorCounter -Counter '\LogicalDisk(*)\Avg. Disk Queue Length' + + $results.DataCollectorSet | Should -Be 'Long Running Queries' + $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 367fc9149d..5e3eee649c 100644 --- a/tests/Add-DbaRegServer.Tests.ps1 +++ b/tests/Add-DbaRegServer.Tests.ps1 @@ -1,44 +1,61 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') + +Describe "Add-DbaRegServer" { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" + } -Describe "$CommandName Unit Tests" -Tags "UnitTests" { Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'ServerName', 'Name', 'Description', 'Group', 'ActiveDirectoryTenant', 'ActiveDirectoryUserId', 'ConnectionString', 'OtherParams', 'InputObject', 'ServerObject', '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 { + $command = Get-Command Add-DbaRegServer + } + $paramList = @( + 'SqlInstance', + 'SqlCredential', + 'ServerName', + 'Name', + 'Description', + 'Group', + 'ActiveDirectoryTenant', + 'ActiveDirectoryUserId', + 'ConnectionString', + 'OtherParams', + 'InputObject', + 'ServerObject', + 'EnableException', + 'WhatIf', + 'Confirm' + ) + It "Should have parameter: <_>" -ForEach $paramList { + $command | Should -HaveParameter $PSItem } } -} -Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { - Context "Setup" { + Context "Integration Tests" -Tag "IntegrationTests" { BeforeAll { $srvName = "dbatoolsci-server1" $group = "dbatoolsci-group1" $regSrvName = "dbatoolsci-server12" $regSrvDesc = "dbatoolsci-server123" - $groupobject = Add-DbaRegServerGroup -SqlInstance $script:instance1 -Name $group + $groupobject = Add-DbaRegServerGroup -SqlInstance $global:instance1 -Name $group } AfterAll { - Get-DbaRegServer -SqlInstance $script:instance1, $script:instance2 | Where-Object Name -match dbatoolsci | Remove-DbaRegServer -Confirm:$false - Get-DbaRegServerGroup -SqlInstance $script:instance1, $script:instance2 | Where-Object Name -match dbatoolsci | Remove-DbaRegServerGroup -Confirm:$false + Get-DbaRegServer -SqlInstance $global:instance1, $global:instance2 | Where-Object Name -match dbatoolsci | Remove-DbaRegServer -Confirm:$false + Get-DbaRegServerGroup -SqlInstance $global:instance1, $global:instance2 | Where-Object Name -match dbatoolsci | Remove-DbaRegServerGroup -Confirm:$false } It "adds a registered server" { - $results1 = Add-DbaRegServer -SqlInstance $script:instance1 -ServerName $srvName + $results1 = Add-DbaRegServer -SqlInstance $global:instance1 -ServerName $srvName $results1.Name | Should -Be $srvName $results1.ServerName | Should -Be $srvName - $results1.SqlInstance | Should -Not -Be $null + $results1.SqlInstance | Should -Not -BeNullOrEmpty } It "adds a registered server with extended properties" { - $results2 = Add-DbaRegServer -SqlInstance $script:instance1 -ServerName $RegsrvName -Name $srvName -Group $groupobject -Description $regSrvDesc + $results2 = Add-DbaRegServer -SqlInstance $global:instance1 -ServerName $RegsrvName -Name $srvName -Group $groupobject -Description $regSrvDesc $results2.ServerName | Should -Be $regSrvName $results2.Description | Should -Be $regSrvDesc $results2.Name | Should -Be $srvName - $results2.SqlInstance | Should -Not -Be $null + $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 c28d01ef27..0260314dcd 100644 --- a/tests/Add-DbaRegServerGroup.Tests.ps1 +++ b/tests/Add-DbaRegServerGroup.Tests.ps1 @@ -1,20 +1,31 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') + +Describe "Add-DbaRegServerGroup" { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" + } -Describe "$CommandName Unit Tests" -Tags "UnitTests" { Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Name', 'Description', 'Group', 'InputObject', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + BeforeAll { + $command = Get-Command Add-DbaRegServerGroup + } + $parms = @( + 'SqlInstance', + 'SqlCredential', + 'Name', + 'Description', + 'Group', + 'InputObject', + 'EnableException', + 'WhatIf', + 'Confirm' + ) + It "Has required parameter: <_>" -ForEach $parms { + $command | Should -HaveParameter $PSItem } } -} -Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { - Context "Setup" { + Context "Integration Tests" -Tag "IntegrationTests" { BeforeAll { $group = "dbatoolsci-group1" $group2 = "dbatoolsci-group2" @@ -22,34 +33,38 @@ Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { $descriptionUpdated = "group description updated" } AfterAll { - Get-DbaRegServerGroup -SqlInstance $script:instance1 | Where-Object Name -match dbatoolsci | Remove-DbaRegServerGroup -Confirm:$false + Get-DbaRegServerGroup -SqlInstance $global:instance1 | Where-Object Name -match dbatoolsci | Remove-DbaRegServerGroup -Confirm:$false } It "adds a registered server group" { - $results = Add-DbaRegServerGroup -SqlInstance $script:instance1 -Name $group + $results = Add-DbaRegServerGroup -SqlInstance $global:instance1 -Name $group $results.Name | Should -Be $group - $results.SqlInstance | Should -Not -Be $null + $results.SqlInstance | Should -Not -BeNullOrEmpty } It "adds a registered server group with extended properties" { - $results = Add-DbaRegServerGroup -SqlInstance $script:instance1 -Name $group2 -Description $description + $results = Add-DbaRegServerGroup -SqlInstance $global:instance1 -Name $group2 -Description $description $results.Name | Should -Be $group2 $results.Description | Should -Be $description - $results.SqlInstance | Should -Not -Be $null + $results.SqlInstance | Should -Not -BeNullOrEmpty } It "supports hella pipe" { - $results = Get-DbaRegServerGroup -SqlInstance $script:instance1 -Id 1 | Add-DbaRegServerGroup -Name dbatoolsci-first | Add-DbaRegServerGroup -Name dbatoolsci-second | Add-DbaRegServerGroup -Name dbatoolsci-third | Add-DbaRegServer -ServerName dbatoolsci-test -Description ridiculous + $results = Get-DbaRegServerGroup -SqlInstance $global:instance1 -Id 1 | + Add-DbaRegServerGroup -Name dbatoolsci-first | + 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' } It "adds a registered server group and sub-group when not exists" { - $results = Add-DbaRegServerGroup -SqlInstance $script:instance1 -Name "$group\$group2" -Description $description + $results = Add-DbaRegServerGroup -SqlInstance $global:instance1 -Name "$group\$group2" -Description $description $results.Name | Should -Be $group2 - $results.SqlInstance | Should -Not -Be $null + $results.SqlInstance | Should -Not -BeNullOrEmpty } It "updates description of sub-group when it already exists" { - $results = Add-DbaRegServerGroup -SqlInstance $script:instance1 -Name "$group\$group2" -Description $descriptionUpdated + $results = Add-DbaRegServerGroup -SqlInstance $global:instance1 -Name "$group\$group2" -Description $descriptionUpdated $results.Name | Should -Be $group2 $results.Description | Should -Be $descriptionUpdated - $results.SqlInstance | Should -Not -Be $null + $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 78d16d32ff..17d8c67de2 100644 --- a/tests/Add-DbaReplArticle.Tests.ps1 +++ b/tests/Add-DbaReplArticle.Tests.ps1 @@ -1,17 +1,33 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') + +Describe "Add-DbaReplArticle Unit Tests" -Tag 'UnitTests' { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" + } -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', 'Publication', 'Schema', 'Name', 'Filter', 'CreationScriptOptions', '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 { + $command = Get-Command Add-DbaReplArticle + } + $knownParameters = @( + 'SqlInstance', + 'SqlCredential', + 'Database', + 'Publication', + 'Schema', + 'Name', + 'Filter', + 'CreationScriptOptions', + 'EnableException', + 'WhatIf', + 'Confirm' + ) + It "Should have the correct parameters" -ForEach $knownParameters { + $command | Should -HaveParameter $PSItem } } } + <# 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 4c0cb0e748..3abf0e9189 100644 --- a/tests/Add-DbaServerRoleMember.Tests.ps1 +++ b/tests/Add-DbaServerRoleMember.Tests.ps1 @@ -1,59 +1,70 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') + +Describe "Add-DbaServerRoleMember" { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" + } -Describe "$CommandName Unit Tests" -Tags "UnitTests" { Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('WhatIf', 'Confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'ServerRole', 'Login', 'Role', 'InputObject', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should -Be 0 + BeforeAll { + $command = Get-Command Add-DbaServerRoleMember } + $knownParameters = @( + 'SqlInstance', + 'SqlCredential', + 'ServerRole', + 'Login', + 'Role', + 'InputObject', + 'EnableException', + 'WhatIf', + 'Confirm' + ) + It "Should have the correct parameters" { + $command.Parameters.Keys | Should -Contain $_ + } -ForEach $knownParameters } -} -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { - BeforeAll { - $server = Connect-DbaInstance -SqlInstance $script:instance2 - $login1 = "dbatoolsci_login1_$(Get-Random)" - $login2 = "dbatoolsci_login2_$(Get-Random)" - $customServerRole = "dbatoolsci_customrole_$(Get-Random)" - $fixedServerRoles = 'dbcreator','processadmin' - $null = New-DbaLogin -SqlInstance $script:instance2 -Login $login1 -Password ('Password1234!' | ConvertTo-SecureString -asPlainText -Force) - $null = New-DbaLogin -SqlInstance $script:instance2 -Login $login2 -Password ('Password1234!' | ConvertTo-SecureString -asPlainText -Force) - $null = New-DbaServerRole -SqlInstance $script:instance2 -ServerRole $customServerRole -Owner sa - } - AfterAll { - $server = Connect-DbaInstance -SqlInstance $script:instance2 - $null = Remove-DbaLogin -SqlInstance $script:instance2 -Login $login1, $login2 -Confirm:$false - } + Context "Integration Tests" -Tag "IntegrationTests" { + BeforeAll { + $server = Connect-DbaInstance -SqlInstance $global:instance2 + $login1 = "dbatoolsci_login1_$(Get-Random)" + $login2 = "dbatoolsci_login2_$(Get-Random)" + $customServerRole = "dbatoolsci_customrole_$(Get-Random)" + $fixedServerRoles = 'dbcreator','processadmin' + $null = New-DbaLogin -SqlInstance $global:instance2 -Login $login1 -Password ('Password1234!' | ConvertTo-SecureString -asPlainText -Force) + $null = New-DbaLogin -SqlInstance $global:instance2 -Login $login2 -Password ('Password1234!' | ConvertTo-SecureString -asPlainText -Force) + $null = New-DbaServerRole -SqlInstance $global:instance2 -ServerRole $customServerRole -Owner sa + } + + AfterAll { + $server = Connect-DbaInstance -SqlInstance $global:instance2 + $null = Remove-DbaLogin -SqlInstance $global:instance2 -Login $login1, $login2 -Confirm:$false + } - Context "Functionality" { It 'Adds Login to Role' { - Add-DbaServerRoleMember -SqlInstance $script:instance2 -ServerRole $fixedServerRoles[0] -Login $login1 -Confirm:$false + Add-DbaServerRoleMember -SqlInstance $global:instance2 -ServerRole $fixedServerRoles[0] -Login $login1 -Confirm:$false $roleAfter = Get-DbaServerRole -SqlInstance $server -ServerRole $fixedServerRoles[0] $roleAfter.Role | Should -Be $fixedServerRoles[0] - $roleAfter.EnumMemberNames().Contains($login1) | Should -Be $true + $roleAfter.EnumMemberNames() | Should -Contain $login1 } It 'Adds Login to Multiple Roles' { $serverRoles = Get-DbaServerRole -SqlInstance $server -ServerRole $fixedServerRoles - Add-DbaServerRoleMember -SqlInstance $script:instance2 -ServerRole $serverRoles -Login $login1 -Confirm:$false + Add-DbaServerRoleMember -SqlInstance $global:instance2 -ServerRole $serverRoles -Login $login1 -Confirm:$false $roleDBAfter = Get-DbaServerRole -SqlInstance $server -ServerRole $fixedServerRoles $roleDBAfter.Count | Should -Be $serverRoles.Count - $roleDBAfter.Login -contains $login1 | Should -Be $true - + $roleDBAfter.Login | Should -Contain $login1 } It 'Adds Customer Server-Level Role Membership' { - Add-DbaServerRoleMember -SqlInstance $script:instance2 -ServerRole $customServerRole -Role $fixedServerRoles[-1] -Confirm:$false + Add-DbaServerRoleMember -SqlInstance $global:instance2 -ServerRole $customServerRole -Role $fixedServerRoles[-1] -Confirm:$false $roleAfter = Get-DbaServerRole -SqlInstance $server -ServerRole $fixedServerRoles[-1] $roleAfter.Role | Should -Be $fixedServerRoles[-1] - $roleAfter.EnumMemberNames().Contains($customServerRole) | Should -Be $true + $roleAfter.EnumMemberNames() | Should -Contain $customServerRole } It 'Adds Login to Roles via piped input from Get-DbaServerRole' { @@ -61,7 +72,7 @@ Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { $serverRole | Add-DbaServerRoleMember -Login $login2 -Confirm:$false $roleAfter = Get-DbaServerRole -SqlInstance $server -ServerRole $fixedServerRoles[0] - $roleAfter.EnumMemberNames().Contains($login2) | Should -Be $true + $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 365c7c10b1..5d0aa911df 100644 --- a/tests/Backup-DbaComputerCertificate.Tests.ps1 +++ b/tests/Backup-DbaComputerCertificate.Tests.ps1 @@ -1,25 +1,39 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') + +Describe "Backup-DbaComputerCertificate" { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" + } -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'SecurePassword', 'InputObject', 'Path', 'FilePath', 'Type', '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 { + $command = Get-Command Backup-DbaComputerCertificate + } + $parms = @( + 'SecurePassword', + 'InputObject', + 'Path', + 'FilePath', + 'Type', + 'EnableException' + ) + It "Has required parameter: <_>" -ForEach $parms { + $command | Should -HaveParameter $PSItem } } -} -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { Context "Certificate is added properly" { - $null = Add-DbaComputerCertificate -Path $script:appveyorlabrepo\certificates\localhost.crt -Confirm:$false + BeforeAll { + $null = Add-DbaComputerCertificate -Path $global:appveyorlabrepo\certificates\localhost.crt -Confirm:$false + } + + AfterAll { + $null = Remove-DbaComputerCertificate -Thumbprint 29C469578D6C6211076A09CEE5C5797EEA0C2713 -Confirm:$false + } + It "returns the proper results" { $result = Get-DbaComputerCertificate -Thumbprint 29C469578D6C6211076A09CEE5C5797EEA0C2713 | Backup-DbaComputerCertificate -Path C:\temp - $result.Name -match '29C469578D6C6211076A09CEE5C5797EEA0C2713.cer' + $result.Name | Should -Match '29C469578D6C6211076A09CEE5C5797EEA0C2713.cer' } - $null = Remove-DbaComputerCertificate -Thumbprint 29C469578D6C6211076A09CEE5C5797EEA0C2713 -Confirm:$false } -} \ No newline at end of file +} diff --git a/tests/Backup-DbaDbCertificate.Tests.ps1 b/tests/Backup-DbaDbCertificate.Tests.ps1 index 445de01875..f9f2e7f3b6 100644 --- a/tests/Backup-DbaDbCertificate.Tests.ps1 +++ b/tests/Backup-DbaDbCertificate.Tests.ps1 @@ -1,67 +1,74 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') + +Describe "Backup-DbaDbCertificate" { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" + } -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', 'Certificate', 'Database', 'ExcludeDatabase', 'EncryptionPassword', 'DecryptionPassword', 'Path', 'Suffix', 'InputObject', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 + BeforeAll { + $command = Get-Command Backup-DbaDbCertificate + } + $paramCount = 13 + $knownParameters = [object[]]@( + 'SqlInstance', 'SqlCredential', 'Certificate', 'Database', 'ExcludeDatabase', + 'EncryptionPassword', 'DecryptionPassword', 'Path', 'Suffix', 'InputObject', + 'EnableException', 'WhatIf', 'Confirm' + ) + It "Should contain parameters" { + $command.Parameters.Count - $defaultParamCount | Should -Be $paramCount + } + It "Should contain parameter: <_>" -ForEach $knownParameters { + $command | Should -HaveParameter $PSItem } } } -Describe "$commandname Integration Tests" -Tag "IntegrationTests" { +Describe "Backup-DbaDbCertificate Integration Tests" -Tag "IntegrationTests" { BeforeAll { $random = Get-Random $db1Name = "dbatoolscli_$random" - $db1 = New-DbaDatabase -SqlInstance $script:instance1 -Name $db1Name + $db1 = New-DbaDatabase -SqlInstance $global:instance1 -Name $db1Name $pw = ConvertTo-SecureString -String "GoodPass1234!" -AsPlainText -Force - if (-not (Get-DbaDbMasterKey -SqlInstance $script:instance1 -Database $db1Name)) { - $masterkey = New-DbaDbMasterKey -SqlInstance $script:instance1 -Database $db1Name -Password $pw -Confirm:$false + if (-not (Get-DbaDbMasterKey -SqlInstance $global:instance1 -Database $db1Name)) { + $masterkey = New-DbaDbMasterKey -SqlInstance $global:instance1 -Database $db1Name -Password $pw -Confirm:$false } - $cert = New-DbaDbCertificate -SqlInstance $script:instance1 -Database $db1Name -Confirm:$false -Password $pw -Name dbatoolscli_cert1_$random - $cert2 = New-DbaDbCertificate -SqlInstance $script:instance1 -Database $db1Name -Confirm:$false -Password $pw -Name dbatoolscli_cert2_$random + $cert = New-DbaDbCertificate -SqlInstance $global:instance1 -Database $db1Name -Confirm:$false -Password $pw -Name dbatoolscli_cert1_$random + $cert2 = New-DbaDbCertificate -SqlInstance $global:instance1 -Database $db1Name -Confirm:$false -Password $pw -Name dbatoolscli_cert2_$random } + AfterAll { - Remove-DbaDatabase -SqlInstance $script:instance1 -Database $db1Name -Confirm:$false + Remove-DbaDatabase -SqlInstance $global:instance1 -Database $db1Name -Confirm:$false } Context "Can create and backup a database certificate" { - It "backs up the db cert" { - $results = Backup-DbaDbCertificate -SqlInstance $script:instance1 -Certificate $cert.Name -Database $db1Name -EncryptionPassword $pw -DecryptionPassword $pw + $results = Backup-DbaDbCertificate -SqlInstance $global:instance1 -Certificate $cert.Name -Database $db1Name -EncryptionPassword $pw -DecryptionPassword $pw $null = Get-ChildItem -Path $results.Path -ErrorAction Ignore | Remove-Item -Confirm:$false -ErrorAction Ignore $results.Certificate | Should -Be $cert.Name - $results.Status -match "Success" - $results.DatabaseID | Should -Be (Get-DbaDatabase -SqlInstance $script:instance1 -Database $db1Name).ID + $results.Status | Should -Match "Success" + $results.DatabaseID | Should -Be (Get-DbaDatabase -SqlInstance $global:instance1 -Database $db1Name).ID } It "warns the caller if the cert cannot be found" { $invalidDBCertName = "dbatoolscli_invalidCertName" $invalidDBCertName2 = "dbatoolscli_invalidCertName2" - $results = Backup-DbaDbCertificate -SqlInstance $script:instance1 -Certificate $invalidDBCertName, $invalidDBCertName2, $cert2.Name -Database $db1Name -EncryptionPassword $pw -DecryptionPassword $pw -WarningVariable warnVariable 3> $null + $results = Backup-DbaDbCertificate -SqlInstance $global:instance1 -Certificate $invalidDBCertName, $invalidDBCertName2, $cert2.Name -Database $db1Name -EncryptionPassword $pw -DecryptionPassword $pw -WarningVariable warnVariable 3> $null $null = Get-ChildItem -Path $results.Path -ErrorAction Ignore | Remove-Item -Confirm:$false -ErrorAction Ignore - #$results.Certificate | Should -Be $cert2.Name $warnVariable | Should -BeLike "*Database certificate(s) * not found*" } - # works locally, gah - It -Skip "backs up all db certs for a database" { - $results = Backup-DbaDbCertificate -SqlInstance $script:instance1 -Database $db1Name -EncryptionPassword $pw -DecryptionPassword $pw + It "backs up all db certs for a database" -Skip { + $results = Backup-DbaDbCertificate -SqlInstance $global:instance1 -Database $db1Name -EncryptionPassword $pw -DecryptionPassword $pw $null = Get-ChildItem -Path $results.Path -ErrorAction Ignore | Remove-Item -Confirm:$false -ErrorAction Ignore $results.length | Should -Be 2 $results.Certificate | Should -Be $cert.Name, $cert2.Name } - # Skip this test as there's a mix of certs, some require a password and some don't and i'll fix later - It -Skip "backs up all db certs for an instance" { - $results = Backup-DbaDbCertificate -SqlInstance $script:instance1 -EncryptionPassword $pw + It "backs up all db certs for an instance" -Skip { + $results = Backup-DbaDbCertificate -SqlInstance $global:instance1 -EncryptionPassword $pw $null = Get-ChildItem -Path $results.Path -ErrorAction Ignore | Remove-Item -Confirm:$false -ErrorAction Ignore - # $results.length | Should -BeGreaterOrEqual 2 } } -} \ No newline at end of file +} diff --git a/tests/Backup-DbaDbMasterKey.Tests.ps1 b/tests/Backup-DbaDbMasterKey.Tests.ps1 index dd61c1a96e..81c4479dde 100644 --- a/tests/Backup-DbaDbMasterKey.Tests.ps1 +++ b/tests/Backup-DbaDbMasterKey.Tests.ps1 @@ -1,39 +1,57 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') + +Describe "Backup-DbaDbMasterKey" { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" + } -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Credential', 'Database', 'ExcludeDatabase', 'SecurePassword', 'Path', 'InputObject', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 + BeforeAll { + $command = Get-Command Backup-DbaDbMasterKey + } + $paramList = @( + 'SqlInstance', + 'SqlCredential', + 'Credential', + 'Database', + 'ExcludeDatabase', + 'SecurePassword', + 'Path', + 'InputObject', + 'EnableException', + 'WhatIf', + 'Confirm' + ) + It "Should have parameter: <_>" -ForEach $paramList { + $command | Should -HaveParameter $PSItem } } -} -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { Context "Can create a database certificate" { BeforeAll { - if (-not (Get-DbaDbMasterKey -SqlInstance $script:instance1 -Database tempdb)) { - $masterkey = New-DbaDbMasterKey -SqlInstance $script:instance1 -Database tempdb -Password $(ConvertTo-SecureString -String "GoodPass1234!" -AsPlainText -Force) -Confirm:$false + $masterKeyPassword = ConvertTo-SecureString -String "GoodPass1234!" -AsPlainText -Force + if (-not (Get-DbaDbMasterKey -SqlInstance $global:instance1 -Database tempdb)) { + $masterkey = New-DbaDbMasterKey -SqlInstance $global:instance1 -Database tempdb -Password $masterKeyPassword -Confirm:$false } } AfterAll { - (Get-DbaDbMasterKey -SqlInstance $script:instance1 -Database tempdb) | Remove-DbaDbMasterKey -Confirm:$false + Get-DbaDbMasterKey -SqlInstance $global:instance1 -Database tempdb | Remove-DbaDbMasterKey -Confirm:$false } - $results = Backup-DbaDbMasterKey -SqlInstance $script:instance1 -Confirm:$false -Database tempdb -Password $(ConvertTo-SecureString -String "GoodPass1234!" -AsPlainText -Force) - $null = Remove-Item -Path $results.Path -ErrorAction SilentlyContinue -Confirm:$false - It "backs up the db cert" { - $results.Database -eq 'tempdb' - $results.Status -eq "Success" + $results = Backup-DbaDbMasterKey -SqlInstance $global:instance1 -Confirm:$false -Database tempdb -Password $masterKeyPassword + $null = Remove-Item -Path $results.Path -ErrorAction SilentlyContinue -Confirm:$false + + $results.Database | Should -Be 'tempdb' + $results.Status | Should -Be "Success" } It "Database ID should be returned" { - $results.DatabaseID | Should -Be (Get-DbaDatabase -SqlInstance $script:instance1 -Database tempdb).ID + $results = Backup-DbaDbMasterKey -SqlInstance $global:instance1 -Confirm:$false -Database tempdb -Password $masterKeyPassword + $null = Remove-Item -Path $results.Path -ErrorAction SilentlyContinue -Confirm:$false + + $expectedDatabaseId = (Get-DbaDatabase -SqlInstance $global:instance1 -Database tempdb).ID + $results.DatabaseID | Should -Be $expectedDatabaseId } } -} \ No newline at end of file +} diff --git a/tests/Backup-DbaServiceMasterKey.Tests.ps1 b/tests/Backup-DbaServiceMasterKey.Tests.ps1 index 13e0d764fe..0588372c94 100644 --- a/tests/Backup-DbaServiceMasterKey.Tests.ps1 +++ b/tests/Backup-DbaServiceMasterKey.Tests.ps1 @@ -1,25 +1,41 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') + +Describe "Backup-DbaServiceMasterKey" { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" + } -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', 'KeyCredential', 'SecurePassword', 'Path', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 + BeforeAll { + $command = Get-Command Backup-DbaServiceMasterKey + } + $knownParameters = @( + 'SqlInstance', + 'SqlCredential', + 'KeyCredential', + 'SecurePassword', + 'Path', + 'EnableException', + 'WhatIf', + 'Confirm' + ) + It "Should have the correct parameters" -ForEach $knownParameters { + $command | Should -HaveParameter $PSItem } } -} -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { Context "Can backup a service master key" { - $results = Backup-DbaServiceMasterKey -SqlInstance $script:instance1 -Confirm:$false -Password $(ConvertTo-SecureString -String "GoodPass1234!" -AsPlainText -Force) - $null = Remove-Item -Path $results.Path -ErrorAction SilentlyContinue -Confirm:$false + BeforeAll { + $password = ConvertTo-SecureString -String "GoodPass1234!" -AsPlainText -Force + $results = Backup-DbaServiceMasterKey -SqlInstance $global:instance1 -Confirm:$false -Password $password + } + + AfterAll { + $null = Remove-Item -Path $results.Path -ErrorAction SilentlyContinue -Confirm:$false + } It "backs up the SMK" { - $results.Status -eq "Success" + $results.Status | Should -Be "Success" } } -} \ No newline at end of file +} diff --git a/tests/Clear-DbaConnectionPool.Tests.ps1 b/tests/Clear-DbaConnectionPool.Tests.ps1 index cbbfd7fb83..b9dec58f68 100644 --- a/tests/Clear-DbaConnectionPool.Tests.ps1 +++ b/tests/Clear-DbaConnectionPool.Tests.ps1 @@ -1,20 +1,27 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') + +Describe "Clear-DbaConnectionPool" { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" + } -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'ComputerName', 'Credential', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + BeforeAll { + $command = Get-Command Clear-DbaConnectionPool + } + $parms = @( + 'ComputerName', + 'Credential', + 'EnableException' + ) + It "Has required parameter: <_>" -ForEach $parms { + $command | Should -HaveParameter $PSItem } } -} -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { - It "doesn't throw" { - { Clear-DbaConnectionPool } | Should Not Throw + Context "Command Execution" { + 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 99b6241406..b7ef55076d 100644 --- a/tests/Clear-DbaLatchStatistics.Tests.ps1 +++ b/tests/Clear-DbaLatchStatistics.Tests.ps1 @@ -1,24 +1,39 @@ -$commandname = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') + +Describe "Clear-DbaLatchStatistics Unit Tests" -Tag "UnitTests" { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" + } -Describe "$CommandName Unit Tests" -Tags "UnitTests" { Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', '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 { + $command = Get-Command Clear-DbaLatchStatistics + } + $knownParameters = @( + 'SqlInstance', + 'SqlCredential', + 'EnableException', + 'WhatIf', + 'Confirm' + ) + It "Should have the correct parameters" { + $command | Should -HaveParameter $knownParameters } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { +Describe "Clear-DbaLatchStatistics Integration Tests" -Tag "IntegrationTests" { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" + } + Context "Command executes properly and returns proper info" { - $results = Clear-DbaLatchStatistics -SqlInstance $script:instance1 -Confirm:$false + BeforeAll { + $results = Clear-DbaLatchStatistics -SqlInstance $global:instance1 -Confirm:$false + } It "returns success" { - $results.Status -eq 'Success' | Should Be $true + $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 00d6f9d3c2..5853131d02 100644 --- a/tests/Clear-DbaPlanCache.Tests.ps1 +++ b/tests/Clear-DbaPlanCache.Tests.ps1 @@ -1,31 +1,45 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') + +Describe "Clear-DbaPlanCache" { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" + } -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', 'Threshold', 'InputObject', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + BeforeAll { + $command = Get-Command Clear-DbaPlanCache + } + $paramList = @( + 'SqlInstance', + 'SqlCredential', + 'Threshold', + 'InputObject', + 'EnableException', + 'WhatIf', + 'Confirm' + ) + It "Should have parameter: <_>" -ForEach $paramList { + $command | Should -HaveParameter $PSItem } } -} -Describe "$commandname Integration Tests" -Tag "IntegrationTests" { Context "doesn't clear plan cache" { + BeforeAll { + $instance1 = $global:instances[0] + } + It "returns correct datatypes" { # Make plan cache way higher than likely for a test rig - $results = Clear-DbaPlanCache -SqlInstance $script:instance1 -Threshold 10240 - $results.Size -is [dbasize] | Should -Be $true - $results.Status -match 'below' | Should -Be $true + $results = Clear-DbaPlanCache -SqlInstance $instance1 -Threshold 10240 + $results.Size | Should -BeOfType [dbasize] + $results.Status | Should -Match 'below' } + It "supports piping" { # Make plan cache way higher than likely for a test rig - $results = Get-DbaPlanCache -SqlInstance $script:instance1 | Clear-DbaPlanCache -Threshold 10240 - $results.Size -is [dbasize] | Should -Be $true - $results.Status -match 'below' | Should -Be $true + $results = Get-DbaPlanCache -SqlInstance $instance1 | Clear-DbaPlanCache -Threshold 10240 + $results.Size | Should -BeOfType [dbasize] + $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 31b0904f25..1ae73edbaf 100644 --- a/tests/Clear-DbaWaitStatistics.Tests.ps1 +++ b/tests/Clear-DbaWaitStatistics.Tests.ps1 @@ -1,24 +1,33 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') + +Describe "Clear-DbaWaitStatistics" { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" + } -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + BeforeAll { + $command = Get-Command Clear-DbaWaitStatistics + } + $parms = @( + 'SqlInstance', + 'SqlCredential', + 'EnableException', + 'WhatIf', + 'Confirm' + ) + It "Has required parameter: <_>" -ForEach $parms { + $command | Should -HaveParameter $PSItem } } -} -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { Context "Command executes properly and returns proper info" { - $results = Clear-DbaWaitStatistics -SqlInstance $script:instance1 -Confirm:$false + BeforeAll { + $results = Clear-DbaWaitStatistics -SqlInstance $global:instance1 -Confirm:$false + } It "returns success" { - $results.Status -eq 'Success' | Should Be $true + $results.Status | Should -Be 'Success' } } -} \ No newline at end of file +} diff --git a/tests/Convert-DbaLsn.Tests.ps1 b/tests/Convert-DbaLsn.Tests.ps1 index c7f97a532d..ece84e28fb 100644 --- a/tests/Convert-DbaLsn.Tests.ps1 +++ b/tests/Convert-DbaLsn.Tests.ps1 @@ -1,46 +1,47 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') + +Describe "Convert-DbaLSN" { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" + } -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { Context "Validate parameters" { - $paramCount = 2 - $defaultParamCount = 11 - [object[]]$params = (Get-ChildItem function:\Convert-DbaLSN).Parameters.Keys - $knownParameters = 'LSN', 'EnableException' - It "Should contain our specific parameters" { - ( (Compare-Object -ReferenceObject $knownParameters -DifferenceObject $params -IncludeEqual | Where-Object SideIndicator -eq "==").Count ) | Should Be $paramCount + BeforeAll { + $command = Get-Command Convert-DbaLSN } - It "Should only contain $paramCount parameters" { - $params.Count - $defaultParamCount | Should Be $paramCount + $parms = @( + 'LSN', + 'EnableException' + ) + It "Has required parameter: <_>" -ForEach $parms { + $command | Should -HaveParameter $PSItem -Mandatory } } Context "Converts Numeric LSN to Hex" { - $LSN = '00000000020000000024300001' - It "Should convert to 00000014:000000f3:0001" { - (Convert-DbaLSN -Lsn $Lsn).Hexadecimal | Should -Be '00000014:000000f3:0001' + It "Should convert '00000000020000000024300001' to '00000014:000000f3:0001'" { + $result = Convert-DbaLSN -Lsn '00000000020000000024300001' + $result.Hexadecimal | Should -Be '00000014:000000f3:0001' } } Context "Converts Numeric LSN to Hex without leading 0s" { - $LSN = '20000000024300001' - It "Should convert to 00000014:000000f3:0001" { - (Convert-DbaLSN -Lsn $Lsn).Hexadecimal | Should -Be '00000014:000000f3:0001' + It "Should convert '20000000024300001' to '00000014:000000f3:0001'" { + $result = Convert-DbaLSN -Lsn '20000000024300001' + $result.Hexadecimal | Should -Be '00000014:000000f3:0001' } } Context "Converts Hex LSN to Numeric" { - $LSN = '00000014:000000f3:0001' - It "Should convert to 20000000024300001" { - (Convert-DbaLSN -Lsn $Lsn).Numeric | Should -Be 20000000024300001 + It "Should convert '00000014:000000f3:0001' to 20000000024300001" { + $result = Convert-DbaLSN -Lsn '00000014:000000f3:0001' + $result.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 guidence. -#> \ No newline at end of file + for more guidance. +#> diff --git a/tests/Convert-DbaMaskingValue.Tests.ps1 b/tests/Convert-DbaMaskingValue.Tests.ps1 index 3531c82407..34a591d69a 100644 --- a/tests/Convert-DbaMaskingValue.Tests.ps1 +++ b/tests/Convert-DbaMaskingValue.Tests.ps1 @@ -1,20 +1,24 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'Value', 'DataType', 'Nullable', 'EnableException' +Describe "Convert-DbaMaskingValue" { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" + } - $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 + Context "Validate parameters" { + BeforeAll { + $command = Get-Command Convert-DbaMaskingValue + } + $parms = @( + 'Value', + 'DataType', + 'Nullable', + 'EnableException' + ) + It "Has required parameter: <_>" -ForEach $parms { + $command | Should -HaveParameter $PSItem } } -} - -Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { Context "Null values" { It "Should return a single 'NULL' value" { @@ -32,65 +36,32 @@ Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { } Context "Text data types" { - It "Should return a text value" { - $value = "this is just text" - $convertedValue = Convert-DbaMaskingValue -Value $value -DataType char - $convertedValue.NewValue | Should -Be "'this is just text'" - } - - It "Should return a text value" { - $value = "this is just text" - $convertedValue = Convert-DbaMaskingValue -Value $value -DataType nchar - $convertedValue.NewValue | Should -Be "'this is just text'" - } - - It "Should return a text value" { - $value = "this is just text" - $convertedValue = Convert-DbaMaskingValue -Value $value -DataType nvarchar - $convertedValue.NewValue | Should -Be "'this is just text'" - } - - It "Should return a text value" { - $value = "this is just text" - $convertedValue = Convert-DbaMaskingValue -Value $value -DataType varchar - $convertedValue.NewValue | Should -Be "'this is just text'" - } - - It "Should return a text value" { - $value = "2.13" - $convertedValue = Convert-DbaMaskingValue -Value $value -DataType varchar - $convertedValue.NewValue | Should -Be "'2.13'" - } - - It "Should return a text value with multiple single quotes" { - $value = "'this is just text'" - $convertedValue = Convert-DbaMaskingValue -Value $value -DataType nchar - $convertedValue.NewValue | Should -Be "'''this is just text'''" + It "Should return a text value for " -ForEach @( + @{ DataType = 'char'; Value = "this is just text"; Expected = "'this is just text'" } + @{ DataType = 'nchar'; Value = "this is just text"; Expected = "'this is just text'" } + @{ DataType = 'nvarchar'; Value = "this is just text"; Expected = "'this is just text'" } + @{ DataType = 'varchar'; Value = "this is just text"; Expected = "'this is just text'" } + @{ DataType = 'varchar'; Value = "2.13"; Expected = "'2.13'" } + @{ DataType = 'nchar'; Value = "'this is just text'"; Expected = "'''this is just text'''" } + ) { + $convertedValue = Convert-DbaMaskingValue -Value $Value -DataType $DataType + $convertedValue.NewValue | Should -Be $Expected } } Context "Date and time data types" { - It "Should return a text value" { - $value = "2020-10-05 10:10:10.1234567" - $convertedValue = Convert-DbaMaskingValue -Value $value -DataType date - $convertedValue.NewValue | Should -Be "'2020-10-05'" + It "Should return a text value for " -ForEach @( + @{ DataType = 'date'; Value = "2020-10-05 10:10:10.1234567"; Expected = "'2020-10-05'" } + @{ DataType = 'time'; Value = "2020-10-05 10:10:10.1234567"; Expected = "'10:10:10.1234567'" } + @{ DataType = 'datetime'; Value = "2020-10-05 10:10:10.1234567"; Expected = "'2020-10-05 10:10:10.123'" } + ) { + $convertedValue = Convert-DbaMaskingValue -Value $Value -DataType $DataType + $convertedValue.NewValue | Should -Be $Expected } - - It "Should return a text value" { - $value = "2020-10-05 10:10:10.1234567" - $convertedValue = Convert-DbaMaskingValue -Value $value -DataType time - $convertedValue.NewValue | Should -Be "'10:10:10.1234567'" - } - - It "Should return a text value" { - $value = "2020-10-05 10:10:10.1234567" - $convertedValue = Convert-DbaMaskingValue -Value $value -DataType datetime - $convertedValue.NewValue | Should -Be "'2020-10-05 10:10:10.123'" - } #> } Context "Handling multiple values" { - It "It should return a NULL value and text value" { + It "Should return a NULL value and text value" { $value = @($null, "this is just text") [array]$convertedValues = Convert-DbaMaskingValue -Value $value -Nullable:$true $convertedValues[0].NewValue | Should -Be 'NULL' @@ -99,12 +70,11 @@ Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { } Context "Error handling" { - It "It should return the value missing error" { + It "Should throw an error when value is missing" { { Convert-DbaMaskingValue -Value $null -DataType datetime -EnableException } | Should -Throw "Please enter a value" } - It "It should return the data type missing error" { + It "Should throw an error when data type is missing" { { Convert-DbaMaskingValue -Value "whatever" -EnableException } | Should -Throw "Please enter a data type" } } - -} \ No newline at end of file +} diff --git a/tests/ConvertTo-DbaTimeline.Tests.ps1 b/tests/ConvertTo-DbaTimeline.Tests.ps1 index 5653044053..6ba3e9c5b3 100644 --- a/tests/ConvertTo-DbaTimeline.Tests.ps1 +++ b/tests/ConvertTo-DbaTimeline.Tests.ps1 @@ -1,19 +1,27 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') + +Describe "ConvertTo-DbaTimeline Unit Tests" -Tag 'UnitTests' { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" + } -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'InputObject', 'ExcludeRowLabel', '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 { + $command = Get-Command ConvertTo-DbaTimeline + } + $parms = @( + 'InputObject', + 'ExcludeRowLabel', + 'EnableException' + ) + It "Should have parameter: <_>" -ForEach $parms { + $command | Should -HaveParameter $PSItem } } } + <# Integration test should appear below and are custom to the command you are writing. Read https://github.com/dataplat/dbatools/blob/development/contributing.md#tests - for more guidence. -#> \ No newline at end of file + for more guidance. +#> diff --git a/tests/ConvertTo-DbaXESession.Tests.ps1 b/tests/ConvertTo-DbaXESession.Tests.ps1 index d8d0a67166..c8571add07 100644 --- a/tests/ConvertTo-DbaXESession.Tests.ps1 +++ b/tests/ConvertTo-DbaXESession.Tests.ps1 @@ -1,112 +1,122 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') + +Describe "ConvertTo-DbaXESession" { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" + } -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'InputObject', 'Name', 'OutputScriptOnly', '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 { + $command = Get-Command ConvertTo-DbaXESession + } + $parms = @( + 'InputObject', + 'Name', + 'OutputScriptOnly', + 'EnableException' + ) + It "Has required parameter: <_>" -ForEach $parms { + $command | Should -HaveParameter $PSItem } } -} -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { - BeforeAll { - $sql = "-- Create a Queue - declare @rc int - declare @TraceID int - declare @maxfilesize bigint - set @maxfilesize = 5 - exec @rc = sp_trace_create @TraceID output, 0, N'C:\windows\temp\temptrace', @maxfilesize, NULL + Context "Test Trace Conversion" { + BeforeAll { + $sql = @" +-- Create a Queue +declare @rc int +declare @TraceID int +declare @maxfilesize bigint +set @maxfilesize = 5 +exec @rc = sp_trace_create @TraceID output, 0, N'C:\windows\temp\temptrace', @maxfilesize, NULL - -- Set the events - declare @on bit - set @on = 1 - exec sp_trace_setevent @TraceID, 14, 1, @on - exec sp_trace_setevent @TraceID, 14, 9, @on - exec sp_trace_setevent @TraceID, 14, 10, @on - exec sp_trace_setevent @TraceID, 14, 11, @on - exec sp_trace_setevent @TraceID, 14, 6, @on - exec sp_trace_setevent @TraceID, 14, 12, @on - exec sp_trace_setevent @TraceID, 14, 14, @on - exec sp_trace_setevent @TraceID, 15, 11, @on - exec sp_trace_setevent @TraceID, 15, 6, @on - exec sp_trace_setevent @TraceID, 15, 9, @on - exec sp_trace_setevent @TraceID, 15, 10, @on - exec sp_trace_setevent @TraceID, 15, 12, @on - exec sp_trace_setevent @TraceID, 15, 13, @on - exec sp_trace_setevent @TraceID, 15, 14, @on - exec sp_trace_setevent @TraceID, 15, 15, @on - exec sp_trace_setevent @TraceID, 15, 16, @on - exec sp_trace_setevent @TraceID, 15, 17, @on - exec sp_trace_setevent @TraceID, 15, 18, @on - exec sp_trace_setevent @TraceID, 17, 1, @on - exec sp_trace_setevent @TraceID, 17, 9, @on - exec sp_trace_setevent @TraceID, 17, 10, @on - exec sp_trace_setevent @TraceID, 17, 11, @on - exec sp_trace_setevent @TraceID, 17, 6, @on - exec sp_trace_setevent @TraceID, 17, 12, @on - exec sp_trace_setevent @TraceID, 17, 14, @on - exec sp_trace_setevent @TraceID, 10, 9, @on - exec sp_trace_setevent @TraceID, 10, 2, @on - exec sp_trace_setevent @TraceID, 10, 10, @on - exec sp_trace_setevent @TraceID, 10, 6, @on - exec sp_trace_setevent @TraceID, 10, 11, @on - exec sp_trace_setevent @TraceID, 10, 12, @on - exec sp_trace_setevent @TraceID, 10, 13, @on - exec sp_trace_setevent @TraceID, 10, 14, @on - exec sp_trace_setevent @TraceID, 10, 15, @on - exec sp_trace_setevent @TraceID, 10, 16, @on - exec sp_trace_setevent @TraceID, 10, 17, @on - exec sp_trace_setevent @TraceID, 10, 18, @on - exec sp_trace_setevent @TraceID, 12, 1, @on - exec sp_trace_setevent @TraceID, 12, 9, @on - exec sp_trace_setevent @TraceID, 12, 11, @on - exec sp_trace_setevent @TraceID, 12, 6, @on - exec sp_trace_setevent @TraceID, 12, 10, @on - exec sp_trace_setevent @TraceID, 12, 12, @on - exec sp_trace_setevent @TraceID, 12, 13, @on - exec sp_trace_setevent @TraceID, 12, 14, @on - exec sp_trace_setevent @TraceID, 12, 15, @on - exec sp_trace_setevent @TraceID, 12, 16, @on - exec sp_trace_setevent @TraceID, 12, 17, @on - exec sp_trace_setevent @TraceID, 12, 18, @on - exec sp_trace_setevent @TraceID, 13, 1, @on - exec sp_trace_setevent @TraceID, 13, 9, @on - exec sp_trace_setevent @TraceID, 13, 11, @on - exec sp_trace_setevent @TraceID, 13, 6, @on - exec sp_trace_setevent @TraceID, 13, 10, @on - exec sp_trace_setevent @TraceID, 13, 12, @on - exec sp_trace_setevent @TraceID, 13, 14, @on +-- Set the events +declare @on bit +set @on = 1 +exec sp_trace_setevent @TraceID, 14, 1, @on +exec sp_trace_setevent @TraceID, 14, 9, @on +exec sp_trace_setevent @TraceID, 14, 10, @on +exec sp_trace_setevent @TraceID, 14, 11, @on +exec sp_trace_setevent @TraceID, 14, 6, @on +exec sp_trace_setevent @TraceID, 14, 12, @on +exec sp_trace_setevent @TraceID, 14, 14, @on +exec sp_trace_setevent @TraceID, 15, 11, @on +exec sp_trace_setevent @TraceID, 15, 6, @on +exec sp_trace_setevent @TraceID, 15, 9, @on +exec sp_trace_setevent @TraceID, 15, 10, @on +exec sp_trace_setevent @TraceID, 15, 12, @on +exec sp_trace_setevent @TraceID, 15, 13, @on +exec sp_trace_setevent @TraceID, 15, 14, @on +exec sp_trace_setevent @TraceID, 15, 15, @on +exec sp_trace_setevent @TraceID, 15, 16, @on +exec sp_trace_setevent @TraceID, 15, 17, @on +exec sp_trace_setevent @TraceID, 15, 18, @on +exec sp_trace_setevent @TraceID, 17, 1, @on +exec sp_trace_setevent @TraceID, 17, 9, @on +exec sp_trace_setevent @TraceID, 17, 10, @on +exec sp_trace_setevent @TraceID, 17, 11, @on +exec sp_trace_setevent @TraceID, 17, 6, @on +exec sp_trace_setevent @TraceID, 17, 12, @on +exec sp_trace_setevent @TraceID, 17, 14, @on +exec sp_trace_setevent @TraceID, 10, 9, @on +exec sp_trace_setevent @TraceID, 10, 2, @on +exec sp_trace_setevent @TraceID, 10, 10, @on +exec sp_trace_setevent @TraceID, 10, 6, @on +exec sp_trace_setevent @TraceID, 10, 11, @on +exec sp_trace_setevent @TraceID, 10, 12, @on +exec sp_trace_setevent @TraceID, 10, 13, @on +exec sp_trace_setevent @TraceID, 10, 14, @on +exec sp_trace_setevent @TraceID, 10, 15, @on +exec sp_trace_setevent @TraceID, 10, 16, @on +exec sp_trace_setevent @TraceID, 10, 17, @on +exec sp_trace_setevent @TraceID, 10, 18, @on +exec sp_trace_setevent @TraceID, 12, 1, @on +exec sp_trace_setevent @TraceID, 12, 9, @on +exec sp_trace_setevent @TraceID, 12, 11, @on +exec sp_trace_setevent @TraceID, 12, 6, @on +exec sp_trace_setevent @TraceID, 12, 10, @on +exec sp_trace_setevent @TraceID, 12, 12, @on +exec sp_trace_setevent @TraceID, 12, 13, @on +exec sp_trace_setevent @TraceID, 12, 14, @on +exec sp_trace_setevent @TraceID, 12, 15, @on +exec sp_trace_setevent @TraceID, 12, 16, @on +exec sp_trace_setevent @TraceID, 12, 17, @on +exec sp_trace_setevent @TraceID, 12, 18, @on +exec sp_trace_setevent @TraceID, 13, 1, @on +exec sp_trace_setevent @TraceID, 13, 9, @on +exec sp_trace_setevent @TraceID, 13, 11, @on +exec sp_trace_setevent @TraceID, 13, 6, @on +exec sp_trace_setevent @TraceID, 13, 10, @on +exec sp_trace_setevent @TraceID, 13, 12, @on +exec sp_trace_setevent @TraceID, 13, 14, @on - -- Set the Filters - declare @intfilter int - declare @bigintfilter bigint +-- Set the Filters +declare @intfilter int +declare @bigintfilter bigint - exec sp_trace_setfilter @TraceID, 10, 0, 7, N'SQL Server Profiler - 934a8575-0dc1-4937-bde1-edac1cb9691f' - -- Set the trace status to start - exec sp_trace_setstatus @TraceID, 1 +exec sp_trace_setfilter @TraceID, 10, 0, 7, N'SQL Server Profiler - 934a8575-0dc1-4937-bde1-edac1cb9691f' +-- Set the trace status to start +exec sp_trace_setstatus @TraceID, 1 + +-- display trace id for future references +select TraceID=@TraceID +"@ + $server = Connect-DbaInstance -SqlInstance $global:instance2 + $traceid = ($server.Query($sql)).TraceID + $global:name = "dbatoolsci-session" + } + + AfterAll { + Remove-DbaXESession -SqlInstance $global:instance2 -Session $global:name -Confirm:$false + Remove-DbaTrace -SqlInstance $global:instance2 -Id $traceid -Confirm:$false + Remove-Item C:\windows\temp\temptrace.trc -ErrorAction SilentlyContinue + } - -- display trace id for future references - select TraceID=@TraceID" - $server = Connect-DbaInstance -SqlInstance $script:instance2 - $traceid = ($server.Query($sql)).TraceID - $script:name = "dbatoolsci-session" - } - AfterAll { - $null = Remove-DbaXESession -SqlInstance $script:instance2 -Session $script:name - $null = Remove-DbaTrace -SqlInstance $script:instance2 -Id $traceid - Remove-Item C:\windows\temp\temptrace.trc -ErrorAction SilentlyContinue - } - Context "Test Trace Conversion" { - $results = Get-DbaTrace -SqlInstance $script:instance2 -Id $traceid | ConvertTo-DbaXESession -Name $script:name | Start-DbaXESession It "returns the right results" { - $results.Name | Should Be $script:name - $results.Status | Should Be "Running" - $results.Targets.Name | Should Be "package0.event_file" + $results = Get-DbaTrace -SqlInstance $global:instance2 -Id $traceid | ConvertTo-DbaXESession -Name $global:name | Start-DbaXESession + $results.Name | Should -Be $global:name + $results.Status | Should -Be "Running" + $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 b4361ae41f..ee4f104d44 100644 --- a/tests/Copy-DbaAgentAlert.Tests.ps1 +++ b/tests/Copy-DbaAgentAlert.Tests.ps1 @@ -1,80 +1,96 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') + +Describe "Copy-DbaAgentAlert" { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" + } -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'Source', 'SourceSqlCredential', 'Destination', 'DestinationSqlCredential', 'Alert', 'ExcludeAlert', 'IncludeDefaults', 'Force', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + BeforeAll { + $command = Get-Command Copy-DbaAgentAlert + } + $parms = @( + 'Source', + 'SourceSqlCredential', + 'Destination', + 'DestinationSqlCredential', + 'Alert', + 'ExcludeAlert', + 'IncludeDefaults', + 'Force', + 'EnableException', + 'WhatIf', + 'Confirm' + ) + It "Has required parameter: <_>" -ForEach $parms { + $command | Should -HaveParameter $PSItem } } -} -Describe "$commandname Integration Tests" -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 $script:instance2 -Database master + Context "Integration Tests" -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 $global:instance2 -Database master - $server.Query("EXEC msdb.dbo.sp_add_alert @name=N'$($alert1)', - @message_id=0, - @severity=6, - @enabled=1, - @delay_between_responses=0, - @include_event_description_in=0, - @category_name=N'[Uncategorized]', - @job_id=N'00000000-0000-0000-0000-000000000000';") + $server.Query("EXEC msdb.dbo.sp_add_alert @name=N'$($alert1)', + @message_id=0, + @severity=6, + @enabled=1, + @delay_between_responses=0, + @include_event_description_in=0, + @category_name=N'[Uncategorized]', + @job_id=N'00000000-0000-0000-0000-000000000000';") - $server.Query("EXEC msdb.dbo.sp_add_alert @name=N'$($alert2)', - @message_id=0, - @severity=10, - @enabled=1, - @delay_between_responses=0, - @include_event_description_in=0, - @job_id=N'00000000-0000-0000-0000-000000000000';") + $server.Query("EXEC msdb.dbo.sp_add_alert @name=N'$($alert2)', + @message_id=0, + @severity=10, + @enabled=1, + @delay_between_responses=0, + @include_event_description_in=0, + @job_id=N'00000000-0000-0000-0000-000000000000';") - $server.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)', - @operator_name = N'$operatorName', - @notification_method = 1 ;") - } - AfterAll { - $server = Connect-DbaInstance -SqlInstance $script: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)'") + $server.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)', + @operator_name = N'$operatorName', + @notification_method = 1 ;") + } - $server = Connect-DbaInstance -SqlInstance $script:instance3 -Database master - $server.Query("EXEC msdb.dbo.sp_delete_alert @name=N'$($alert1)'") - } + AfterAll { + $server = Connect-DbaInstance -SqlInstance $global: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)'") - It "Copies the sample alert" { - $results = Copy-DbaAgentAlert -Source $script:instance2 -Destination $script:instance3 -Alert $alert1 - $results.Name -eq 'dbatoolsci test alert', 'dbatoolsci test alert' - $results.Status -eq 'Successful', 'Successful' - } + $server = Connect-DbaInstance -SqlInstance $global:instance3 -Database master + $server.Query("EXEC msdb.dbo.sp_delete_alert @name=N'$($alert1)'") + } - It "Skips alerts where destination is missing the operator" { - $results = Copy-DbaAgentAlert -Source $script:instance2 -Destination $script:instance3 -Alert $alert2 -WarningAction SilentlyContinue - $results.Status -eq 'Skipped', 'Skipped' - } + It "Copies the sample alert" { + $results = Copy-DbaAgentAlert -Source $global:instance2 -Destination $global:instance3 -Alert $alert1 + $results.Name | Should -Be @('dbatoolsci test alert', 'dbatoolsci test alert') + $results.Status | Should -Be @('Successful', 'Successful') + } - It "Doesn't overwrite existing alerts" { - $results = Copy-DbaAgentAlert -Source $script:instance2 -Destination $script:instance3 -Alert $alert1 - $results.Name -eq 'dbatoolsci test alert' - $results.Status -eq 'Skipped' - } + It "Skips alerts where destination is missing the operator" { + $results = Copy-DbaAgentAlert -Source $global:instance2 -Destination $global:instance3 -Alert $alert2 -WarningAction SilentlyContinue + $results.Status | Should -Be @('Skipped', 'Skipped') + } - It "The newly copied alert exists" { - $results = Get-DbaAgentAlert -SqlInstance $script:instance2 - $results.Name -contains 'dbatoolsci test alert' + It "Doesn't overwrite existing alerts" { + $results = Copy-DbaAgentAlert -Source $global:instance2 -Destination $global:instance3 -Alert $alert1 + $results.Name | Should -Be 'dbatoolsci test alert' + $results.Status | Should -Be 'Skipped' + } + + It "The newly copied alert exists" { + $results = Get-DbaAgentAlert -SqlInstance $global:instance3 + $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 aeb6367215..9520cd1195 100644 --- a/tests/Copy-DbaAgentJob.Tests.ps1 +++ b/tests/Copy-DbaAgentJob.Tests.ps1 @@ -1,49 +1,57 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'Source', 'SourceSqlCredential', 'Destination', 'DestinationSqlCredential', 'Job', 'ExcludeJob', 'DisableOnSource', 'DisableOnDestination', 'Force', 'EnableException', 'InputObject' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 - } +Describe "Copy-DbaAgentJob" { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" } -} -Describe "$commandname Integration Tests" -Tag "IntegrationTests" { - BeforeAll { - $null = New-DbaAgentJob -SqlInstance $script:instance2 -Job dbatoolsci_copyjob - $null = New-DbaAgentJob -SqlInstance $script:instance2 -Job dbatoolsci_copyjob_disabled - $sourcejobs = Get-DbaAgentJob -SqlInstance $script:instance2 - $destjobs = Get-DbaAgentJob -SqlInstance $script:instance3 - } - AfterAll { - $null = Remove-DbaAgentJob -SqlInstance $script:instance2 -Job dbatoolsci_copyjob, dbatoolsci_copyjob_disabled -Confirm:$false - $null = Remove-DbaAgentJob -SqlInstance $script:instance3 -Job dbatoolsci_copyjob, dbatoolsci_copyjob_disabled -Confirm:$false + Context "Validate parameters" { + BeforeAll { + $command = Get-Command Copy-DbaAgentJob + } + $paramList = @( + 'Source', 'SourceSqlCredential', 'Destination', 'DestinationSqlCredential', + 'Job', 'ExcludeJob', 'DisableOnSource', 'DisableOnDestination', + 'Force', 'InputObject', 'EnableException' + ) + It "Should have parameter: <_>" -ForEach $paramList { + $command | Should -HaveParameter $_ -Because "this parameter is required" + } + It "Should have WhatIf and Confirm switch parameters" { + $command | Should -HaveParameter WhatIf -Mandatory:$false -Type switch + $command | Should -HaveParameter Confirm -Mandatory:$false -Type switch + } } - Context "Command copies jobs properly" { - $results = Copy-DbaAgentJob -Source $script:instance2 -Destination $script:instance3 -Job dbatoolsci_copyjob + Context "Command copies jobs properly" -Tag "IntegrationTests" { + BeforeAll { + $null = New-DbaAgentJob -SqlInstance $global:instance2 -Job dbatoolsci_copyjob + $null = New-DbaAgentJob -SqlInstance $global:instance2 -Job dbatoolsci_copyjob_disabled + $sourcejobs = Get-DbaAgentJob -SqlInstance $global:instance2 + $destjobs = Get-DbaAgentJob -SqlInstance $global:instance3 + } + AfterAll { + $null = Remove-DbaAgentJob -SqlInstance $global:instance2 -Job dbatoolsci_copyjob, dbatoolsci_copyjob_disabled -Confirm:$false + $null = Remove-DbaAgentJob -SqlInstance $global:instance3 -Job dbatoolsci_copyjob, dbatoolsci_copyjob_disabled -Confirm:$false + } It "returns one success" { + $results = Copy-DbaAgentJob -Source $global:instance2 -Destination $global:instance3 -Job dbatoolsci_copyjob $results.Name | Should -Be "dbatoolsci_copyjob" $results.Status | Should -Be "Successful" } It "did not copy dbatoolsci_copyjob_disabled" { - Get-DbaAgentJob -SqlInstance $script:instance3 -Job dbatoolsci_copyjob_disabled | Should -Be $null + Get-DbaAgentJob -SqlInstance $global:instance3 -Job dbatoolsci_copyjob_disabled | Should -BeNullOrEmpty } It "disables jobs when requested" { - (Get-DbaAgentJob -SqlInstance $script:instance2 -Job dbatoolsci_copyjob_disabled).Enabled - $results = Copy-DbaAgentJob -Source $script:instance2 -Destination $script:instance3 -Job dbatoolsci_copyjob_disabled -DisableOnSource -DisableOnDestination -Force + (Get-DbaAgentJob -SqlInstance $global:instance2 -Job dbatoolsci_copyjob_disabled).Enabled | Should -BeTrue + $results = Copy-DbaAgentJob -Source $global:instance2 -Destination $global:instance3 -Job dbatoolsci_copyjob_disabled -DisableOnSource -DisableOnDestination -Force $results.Name | Should -Be "dbatoolsci_copyjob_disabled" $results.Status | Should -Be "Successful" - (Get-DbaAgentJob -SqlInstance $script:instance2 -Job dbatoolsci_copyjob_disabled).Enabled | Should -Be $false - (Get-DbaAgentJob -SqlInstance $script:instance3 -Job dbatoolsci_copyjob_disabled).Enabled | Should -Be $false + (Get-DbaAgentJob -SqlInstance $global:instance2 -Job dbatoolsci_copyjob_disabled).Enabled | Should -BeFalse + (Get-DbaAgentJob -SqlInstance $global: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 d6c4745b30..06eaf4bea0 100644 --- a/tests/Copy-DbaAgentJobCategory.Tests.ps1 +++ b/tests/Copy-DbaAgentJobCategory.Tests.ps1 @@ -1,37 +1,51 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') + +Describe "Copy-DbaAgentJobCategory" { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" + } -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'Source', 'SourceSqlCredential', 'Destination', 'DestinationSqlCredential', 'CategoryType', 'JobCategory', 'AgentCategory', 'OperatorCategory', 'Force', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + BeforeAll { + $command = Get-Command Copy-DbaAgentJobCategory + } + $paramList = @( + 'Source', + 'SourceSqlCredential', + 'Destination', + 'DestinationSqlCredential', + 'CategoryType', + 'JobCategory', + 'AgentCategory', + 'OperatorCategory', + 'Force', + 'EnableException', + 'WhatIf', + 'Confirm' + ) + It "Should have parameter: <_>" -ForEach $paramList { + $command | Should -HaveParameter $PSItem } } -} -Describe "$commandname Integration Tests" -Tag "IntegrationTests" { - BeforeAll { - $null = New-DbaAgentJobCategory -SqlInstance $script:instance2 -Category 'dbatoolsci test category' - } - AfterAll { - $null = Remove-DbaAgentJobCategory -SqlInstance $script:instance2 -Category 'dbatoolsci test category' -Confirm:$false - } + Context "Command copies jobs properly" -Tag "IntegrationTests" { + BeforeAll { + $null = New-DbaAgentJobCategory -SqlInstance $global:instance2 -Category 'dbatoolsci test category' + } + AfterAll { + $null = Remove-DbaAgentJobCategory -SqlInstance $global:instance2 -Category 'dbatoolsci test category' -Confirm:$false + } - Context "Command copies jobs properly" { It "returns one success" { - $results = Copy-DbaAgentJobCategory -Source $script:instance2 -Destination $script:instance3 -JobCategory 'dbatoolsci test category' - $results.Name -eq "dbatoolsci test category" - $results.Status -eq "Successful" + $results = Copy-DbaAgentJobCategory -Source $global:instance2 -Destination $global:instance3 -JobCategory 'dbatoolsci test category' + $results.Name | Should -Be "dbatoolsci test category" + $results.Status | Should -Be "Successful" } It "does not overwrite" { - $results = Copy-DbaAgentJobCategory -Source $script:instance2 -Destination $script:instance3 -JobCategory 'dbatoolsci test category' - $results.Name -eq "dbatoolsci test category" - $results.Status -eq "Skipped" + $results = Copy-DbaAgentJobCategory -Source $global:instance2 -Destination $global:instance3 -JobCategory 'dbatoolsci test category' + $results.Name | Should -Be "dbatoolsci test category" + $results.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 3b33a2d478..4eaabcc1de 100644 --- a/tests/Copy-DbaAgentOperator.Tests.ps1 +++ b/tests/Copy-DbaAgentOperator.Tests.ps1 @@ -1,51 +1,59 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') + +Describe "Copy-DbaAgentOperator" { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" + } -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'Source', 'SourceSqlCredential', 'Destination', 'DestinationSqlCredential', 'Operator', 'ExcludeOperator', 'Force', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + BeforeAll { + $command = Get-Command Copy-DbaAgentOperator + } + $paramCount = 10 + $knownParameters = [object[]]@( + 'Source', 'SourceSqlCredential', 'Destination', 'DestinationSqlCredential', + 'Operator', 'ExcludeOperator', 'Force', 'EnableException', 'WhatIf', 'Confirm' + ) + It "Should contain parameters" { + $command.Parameters.Count - $command.Parameters.Values.Where({$_.Attributes.DontShow}).Count | Should -Be $paramCount + } + It "Should contain parameter: <_>" -ForEach $knownParameters { + $command | Should -HaveParameter $_ } } -} -Describe "$commandname Integration Tests" -Tag "IntegrationTests" { - BeforeAll { - $server = Connect-DbaInstance -SqlInstance $script: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) - } - AfterAll { - $server = Connect-DbaInstance -SqlInstance $script: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) + Context "Copies operators" { + BeforeAll { + $server = Connect-DbaInstance -SqlInstance $global: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) + } - $server = Connect-DbaInstance -SqlInstance $script: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) - } + AfterAll { + $server = Connect-DbaInstance -SqlInstance $global: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) - Context "Copies operators" { - $results = Copy-DbaAgentOperator -Source $script:instance2 -Destination $script:instance3 -Operator dbatoolsci_operator, dbatoolsci_operator2 + $server = Connect-DbaInstance -SqlInstance $global: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) + } - It "returns two results" { - $results.Count -eq 2 - $results.Status -eq "Successful", "Successful" + It "returns two successful results" { + $results = Copy-DbaAgentOperator -Source $global:instance2 -Destination $global:instance3 -Operator dbatoolsci_operator, dbatoolsci_operator2 + $results.Count | Should -Be 2 + $results.Status | Should -Be @("Successful", "Successful") } - It "return one result that's skipped" { - $results = Copy-DbaAgentOperator -Source $script:instance2 -Destination $script:instance3 -Operator dbatoolsci_operator - $results.Status -eq "Skipped" + It "returns one skipped result" { + $results = Copy-DbaAgentOperator -Source $global:instance2 -Destination $global:instance3 -Operator dbatoolsci_operator + $results.Status | Should -Be "Skipped" } } -} \ No newline at end of file +} diff --git a/tests/Copy-DbaAgentProxy.Tests.ps1 b/tests/Copy-DbaAgentProxy.Tests.ps1 index 5b4e8f25c0..265404d514 100644 --- a/tests/Copy-DbaAgentProxy.Tests.ps1 +++ b/tests/Copy-DbaAgentProxy.Tests.ps1 @@ -1,55 +1,67 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'Source', 'SourceSqlCredential', 'Destination', 'DestinationSqlCredential', 'ProxyAccount', 'ExcludeProxyAccount', 'Force', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 - } +Describe "Copy-DbaAgentProxy" { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" } -} -Describe "$commandname Integration Tests" -Tag "IntegrationTests" { - BeforeAll { - $server = Connect-DbaInstance -SqlInstance $script:instance2 - $sql = "CREATE CREDENTIAL dbatoolsci_credential WITH IDENTITY = 'sa', SECRET = 'dbatools'" - $server.Query($sql) - $sql = "EXEC msdb.dbo.sp_add_proxy @proxy_name = 'dbatoolsci_agentproxy', @enabled = 1, @credential_name = 'dbatoolsci_credential'" - $server.Query($sql) - - $server = Connect-DbaInstance -SqlInstance $script:instance3 - $sql = "CREATE CREDENTIAL dbatoolsci_credential WITH IDENTITY = 'sa', SECRET = 'dbatools'" - $server.Query($sql) - } - AfterAll { - $server = Connect-DbaInstance -SqlInstance $script:instance2 - $sql = "EXEC msdb.dbo.sp_delete_proxy @proxy_name = 'dbatoolsci_agentproxy'" - $server.Query($sql) - $sql = "DROP CREDENTIAL dbatoolsci_credential" - $server.Query($sql) - - $server = Connect-DbaInstance -SqlInstance $script:instance3 - $sql = "EXEC msdb.dbo.sp_delete_proxy @proxy_name = 'dbatoolsci_agentproxy'" - $server.Query($sql) - $sql = "DROP CREDENTIAL dbatoolsci_credential" - $server.Query($sql) + Context "Validate parameters" { + BeforeAll { + $command = Get-Command Copy-DbaAgentProxy + } + $paramList = @( + 'Source', + 'SourceSqlCredential', + 'Destination', + 'DestinationSqlCredential', + 'ProxyAccount', + 'ExcludeProxyAccount', + 'Force', + 'EnableException', + 'WhatIf', + 'Confirm' + ) + It "Should have parameter: <_>" -ForEach $paramList { + $command | Should -HaveParameter $PSItem + } } Context "Copies Agent Proxy" { - $results = Copy-DbaAgentProxy -Source $script:instance2 -Destination $script:instance3 -ProxyAccount dbatoolsci_agentproxy + BeforeAll { + $server = Connect-DbaInstance -SqlInstance $global:instance2 + $sql = "CREATE CREDENTIAL dbatoolsci_credential WITH IDENTITY = 'sa', SECRET = 'dbatools'" + $server.Query($sql) + $sql = "EXEC msdb.dbo.sp_add_proxy @proxy_name = 'dbatoolsci_agentproxy', @enabled = 1, @credential_name = 'dbatoolsci_credential'" + $server.Query($sql) - It "returns one results" { - $results.Count -eq 1 - $results.Status -eq "Successful" + $server = Connect-DbaInstance -SqlInstance $global:instance3 + $sql = "CREATE CREDENTIAL dbatoolsci_credential WITH IDENTITY = 'sa', SECRET = 'dbatools'" + $server.Query($sql) } - It "return one result that's skipped" { - $results = Get-DbaAgentProxy -SqlInstance $script:instance3 -Proxy dbatoolsci_agentproxy - $results.Count -eq 1 + AfterAll { + $server = Connect-DbaInstance -SqlInstance $global:instance2 + $sql = "EXEC msdb.dbo.sp_delete_proxy @proxy_name = 'dbatoolsci_agentproxy'" + $server.Query($sql) + $sql = "DROP CREDENTIAL dbatoolsci_credential" + $server.Query($sql) + + $server = Connect-DbaInstance -SqlInstance $global:instance3 + $sql = "EXEC msdb.dbo.sp_delete_proxy @proxy_name = 'dbatoolsci_agentproxy'" + $server.Query($sql) + $sql = "DROP CREDENTIAL dbatoolsci_credential" + $server.Query($sql) + } + + It "returns one successful result" { + $results = Copy-DbaAgentProxy -Source $global:instance2 -Destination $global:instance3 -ProxyAccount dbatoolsci_agentproxy + $results.Count | Should -Be 1 + $results.Status | Should -Be "Successful" + } + + It "creates one proxy on the destination" { + $results = Get-DbaAgentProxy -SqlInstance $global:instance3 -Proxy dbatoolsci_agentproxy + $results.Count | Should -Be 1 } } -} \ No newline at end of file +} diff --git a/tests/Copy-DbaAgentSchedule.Tests.ps1 b/tests/Copy-DbaAgentSchedule.Tests.ps1 index a622127b7e..8366877d2d 100644 --- a/tests/Copy-DbaAgentSchedule.Tests.ps1 +++ b/tests/Copy-DbaAgentSchedule.Tests.ps1 @@ -1,46 +1,58 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'Source', 'SourceSqlCredential', 'Destination', 'DestinationSqlCredential', 'Force', 'EnableException', 'Schedule', 'Id', 'InputObject' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 - } +Describe "Copy-DbaAgentSchedule" { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" } -} -Describe "$commandname Integration Tests" -Tag "IntegrationTests" { - BeforeAll { - $server = Connect-DbaInstance -SqlInstance $script:instance2 - $sql = "EXEC msdb.dbo.sp_add_schedule @schedule_name = N'dbatoolsci_DailySchedule' , @freq_type = 4, @freq_interval = 1, @active_start_time = 010000" - $server.Query($sql) + Context "Validate parameters" { + BeforeAll { + $command = Get-Command Copy-DbaAgentSchedule + } + $paramList = @( + 'Source', + 'SourceSqlCredential', + 'Destination', + 'DestinationSqlCredential', + 'Schedule', + 'Id', + 'InputObject', + 'Force', + 'EnableException', + 'WhatIf', + 'Confirm' + ) + It "Should have parameter: <_>" -ForEach $paramList { + $command | Should -HaveParameter $PSItem + } } - AfterAll { - $server = Connect-DbaInstance -SqlInstance $script:instance2 - $sql = "EXEC msdb.dbo.sp_delete_schedule @schedule_name = 'dbatoolsci_DailySchedule'" - $server.Query($sql) - $server = Connect-DbaInstance -SqlInstance $script:instance3 - $sql = "EXEC msdb.dbo.sp_delete_schedule @schedule_name = 'dbatoolsci_DailySchedule'" - $server.Query($sql) + Context "Copies Agent Schedule" { + BeforeAll { + $server = Connect-DbaInstance -SqlInstance $global:instance2 + $sql = "EXEC msdb.dbo.sp_add_schedule @schedule_name = N'dbatoolsci_DailySchedule' , @freq_type = 4, @freq_interval = 1, @active_start_time = 010000" + $server.Query($sql) + } - } + AfterAll { + $server = Connect-DbaInstance -SqlInstance $global:instance2 + $sql = "EXEC msdb.dbo.sp_delete_schedule @schedule_name = 'dbatoolsci_DailySchedule'" + $server.Query($sql) - Context "Copies Agent Schedule" { - $results = Copy-DbaAgentSchedule -Source $script:instance2 -Destination $script:instance3 + $server = Connect-DbaInstance -SqlInstance $global:instance3 + $sql = "EXEC msdb.dbo.sp_delete_schedule @schedule_name = 'dbatoolsci_DailySchedule'" + $server.Query($sql) + } - It "returns one results" { + It "returns more than one result with at least one successful" { + $results = Copy-DbaAgentSchedule -Source $global:instance2 -Destination $global:instance3 $results.Count | Should -BeGreaterThan 1 - ($results | Where Status -eq "Successful") | Should -Not -Be $null + $results | Where-Object Status -eq "Successful" | Should -Not -BeNullOrEmpty } - It "return one result of Start Time 1:00 AM" { - $results = Get-DbaAgentSchedule -SqlInstance $script:instance3 -Schedule dbatoolsci_DailySchedule - $results.ActiveStartTimeOfDay -eq '01:00:00' + It "returns one result of Start Time 1:00 AM" { + $results = Get-DbaAgentSchedule -SqlInstance $global:instance3 -Schedule dbatoolsci_DailySchedule + $results.ActiveStartTimeOfDay | Should -Be '01:00:00' } } -} \ No newline at end of file +} diff --git a/tests/Copy-DbaAgentServer.Tests.ps1 b/tests/Copy-DbaAgentServer.Tests.ps1 index 99190ba341..80773ff28c 100644 --- a/tests/Copy-DbaAgentServer.Tests.ps1 +++ b/tests/Copy-DbaAgentServer.Tests.ps1 @@ -1,19 +1,35 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') + +Describe "Copy-DbaAgentServer Unit Tests" -Tag 'UnitTests' { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" + } -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'Source', 'SourceSqlCredential', 'Destination', 'DestinationSqlCredential', 'DisableJobsOnDestination', 'DisableJobsOnSource', 'ExcludeServerProperties', 'Force', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + BeforeAll { + $command = Get-Command Copy-DbaAgentServer + } + $knownParameters = @( + 'Source', + 'SourceSqlCredential', + 'Destination', + 'DestinationSqlCredential', + 'DisableJobsOnDestination', + 'DisableJobsOnSource', + 'ExcludeServerProperties', + 'Force', + 'EnableException', + 'WhatIf', + 'Confirm' + ) + It "Should have the correct parameters" -ForEach $knownParameters { + $command | Should -HaveParameter $PSItem } } } + <# Integration test should appear below and are custom to the command you are writing. Read https://github.com/dataplat/dbatools/blob/development/contributing.md#tests - for more guidence. -#> \ No newline at end of file + for more guidance. +#> diff --git a/tests/Copy-DbaBackupDevice.Tests.ps1 b/tests/Copy-DbaBackupDevice.Tests.ps1 index 70d7ba6260..d0826d2e19 100644 --- a/tests/Copy-DbaBackupDevice.Tests.ps1 +++ b/tests/Copy-DbaBackupDevice.Tests.ps1 @@ -1,55 +1,64 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') + +Describe "Copy-DbaBackupDevice" { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" + } -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'Source', 'SourceSqlCredential', 'Destination', 'DestinationSqlCredential', 'BackupDevice', 'Force', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + BeforeAll { + $command = Get-Command Copy-DbaBackupDevice + } + $parms = @( + 'Source', + 'SourceSqlCredential', + 'Destination', + 'DestinationSqlCredential', + 'BackupDevice', + 'Force', + 'EnableException', + 'WhatIf', + 'Confirm' + ) + It "Has required parameter: <_>" -ForEach $parms { + $command | Should -HaveParameter $PSItem } } -} -if (-not $env:appveyor) { - Describe "$commandname Integration Tests" -Tags "IntegrationTests" { - Context "Setup" { - BeforeAll { - $devicename = "dbatoolsci-backupdevice" - $backupdir = (Get-DbaDefaultPath -SqlInstance $script:instance1).Backup - $backupfilename = "$backupdir\$devicename.bak" - $server = Connect-DbaInstance -SqlInstance $script:instance1 - $server.Query("EXEC master.dbo.sp_addumpdevice @devtype = N'disk', @logicalname = N'$devicename',@physicalname = N'$backupfilename'") - $server.Query("BACKUP DATABASE master TO DISK = '$backupfilename'") - } - AfterAll { - $server.Query("EXEC master.dbo.sp_dropdevice @logicalname = N'$devicename'") - $server1 = Connect-DbaInstance -SqlInstance $script:instance2 - try { - $server1.Query("EXEC master.dbo.sp_dropdevice @logicalname = N'$devicename'") - } catch { - # don't care - } - Get-ChildItem -Path $backupfilename | Remove-Item + Context "Integration Tests" -Tag "IntegrationTests" { + BeforeAll { + $devicename = "dbatoolsci-backupdevice" + $backupdir = (Get-DbaDefaultPath -SqlInstance $global:instance1).Backup + $backupfilename = "$backupdir\$devicename.bak" + $server = Connect-DbaInstance -SqlInstance $global:instance1 + $server.Query("EXEC master.dbo.sp_addumpdevice @devtype = N'disk', @logicalname = N'$devicename',@physicalname = N'$backupfilename'") + $server.Query("BACKUP DATABASE master TO DISK = '$backupfilename'") + } + + AfterAll { + $server.Query("EXEC master.dbo.sp_dropdevice @logicalname = N'$devicename'") + $server1 = Connect-DbaInstance -SqlInstance $global:instance2 + try { + $server1.Query("EXEC master.dbo.sp_dropdevice @logicalname = N'$devicename'") + } catch { + # don't care } + Get-ChildItem -Path $backupfilename | Remove-Item + } - $results = Copy-DbaBackupDevice -Source $script:instance1 -Destination $script:instance2 -WarningVariable warn -WarningAction SilentlyContinue 3> $null + It "Should warn if it has a problem moving (issue for local to local)" { + $warn = $null + $results = Copy-DbaBackupDevice -Source $global:instance1 -Destination $global:instance2 -WarningVariable warn -WarningAction SilentlyContinue 3> $null if ($warn) { - It "warns if it has a problem moving (issue for local to local)" { - $warn | Should -Match "backup device to destination" - } + $warn | Should -Match "backup device to destination" } else { - It "should report success" { - $results.Status | Should Be "Successful" - } + $results.Status | Should -Be "Successful" } + } - $results = Copy-DbaBackupDevice -Source $script:instance1 -Destination $script:instance2 - It "Should say skipped" { - $results.Status -ne "Successful" | Should be $true - } + It "Should say skipped when copying again" { + $results = Copy-DbaBackupDevice -Source $global:instance1 -Destination $global:instance2 + $results.Status | Should -Not -Be "Successful" } } -} \ No newline at end of file +} diff --git a/tests/Copy-DbaCredential.Tests.ps1 b/tests/Copy-DbaCredential.Tests.ps1 index 326f47ccf1..045b2d26cf 100644 --- a/tests/Copy-DbaCredential.Tests.ps1 +++ b/tests/Copy-DbaCredential.Tests.ps1 @@ -1,137 +1,124 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" -. "$PSScriptRoot\..\private\functions\Invoke-Command2.ps1" +param($ModuleName = 'dbatools') -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'Source', 'SourceSqlCredential', 'Credential', 'Destination', 'DestinationSqlCredential', 'Name', 'ExcludeName', 'Identity', 'ExcludeIdentity', 'Force', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 - } +Describe "Copy-DbaCredential" { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" + . "$PSScriptRoot\..\private\functions\Invoke-Command2.ps1" } -} -Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { BeforeAll { $logins = "dbatoolsci_thor", "dbatoolsci_thorsmomma", "dbatoolsci_thor_crypto" $plaintext = "BigOlPassword!" $password = ConvertTo-SecureString $plaintext -AsPlainText -Force - $server2 = Connect-DbaInstance -SqlInstance $script:instance2 - $server3 = Connect-DbaInstance -SqlInstance $script:instance3 + $global:server2 = Connect-DbaInstance -SqlInstance $global:instance2 + $global:server3 = Connect-DbaInstance -SqlInstance $global:instance3 # Add user foreach ($login in $logins) { - $null = Invoke-Command2 -ScriptBlock { net user $args[0] $args[1] /add *>&1 } -ArgumentList $login, $plaintext -ComputerName $script:instance2 - $null = Invoke-Command2 -ScriptBlock { net user $args[0] $args[1] /add *>&1 } -ArgumentList $login, $plaintext -ComputerName $script:instance3 + $null = Invoke-Command2 -ScriptBlock { net user $args[0] $args[1] /add *>&1 } -ArgumentList $login, $plaintext -ComputerName $global:instance2 + $null = Invoke-Command2 -ScriptBlock { net user $args[0] $args[1] /add *>&1 } -ArgumentList $login, $plaintext -ComputerName $global:instance3 } - <# - New tests have been added for validating a credential that uses a crypto provider. (Ref: https://github.com/dataplat/dbatools/issues/7896) - - The new pester tests will only run if a crypto provider is registered and enabled. - - Follow these steps to configure the local machine to run the crypto provider tests. - - 1. Run these SQL commands on the instance2 and instance3 servers: - - -- Enable advanced options. - USE master; - GO - sp_configure 'show advanced options', 1; - GO - RECONFIGURE; - GO - -- Enable EKM provider - sp_configure 'EKM provider enabled', 1; - GO - RECONFIGURE; - - 2. Install https://www.microsoft.com/en-us/download/details.aspx?id=45344 on the instance2 and instance3 servers. - - 3. Run these SQL commands on the instance2 and instance3 servers: - - CREATE CRYPTOGRAPHIC PROVIDER dbatoolsci_AKV FROM FILE = 'C:\github\appveyor-lab\keytests\ekm\Microsoft.AzureKeyVaultService.EKM.dll' - #> - # check to see if a crypto provider is present on the instances - $instance2CryptoProviders = $server2.Query("SELECT name FROM sys.cryptographic_providers WHERE is_enabled = 1 ORDER BY name") - $instance3CryptoProviders = $server3.Query("SELECT name FROM sys.cryptographic_providers WHERE is_enabled = 1 ORDER BY name") + $instance2CryptoProviders = $global:server2.Query("SELECT name FROM sys.cryptographic_providers WHERE is_enabled = 1 ORDER BY name") + $instance3CryptoProviders = $global:server3.Query("SELECT name FROM sys.cryptographic_providers WHERE is_enabled = 1 ORDER BY name") - $cryptoProvider = ($instance2CryptoProviders | Where-Object { $_.name -eq $instance3CryptoProviders.name } | Select-Object -First 1).name + $global:cryptoProvider = ($instance2CryptoProviders | Where-Object { $_.name -eq $instance3CryptoProviders.name } | Select-Object -First 1).name } + AfterAll { - (Get-DbaCredential -SqlInstance $server2 -Identity dbatoolsci_thor, dbatoolsci_thorsmomma, dbatoolsci_thor_crypto -ErrorAction Stop -WarningAction SilentlyContinue).Drop() - (Get-DbaCredential -SqlInstance $server3 -Identity dbatoolsci_thor, dbatoolsci_thorsmomma, dbatoolsci_thor_crypto -ErrorAction Stop -WarningAction SilentlyContinue).Drop() + (Get-DbaCredential -SqlInstance $global:server2 -Identity dbatoolsci_thor, dbatoolsci_thorsmomma, dbatoolsci_thor_crypto -ErrorAction Stop -WarningAction SilentlyContinue).Drop() + (Get-DbaCredential -SqlInstance $global:server3 -Identity dbatoolsci_thor, dbatoolsci_thorsmomma, dbatoolsci_thor_crypto -ErrorAction Stop -WarningAction SilentlyContinue).Drop() foreach ($login in $logins) { - $null = Invoke-Command2 -ScriptBlock { net user $args /delete *>&1 } -ArgumentList $login -ComputerName $script:instance2 - $null = Invoke-Command2 -ScriptBlock { net user $args /delete *>&1 } -ArgumentList $login -ComputerName $script:instance3 + $null = Invoke-Command2 -ScriptBlock { net user $args /delete *>&1 } -ArgumentList $login -ComputerName $global:instance2 + $null = Invoke-Command2 -ScriptBlock { net user $args /delete *>&1 } -ArgumentList $login -ComputerName $global:instance3 + } + } + + Context "Validate parameters" { + BeforeAll { + $command = Get-Command Copy-DbaCredential + } + $parms = @( + 'Source', + 'SourceSqlCredential', + 'Credential', + 'Destination', + 'DestinationSqlCredential', + 'Name', + 'ExcludeName', + 'Identity', + 'ExcludeIdentity', + 'Force', + 'EnableException', + 'WhatIf', + 'Confirm' + ) + It "Has required parameter: <_>" -ForEach $parms { + $command | Should -HaveParameter $PSItem } } Context "Create new credential" { It "Should create new credentials with the proper properties" { - $results = New-DbaCredential -SqlInstance $server2 -Name dbatoolsci_thorcred -Identity dbatoolsci_thor -Password $password - $results.Name | Should Be "dbatoolsci_thorcred" - $results.Identity | Should Be "dbatoolsci_thor" - - $results = New-DbaCredential -SqlInstance $server2 -Identity dbatoolsci_thorsmomma -Password $password - $results.Name | Should Be "dbatoolsci_thorsmomma" - $results.Identity | Should Be "dbatoolsci_thorsmomma" - - if ($cryptoProvider) { - $results = New-DbaCredential -SqlInstance $server2 -Identity dbatoolsci_thor_crypto -Password $password -MappedClassType CryptographicProvider -ProviderName $cryptoProvider - $results.Name | Should Be "dbatoolsci_thor_crypto" - $results.Identity | Should Be "dbatoolsci_thor_crypto" - $results.ProviderName | Should -Be $cryptoProvider + $results = New-DbaCredential -SqlInstance $global:server2 -Name dbatoolsci_thorcred -Identity dbatoolsci_thor -Password $password + $results.Name | Should -Be "dbatoolsci_thorcred" + $results.Identity | Should -Be "dbatoolsci_thor" + + $results = New-DbaCredential -SqlInstance $global:server2 -Identity dbatoolsci_thorsmomma -Password $password + $results.Name | Should -Be "dbatoolsci_thorsmomma" + $results.Identity | Should -Be "dbatoolsci_thorsmomma" + + if ($global:cryptoProvider) { + $results = New-DbaCredential -SqlInstance $global:server2 -Identity dbatoolsci_thor_crypto -Password $password -MappedClassType CryptographicProvider -ProviderName $global:cryptoProvider + $results.Name | Should -Be "dbatoolsci_thor_crypto" + $results.Identity | Should -Be "dbatoolsci_thor_crypto" + $results.ProviderName | Should -Be $global:cryptoProvider } } } Context "Copy Credential with the same properties." { It "Should copy successfully" { - $results = Copy-DbaCredential -Source $server2 -Destination $server3 -Name dbatoolsci_thorcred - $results.Status | Should Be "Successful" + $results = Copy-DbaCredential -Source $global:server2 -Destination $global:server3 -Name dbatoolsci_thorcred + $results.Status | Should -Be "Successful" } It "Should retain its same properties" { - $Credential1 = Get-DbaCredential -SqlInstance $server2 -Name dbatoolsci_thor -ErrorAction SilentlyContinue -WarningAction SilentlyContinue - $Credential2 = Get-DbaCredential -SqlInstance $server3 -Name dbatoolsci_thor -ErrorAction SilentlyContinue -WarningAction SilentlyContinue + $Credential1 = Get-DbaCredential -SqlInstance $global:server2 -Name dbatoolsci_thor -ErrorAction SilentlyContinue -WarningAction SilentlyContinue + $Credential2 = Get-DbaCredential -SqlInstance $global:server3 -Name dbatoolsci_thor -ErrorAction SilentlyContinue -WarningAction SilentlyContinue # Compare its value - $Credential1.Name | Should Be $Credential2.Name - $Credential1.Identity | Should Be $Credential2.Identity + $Credential1.Name | Should -Be $Credential2.Name + $Credential1.Identity | Should -Be $Credential2.Identity } } Context "No overwrite" { It "does not overwrite without force" { - $results = Copy-DbaCredential -Source $server2 -Destination $server3 -Name dbatoolsci_thorcred - $results.Status | Should Be "Skipping" + $results = Copy-DbaCredential -Source $global:server2 -Destination $global:server3 -Name dbatoolsci_thorcred + $results.Status | Should -Be "Skipping" } } - # See https://github.com/dataplat/dbatools/issues/7896 and comments above in BeforeAll Context "Crypto provider cred" { - It -Skip:(-not $cryptoProvider) "ensure copied credential is using the same crypto provider" { - $results = Copy-DbaCredential -Source $server2 -Destination $server3 -Name dbatoolsci_thor_crypto - $results.Status | Should Be Successful - $results = Get-DbaCredential -SqlInstance $server3 -Name dbatoolsci_thor_crypto + It "ensure copied credential is using the same crypto provider" -Skip:(-not $global:cryptoProvider) { + $results = Copy-DbaCredential -Source $global:server2 -Destination $global:server3 -Name dbatoolsci_thor_crypto + $results.Status | Should -Be Successful + $results = Get-DbaCredential -SqlInstance $global:server3 -Name dbatoolsci_thor_crypto $results.Name | Should -Be dbatoolsci_thor_crypto - $results.ProviderName | Should -Be $cryptoProvider + $results.ProviderName | Should -Be $global:cryptoProvider } - It -Skip:(-not $cryptoProvider) "check warning message if crypto provider is not configured/enabled on destination" { - Remove-DbaCredential -SqlInstance $server3 -Credential dbatoolsci_thor_crypto -Confirm:$false - $server3.Query("ALTER CRYPTOGRAPHIC PROVIDER $cryptoProvider DISABLE") - $results = Copy-DbaCredential -Source $server2 -Destination $server3 -Name dbatoolsci_thor_crypto - $server3.Query("ALTER CRYPTOGRAPHIC PROVIDER $cryptoProvider ENABLE") - $results.Status | Should Be Failed - $results.Notes | Should -Match "The cryptographic provider $cryptoProvider needs to be configured and enabled on" + It "check warning message if crypto provider is not configured/enabled on destination" -Skip:(-not $global:cryptoProvider) { + Remove-DbaCredential -SqlInstance $global:server3 -Credential dbatoolsci_thor_crypto -Confirm:$false + $global:server3.Query("ALTER CRYPTOGRAPHIC PROVIDER $global:cryptoProvider DISABLE") + $results = Copy-DbaCredential -Source $global:server2 -Destination $global:server3 -Name dbatoolsci_thor_crypto + $global:server3.Query("ALTER CRYPTOGRAPHIC PROVIDER $global:cryptoProvider ENABLE") + $results.Status | Should -Be Failed + $results.Notes | Should -Match "The cryptographic provider $global:cryptoProvider needs to be configured and enabled on" } } -} \ No newline at end of file +} diff --git a/tests/Copy-DbaCustomError.Tests.ps1 b/tests/Copy-DbaCustomError.Tests.ps1 index ea8f41df93..a276f2d06f 100644 --- a/tests/Copy-DbaCustomError.Tests.ps1 +++ b/tests/Copy-DbaCustomError.Tests.ps1 @@ -1,45 +1,60 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') + +Describe "Copy-DbaCustomError" { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" + } -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'Source', 'SourceSqlCredential', 'Destination', 'DestinationSqlCredential', 'CustomError', 'ExcludeCustomError', 'Force', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + BeforeAll { + $command = Get-Command Copy-DbaCustomError + } + $knownParameters = @( + 'Source', + 'SourceSqlCredential', + 'Destination', + 'DestinationSqlCredential', + 'CustomError', + 'ExcludeCustomError', + 'Force', + 'EnableException', + 'WhatIf', + 'Confirm' + ) + It "Should have the correct parameters" { + $command | Should -HaveParameter $knownParameters } } -} -Describe "$commandname Integration Tests" -Tag "IntegrationTests" { - BeforeAll { - $server = Connect-DbaInstance -SqlInstance $script:instance2 -Database master - $server.Query("EXEC sp_addmessage @msgnum = 60000, @severity = 16,@msgtext = N'The item named %s already exists in %s.',@lang = 'us_english';") - $server.Query("EXEC sp_addmessage @msgnum = 60000, @severity = 16, @msgtext = N'L''élément nommé %1! existe déjà dans %2!',@lang = 'French';") - } - AfterAll { - $server = Connect-DbaInstance -SqlInstance $script:instance2 -Database master - $server.Query("EXEC sp_dropmessage @msgnum = 60000, @lang = 'all';") - $server = Connect-DbaInstance -SqlInstance $script:instance3 -Database master - $server.Query("EXEC sp_dropmessage @msgnum = 60000, @lang = 'all';") - } + Context "Integration Tests" -Tag "IntegrationTests" { + BeforeAll { + $server = Connect-DbaInstance -SqlInstance $global:instance2 -Database master + $server.Query("EXEC sp_addmessage @msgnum = 60000, @severity = 16,@msgtext = N'The item named %s already exists in %s.',@lang = 'us_english';") + $server.Query("EXEC sp_addmessage @msgnum = 60000, @severity = 16, @msgtext = N'L''élément nommé %1! existe déjà dans %2!',@lang = 'French';") + } - It "copies the sample custom errror" { - $results = Copy-DbaCustomError -Source $script:instance2 -Destination $script:instance3 -CustomError 60000 - $results.Name -eq "60000:'us_english'", "60000:'Français'" - $results.Status -eq 'Successful', 'Successful' - } + AfterAll { + $server = Connect-DbaInstance -SqlInstance $global:instance2 -Database master + $server.Query("EXEC sp_dropmessage @msgnum = 60000, @lang = 'all';") + $server = Connect-DbaInstance -SqlInstance $global:instance3 -Database master + $server.Query("EXEC sp_dropmessage @msgnum = 60000, @lang = 'all';") + } - It "doesn't overwrite existing custom errors" { - $results = Copy-DbaCustomError -Source $script:instance2 -Destination $script:instance3 -CustomError 60000 - $results.Name -eq "60000:'us_english'", "60000:'Français'" - $results.Status -eq 'Skipped', 'Skipped' - } + It "copies the sample custom error" { + $results = Copy-DbaCustomError -Source $global:instance2 -Destination $global:instance3 -CustomError 60000 + $results.Name | Should -Be @("60000:'us_english'", "60000:'Français'") + $results.Status | Should -Be @('Successful', 'Successful') + } - It "the newly copied custom error exists" { - $results = Get-DbaCustomError -SqlInstance $script:instance2 - $results.ID -contains 60000 + It "doesn't overwrite existing custom errors" { + $results = Copy-DbaCustomError -Source $global:instance2 -Destination $global:instance3 -CustomError 60000 + $results.Name | Should -Be @("60000:'us_english'", "60000:'Français'") + $results.Status | Should -Be @('Skipped', 'Skipped') + } + + It "the newly copied custom error exists" { + $results = Get-DbaCustomError -SqlInstance $global:instance3 + $results.ID | Should -Contain 60000 + } } -} \ No newline at end of file +} diff --git a/tests/Copy-DbaDataCollector.Tests.ps1 b/tests/Copy-DbaDataCollector.Tests.ps1 index 16402e6910..9b92c9af58 100644 --- a/tests/Copy-DbaDataCollector.Tests.ps1 +++ b/tests/Copy-DbaDataCollector.Tests.ps1 @@ -1,19 +1,33 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') + +Describe "Copy-DbaDataCollector Unit Tests" -Tag 'UnitTests' { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" + } -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'Source', 'SourceSqlCredential', 'Destination', 'DestinationSqlCredential', 'CollectionSet', 'ExcludeCollectionSet', 'NoServerReconfig', 'Force', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + BeforeAll { + $command = Get-Command Copy-DbaDataCollector + } + $paramsList = @( + 'Source', + 'SourceSqlCredential', + 'Destination', + 'DestinationSqlCredential', + 'CollectionSet', + 'ExcludeCollectionSet', + 'NoServerReconfig', + 'Force', + 'EnableException', + 'WhatIf', + 'Confirm' + ) + It "Should have parameter: <_>" -ForEach $paramsList { + $command | Should -HaveParameter $PSItem } } } -<# - Integration test should appear below and are custom to the command you are writing. - Read https://github.com/dataplat/dbatools/blob/development/contributing.md#tests - for more guidence. -#> \ No newline at end of file + +# Integration test should appear below and are custom to the command you are writing. +# Read https://github.com/dataplat/dbatools/blob/development/contributing.md#tests +# for more guidance. diff --git a/tests/Copy-DbaDbCertificate.Tests.ps1 b/tests/Copy-DbaDbCertificate.Tests.ps1 index 8909f2cee4..7027550124 100644 --- a/tests/Copy-DbaDbCertificate.Tests.ps1 +++ b/tests/Copy-DbaDbCertificate.Tests.ps1 @@ -1,53 +1,71 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') + +Describe "Copy-DbaDbCertificate" { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" + } -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'Source', 'SourceSqlCredential', 'Destination', 'DestinationSqlCredential', 'Database', 'ExcludeDatabase', 'Certificate', 'ExcludeCertificate', 'SharedPath', 'MasterKeyPassword', 'EncryptionPassword', 'DecryptionPassword', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 + BeforeAll { + $command = Get-Command Copy-DbaDbCertificate + } + $paramsList = @( + 'Source', + 'SourceSqlCredential', + 'Destination', + 'DestinationSqlCredential', + 'Database', + 'ExcludeDatabase', + 'Certificate', + 'ExcludeCertificate', + 'SharedPath', + 'MasterKeyPassword', + 'EncryptionPassword', + 'DecryptionPassword', + 'EnableException', + 'WhatIf', + 'Confirm' + ) + It "Should have parameter: <_>" -ForEach $paramsList { + $command | Should -HaveParameter $PSItem } } -} -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { Context "Can create a database certificate" { BeforeAll { - $passwd = $(ConvertTo-SecureString -String "GoodPass1234!" -AsPlainText -Force) - $masterkey = New-DbaDbMasterKey -SqlInstance $script:instance2 -Database master -SecurePassword $passwd -Confirm:$false -ErrorAction SilentlyContinue + $passwd = ConvertTo-SecureString -String "GoodPass1234!" -AsPlainText -Force + $masterkey = New-DbaDbMasterKey -SqlInstance $global:instance2 -Database master -SecurePassword $passwd -Confirm:$false -ErrorAction SilentlyContinue - $newdbs = New-DbaDatabase -SqlInstance $script:instance2, $script:instance3 -Name dbatoolscopycred - $null = New-DbaDbMasterKey -SqlInstance $script:instance2 -Database dbatoolscopycred -SecurePassword $passwd -Confirm:$false + $newdbs = New-DbaDatabase -SqlInstance $global:instance2, $global:instance3 -Name dbatoolscopycred + $null = New-DbaDbMasterKey -SqlInstance $global:instance2 -Database dbatoolscopycred -SecurePassword $passwd -Confirm:$false $certificateName2 = "Cert_$(Get-Random)" - $null = New-DbaDbCertificate -SqlInstance $script:instance2 -Name $certificateName2 -Database dbatoolscopycred -Confirm:$false + $null = New-DbaDbCertificate -SqlInstance $global:instance2 -Name $certificateName2 -Database dbatoolscopycred -Confirm:$false } + AfterAll { $null = $newdbs | Remove-DbaDatabase -Confirm:$false -ErrorAction SilentlyContinue if ($masterKey) { $masterkey | Remove-DbaDbMasterKey -Confirm:$false -ErrorAction SilentlyContinue } } - # doing it on docker instead. this works on linux and on a windows homelab so i dont know - It -Skip "Successfully copies a certificate" { - $passwd = $(ConvertTo-SecureString -String "GoodPass1234!" -AsPlainText -Force) + + It "Successfully copies a certificate" -Skip { + $passwd = ConvertTo-SecureString -String "GoodPass1234!" -AsPlainText -Force $paramscopydb = @{ - Source = $script:instance2 - Destination = $script:instance3 + Source = $global:instance2 + Destination = $global:instance3 EncryptionPassword = $passwd MasterKeyPassword = $passwd Database = "dbatoolscopycred" - SharedPath = $script:appveyorlabrepo + SharedPath = $global:appveyorlabrepo } $results = Copy-DbaDbCertificate @paramscopydb -Confirm:$false | Where-Object SourceDatabase -eq dbatoolscopycred | Select-Object -First 1 $results.Notes | Should -Be $null $results.Status | Should -Be "Successful" - $results.SourceDatabaseID | Should -Be (Get-DbaDatabase -SqlInstance $script:instance2 -Database dbatoolscopycred).ID - $results.DestinationDatabaseID | Should -Be (Get-DbaDatabase -SqlInstance $script:instance3 -Database dbatoolscopycred).ID + $results.SourceDatabaseID | Should -Be (Get-DbaDatabase -SqlInstance $global:instance2 -Database dbatoolscopycred).ID + $results.DestinationDatabaseID | Should -Be (Get-DbaDatabase -SqlInstance $global:instance3 -Database dbatoolscopycred).ID - Get-DbaDbCertificate -SqlInstance $script:instance3 -Database dbatoolscopycred -Certificate $certificateName2 | Should -Not -BeNullOrEmpty + Get-DbaDbCertificate -SqlInstance $global:instance3 -Database dbatoolscopycred -Certificate $certificateName2 | Should -Not -BeNullOrEmpty } } -} \ No newline at end of file +} diff --git a/tests/Copy-DbaDbMail.Tests.ps1 b/tests/Copy-DbaDbMail.Tests.ps1 index 2b282dc4f4..7107a7fdbe 100644 --- a/tests/Copy-DbaDbMail.Tests.ps1 +++ b/tests/Copy-DbaDbMail.Tests.ps1 @@ -1,106 +1,111 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') + +Describe "Copy-DbaDbMail" { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" + } -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'Source', 'Destination', 'Type', 'SourceSqlCredential', 'DestinationSqlCredential', 'Force', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + BeforeAll { + $command = Get-Command Copy-DbaDbMail + } + $parms = @( + 'Source', + 'Destination', + 'Type', + 'SourceSqlCredential', + 'DestinationSqlCredential', + 'Force', + 'EnableException', + 'WhatIf', + 'Confirm' + ) + It "Has required parameter: <_>" -ForEach $parms { + $command | Should -HaveParameter $PSItem } } -} -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { - BeforeAll { - $servers = Connect-DbaInstance -SqlInstance $script:instance2, $script:instance3 - foreach ($s in $servers) { - if ( (Get-DbaSpConfigure -SqlInstance $s -Name 'Database Mail XPs').RunningValue -ne 1 ) { - Set-DbaSpConfigure -SqlInstance $s -Name 'Database Mail XPs' -Value 1 + Context "Integration Tests" -Tag "IntegrationTests" { + BeforeAll { + $servers = Connect-DbaInstance -SqlInstance $global:instance2, $global:instance3 + foreach ($s in $servers) { + if ( (Get-DbaSpConfigure -SqlInstance $s -Name 'Database Mail XPs').RunningValue -ne 1 ) { + Set-DbaSpConfigure -SqlInstance $s -Name 'Database Mail XPs' -Value 1 + } } - } - - $accountName = "dbatoolsci_test_$(get-random)" - $account_display_name = 'dbatoolsci mail alerts' - $account_description = 'Mail account for email alerts' - $profilename = "dbatoolsci_test_$(get-random)" - $profile_description = 'Mail profile for email alerts' - $email_address = 'dbatoolssci@dbatools.io' - $mailserver_name = 'smtp.dbatools.io' - $replyto_address = 'no-reply@dbatools.io' - $mailaccountpriority = 1 + $accountName = "dbatoolsci_test_$(Get-Random)" + $account_display_name = 'dbatoolsci mail alerts' + $account_description = 'Mail account for email alerts' + $profilename = "dbatoolsci_test_$(Get-Random)" + $profile_description = 'Mail profile for email alerts' + $email_address = 'dbatoolssci@dbatools.io' + $mailserver_name = 'smtp.dbatools.io' + $replyto_address = 'no-reply@dbatools.io' + $mailaccountpriority = 1 - $splat1 = @{ - SqlInstance = $script:instance2 - Name = $accountName - Description = $account_description - EmailAddress = $email_address - DisplayName = $account_display_name - ReplyToAddress = $replyto_address - MailServer = $mailserver_name - } - $null = New-DbaDbMailAccount @splat1 -Force + $splat1 = @{ + SqlInstance = $global:instance2 + Name = $accountName + Description = $account_description + EmailAddress = $email_address + DisplayName = $account_display_name + ReplyToAddress = $replyto_address + MailServer = $mailserver_name + } + $null = New-DbaDbMailAccount @splat1 -Force - $splat2 = @{ - SqlInstance = $script:instance2 - Name = $profilename - Description = $profile_description - MailAccountName = $email_address - MailAccountPriority = $mailaccountpriority + $splat2 = @{ + SqlInstance = $global:instance2 + Name = $profilename + Description = $profile_description + MailAccountName = $email_address + MailAccountPriority = $mailaccountpriority + } + $null = New-DbaDbMailProfile @splat2 } - $null = New-DbaDbMailProfile @splat2 - } - AfterAll { - $servers = Connect-DbaInstance -SqlInstance $script:instance2, $script:instance3 - - foreach ($s in $servers) { - $mailAccountSettings = "EXEC msdb.dbo.sysmail_delete_account_sp @account_name = '$accountname';" - Invoke-DbaQuery -SqlInstance $s -Query $mailAccountSettings -Database msdb - $mailProfileSettings = "EXEC msdb.dbo.sysmail_delete_profile_sp @profile_name = '$profilename';" - Invoke-DbaQuery -SqlInstance $s -Query $mailProfileSettings -Database msdb + AfterAll { + $servers = Connect-DbaInstance -SqlInstance $global:instance2, $global:instance3 + foreach ($s in $servers) { + $mailAccountSettings = "EXEC msdb.dbo.sysmail_delete_account_sp @account_name = '$accountname';" + Invoke-DbaQuery -SqlInstance $s -Query $mailAccountSettings -Database msdb + $mailProfileSettings = "EXEC msdb.dbo.sysmail_delete_profile_sp @profile_name = '$profilename';" + Invoke-DbaQuery -SqlInstance $s -Query $mailProfileSettings -Database msdb + } } - } - - Context "Copy DbMail to $script:instance3" { - $results = Copy-DbaDbMail -Source $script:instance2 -Destination $script:instance3 - It "Should have copied database mailitems" { - $results | Should Not Be $null - } - foreach ($r in $results) { - if ($r.type -in @('Mail Configuration', 'Mail Account', 'Mail Profile')) { - It "Should have copied $($r.type) from $script:instance2" { - $r.SourceServer | Should Be "$script:instance2" - } - It "Should have copied $($r.type) to $script:instance3" { - $r.DestinationServer | Should Be "$script:instance3" - } + Context "Copy DbMail to $global:instance3" { + BeforeAll { + $results = Copy-DbaDbMail -Source $global:instance2 -Destination $global:instance3 } - } - } - Context "Copy MailServers specifically" { - $results = Copy-DbaDbMail -Source $script:instance2 -Destination $script:instance3 -Type MailServers + It "Should have copied database mailitems" { + $results | Should -Not -BeNullOrEmpty + } - It "Should have copied database mailitems" { - $results | Should Not Be $null + It "Should have copied <_.type> from $global:instance2 to $global:instance3" -ForEach ($results | Where-Object { $_.type -in @('Mail Configuration', 'Mail Account', 'Mail Profile') }) { + $_.SourceServer | Should -Be "$global:instance2" + $_.DestinationServer | Should -Be "$global:instance3" + } } - foreach ($r in $results) { - It "Should have $($r.status) $($r.type) from $script:instance2" { - $r.SourceServer | Should Be "$script:instance2" - $r.status | Should Be 'Skipped' + Context "Copy MailServers specifically" { + BeforeAll { + $results = Copy-DbaDbMail -Source $global:instance2 -Destination $global:instance3 -Type MailServers + } + + It "Should have copied database mailitems" { + $results | Should -Not -BeNullOrEmpty } - It "Should have $($r.status) $($r.type) to $script:instance3" { - $r.DestinationServer | Should Be "$script:instance3" - $r.status | Should Be 'Skipped' + + It "Should have skipped <_.type> from $global:instance2 to $global:instance3" -ForEach $results { + $_.SourceServer | Should -Be "$global:instance2" + $_.DestinationServer | Should -Be "$global:instance3" + $_.Status | Should -Be 'Skipped' } } } -} \ No newline at end of file +} diff --git a/tests/Copy-DbaDbQueryStoreOption.Tests.ps1 b/tests/Copy-DbaDbQueryStoreOption.Tests.ps1 index 3ae73a5444..7a93f694f2 100644 --- a/tests/Copy-DbaDbQueryStoreOption.Tests.ps1 +++ b/tests/Copy-DbaDbQueryStoreOption.Tests.ps1 @@ -1,24 +1,36 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') + +Describe "Copy-DbaDbQueryStoreOption" { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" + } -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'Source', 'SourceSqlCredential', 'SourceDatabase', 'Destination', 'DestinationSqlCredential', 'DestinationDatabase', 'Exclude', 'AllDatabases', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 + BeforeAll { + $command = Get-Command Copy-DbaDbQueryStoreOption + } + $knownParameters = @( + 'Source', + 'SourceSqlCredential', + 'SourceDatabase', + 'Destination', + 'DestinationSqlCredential', + 'DestinationDatabase', + 'Exclude', + 'AllDatabases', + 'EnableException', + 'WhatIf', + 'Confirm' + ) + It "Should have the correct parameters" -ForEach $knownParameters { + $command | Should -HaveParameter $PSItem } } -} -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { Context "Verifying query store options are copied" { BeforeAll { - $server2 = Connect-DbaInstance -SqlInstance $script:instance2 - } - BeforeEach { + $server2 = Connect-DbaInstance -SqlInstance $global:instance2 + $db1Name = "dbatoolsci_querystoretest1" $db1 = New-DbaDatabase -SqlInstance $server2 -Name $db1Name @@ -36,7 +48,8 @@ Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { $db4Name = "dbatoolsci_querystoretest4" $db4 = New-DbaDatabase -SqlInstance $server2 -Name $db4Name } - AfterEach { + + AfterAll { $db1, $db2, $db3, $db4 | Remove-DbaDatabase -Confirm:$false } @@ -46,7 +59,7 @@ Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { $result = Copy-DbaDbQueryStoreOption -Source $server2 -SourceDatabase $db1Name -Destination $server2 -DestinationDatabase $db2Name - $result.Status | Should -Be Successful + $result.Status | Should -Be "Successful" $result.SourceDatabase | Should -Be $db1Name $result.SourceDatabaseID | Should -Be $db1.ID $result.Name | Should -Be $db2Name @@ -83,4 +96,4 @@ Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { $db4QSOptions.DataFlushIntervalInSeconds | Should -Be $originalQSOptionValue } } -} \ No newline at end of file +} diff --git a/tests/Copy-DbaDbTableData.Tests.ps1 b/tests/Copy-DbaDbTableData.Tests.ps1 index d864cfb16f..0c8e9e3fac 100644 --- a/tests/Copy-DbaDbTableData.Tests.ps1 +++ b/tests/Copy-DbaDbTableData.Tests.ps1 @@ -1,57 +1,66 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - It "Should only contain our specific parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'AutoCreateTable', 'BatchSize', 'BulkCopyTimeout', 'CheckConstraints', 'CommandTimeout', 'Database', 'Destination', 'DestinationDatabase', 'DestinationSqlCredential', 'DestinationTable', 'EnableException', 'FireTriggers', 'InputObject', 'KeepIdentity', 'KeepNulls', 'NoTableLock', 'NotifyAfter', 'Query', 'SqlCredential', 'SqlInstance', 'Table', 'Truncate', 'View', 'UseDefaultFileGroup' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters +Describe "Copy-DbaDbTableData" { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" + } - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should -Be 0 + Context "Validate parameters" { + BeforeAll { + $command = Get-Command Copy-DbaDbTableData + } + $paramList = @( + 'SqlInstance', 'SqlCredential', 'Destination', 'DestinationSqlCredential', + 'Database', 'DestinationDatabase', 'Table', 'View', 'Query', 'AutoCreateTable', + 'BatchSize', 'NotifyAfter', 'DestinationTable', 'NoTableLock', 'CheckConstraints', + 'FireTriggers', 'KeepIdentity', 'KeepNulls', 'Truncate', 'BulkCopyTimeout', + 'CommandTimeout', 'UseDefaultFileGroup', 'InputObject', 'EnableException', + 'WhatIf', 'Confirm' + ) + It "Should have parameter: <_>" -ForEach $paramList { + $command | Should -HaveParameter $PSItem } - } -} -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { - BeforeAll { - $db = Get-DbaDatabase -SqlInstance $script:instance1 -Database tempdb - $db2 = Get-DbaDatabase -SqlInstance $script:instance2 -Database tempdb - $null = $db.Query("CREATE TABLE dbo.dbatoolsci_example (id int); - INSERT dbo.dbatoolsci_example - SELECT top 10 1 - FROM sys.objects") - $null = $db.Query("CREATE TABLE dbo.dbatoolsci_example2 (id int)") - $null = $db.Query("CREATE TABLE dbo.dbatoolsci_example3 (id int)") - $null = $db.Query("CREATE TABLE dbo.dbatoolsci_example4 (id int); - INSERT dbo.dbatoolsci_example4 - SELECT top 13 1 - FROM sys.objects") - $null = $db2.Query("CREATE TABLE dbo.dbatoolsci_example (id int)") - $null = $db2.Query("CREATE TABLE dbo.dbatoolsci_example3 (id int)") - $null = $db2.Query("CREATE TABLE dbo.dbatoolsci_example4 (id int); - INSERT dbo.dbatoolsci_example4 - SELECT top 13 2 - FROM sys.objects") } - AfterAll { - try { - $null = $db.Query("DROP TABLE dbo.dbatoolsci_example") - $null = $db.Query("DROP TABLE dbo.dbatoolsci_example2") - $null = $db.Query("DROP TABLE dbo.dbatoolsci_example3") - $null = $db.Query("DROP TABLE dbo.dbatoolsci_example4") - $null = $db2.Query("DROP TABLE dbo.dbatoolsci_example3") - $null = $db2.Query("DROP TABLE dbo.dbatoolsci_example4") - $null = $db2.Query("DROP TABLE dbo.dbatoolsci_example") - $null = $db.Query("DROP TABLE tempdb.dbo.dbatoolsci_willexist") - } catch { - $null = 1 + Context "Data movement" -ForEach @{ instance1 = $global:instance1; instance2 = $global:instance2 } { + BeforeAll { + $db = Get-DbaDatabase -SqlInstance $instance1 -Database tempdb + $db2 = Get-DbaDatabase -SqlInstance $instance2 -Database tempdb + $null = $db.Query("CREATE TABLE dbo.dbatoolsci_example (id int); + INSERT dbo.dbatoolsci_example + SELECT top 10 1 + FROM sys.objects") + $null = $db.Query("CREATE TABLE dbo.dbatoolsci_example2 (id int)") + $null = $db.Query("CREATE TABLE dbo.dbatoolsci_example3 (id int)") + $null = $db.Query("CREATE TABLE dbo.dbatoolsci_example4 (id int); + INSERT dbo.dbatoolsci_example4 + SELECT top 13 1 + FROM sys.objects") + $null = $db2.Query("CREATE TABLE dbo.dbatoolsci_example (id int)") + $null = $db2.Query("CREATE TABLE dbo.dbatoolsci_example3 (id int)") + $null = $db2.Query("CREATE TABLE dbo.dbatoolsci_example4 (id int); + INSERT dbo.dbatoolsci_example4 + SELECT top 13 2 + FROM sys.objects") } - } - Context "Data movement" { + + AfterAll { + try { + $null = $db.Query("DROP TABLE dbo.dbatoolsci_example") + $null = $db.Query("DROP TABLE dbo.dbatoolsci_example2") + $null = $db.Query("DROP TABLE dbo.dbatoolsci_example3") + $null = $db.Query("DROP TABLE dbo.dbatoolsci_example4") + $null = $db2.Query("DROP TABLE dbo.dbatoolsci_example3") + $null = $db2.Query("DROP TABLE dbo.dbatoolsci_example4") + $null = $db2.Query("DROP TABLE dbo.dbatoolsci_example") + $null = $db.Query("DROP TABLE tempdb.dbo.dbatoolsci_willexist") + } catch { + $null = 1 + } + } + It "copies the table data" { - $results = Copy-DbaDbTableData -SqlInstance $script:instance1 -Database tempdb -Table dbatoolsci_example -DestinationTable dbatoolsci_example2 + $results = Copy-DbaDbTableData -SqlInstance $instance1 -Database tempdb -Table dbatoolsci_example -DestinationTable dbatoolsci_example2 $table1count = $db.Query("select id from dbo.dbatoolsci_example") $table2count = $db.Query("select id from dbo.dbatoolsci_example2") $table1count.Count | Should -Be $table2count.Count @@ -60,39 +69,44 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { } It "copies the table data to another instance" { - $null = Copy-DbaDbTableData -SqlInstance $script:instance1 -Destination $script:instance2 -Database tempdb -Table tempdb.dbo.dbatoolsci_example -DestinationTable dbatoolsci_example3 + $null = Copy-DbaDbTableData -SqlInstance $instance1 -Destination $instance2 -Database tempdb -Table tempdb.dbo.dbatoolsci_example -DestinationTable dbatoolsci_example3 $table1count = $db.Query("select id from dbo.dbatoolsci_example") $table2count = $db2.Query("select id from dbo.dbatoolsci_example3") $table1count.Count | Should -Be $table2count.Count } It "Copy data using a query that relies on the default source database" { - $result = Copy-DbaDbTableData -SqlInstance $script:instance2 -Database tempdb -Table dbo.dbatoolsci_example4 -Query "SELECT TOP (1) Id FROM dbo.dbatoolsci_example4 ORDER BY Id DESC" -DestinationTable dbatoolsci_example3 -Truncate + $result = Copy-DbaDbTableData -SqlInstance $instance2 -Database tempdb -Table dbo.dbatoolsci_example4 -Query "SELECT TOP (1) Id FROM dbo.dbatoolsci_example4 ORDER BY Id DESC" -DestinationTable dbatoolsci_example3 -Truncate $result.RowsCopied | Should -Be 1 } It "Copy data using a query that uses a 3 part query" { - $result = Copy-DbaDbTableData -SqlInstance $script:instance2 -Database tempdb -Table dbo.dbatoolsci_example4 -Query "SELECT TOP (1) Id FROM tempdb.dbo.dbatoolsci_example4 ORDER BY Id DESC" -DestinationTable dbatoolsci_example3 -Truncate + $result = Copy-DbaDbTableData -SqlInstance $instance2 -Database tempdb -Table dbo.dbatoolsci_example4 -Query "SELECT TOP (1) Id FROM tempdb.dbo.dbatoolsci_example4 ORDER BY Id DESC" -DestinationTable dbatoolsci_example3 -Truncate $result.RowsCopied | Should -Be 1 } } - Context "Functionality checks" { + + Context "Functionality checks" -ForEach @{ instance1 = $global:instance1; instance2 = $global:instance2 } { + BeforeAll { + $db = Get-DbaDatabase -SqlInstance $instance1 -Database tempdb + $db2 = Get-DbaDatabase -SqlInstance $instance2 -Database tempdb + } + It "supports piping" { - $null = Get-DbaDbTable -SqlInstance $script:instance1 -Database tempdb -Table dbatoolsci_example | Copy-DbaDbTableData -DestinationTable dbatoolsci_example2 -Truncate + $null = Get-DbaDbTable -SqlInstance $instance1 -Database tempdb -Table dbatoolsci_example | Copy-DbaDbTableData -DestinationTable dbatoolsci_example2 -Truncate $table1count = $db.Query("select id from dbo.dbatoolsci_example") $table2count = $db.Query("select id from dbo.dbatoolsci_example2") $table1count.Count | Should -Be $table2count.Count } It "supports piping more than one table" { - $results = Get-DbaDbTable -SqlInstance $script:instance1 -Database tempdb -Table dbatoolsci_example2, dbatoolsci_example | Copy-DbaDbTableData -DestinationTable dbatoolsci_example3 + $results = Get-DbaDbTable -SqlInstance $instance1 -Database tempdb -Table dbatoolsci_example2, dbatoolsci_example | Copy-DbaDbTableData -DestinationTable dbatoolsci_example3 $results.Count | Should -Be 2 - $results.RowsCopied | Measure-Object -Sum | Select-Object -Expand Sum | Should -Be 20 + $results.RowsCopied | Measure-Object -Sum | Select-Object -ExpandProperty Sum | Should -Be 20 } It "opens and closes connections properly" { - #regression test, see #3468 - $results = Get-DbaDbTable -SqlInstance $script:instance1 -Database tempdb -Table 'dbo.dbatoolsci_example', 'dbo.dbatoolsci_example4' | Copy-DbaDbTableData -Destination $script:instance2 -DestinationDatabase tempdb -KeepIdentity -KeepNulls -BatchSize 5000 -Truncate + $results = Get-DbaDbTable -SqlInstance $instance1 -Database tempdb -Table 'dbo.dbatoolsci_example', 'dbo.dbatoolsci_example4' | Copy-DbaDbTableData -Destination $instance2 -DestinationDatabase tempdb -KeepIdentity -KeepNulls -BatchSize 5000 -Truncate $results.Count | Should -Be 2 $table1DbCount = $db.Query("select id from dbo.dbatoolsci_example") $table4DbCount = $db2.Query("select id from dbo.dbatoolsci_example4") @@ -107,25 +121,25 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { } It "Should return nothing if Source and Destination are same" { - $result = Copy-DbaDbTableData -SqlInstance $script:instance1 -Database tempdb -Table dbatoolsci_example -Truncate - $result | Should -Be $null + $result = Copy-DbaDbTableData -SqlInstance $instance1 -Database tempdb -Table dbatoolsci_example -Truncate + $result | Should -BeNullOrEmpty } - It "Should warn if the destinaton table doesn't exist" { - $result = Copy-DbaDbTableData -SqlInstance $script:instance1 -Database tempdb -Table dbatoolsci_example -DestinationTable dbatoolsci_doesntexist -WarningVariable tablewarning 3> $null - $result | Should -Be $null + It "Should warn if the destination table doesn't exist" { + $result = Copy-DbaDbTableData -SqlInstance $instance1 -Database tempdb -Table dbatoolsci_example -DestinationTable dbatoolsci_doesntexist -WarningVariable tablewarning 3> $null + $result | Should -BeNullOrEmpty $tablewarning | Should -Match Auto } It "automatically creates the table" { - $result = Copy-DbaDbTableData -SqlInstance $script:instance1 -Database tempdb -Table dbatoolsci_example -DestinationTable dbatoolsci_willexist -AutoCreateTable + $result = Copy-DbaDbTableData -SqlInstance $instance1 -Database tempdb -Table dbatoolsci_example -DestinationTable dbatoolsci_willexist -AutoCreateTable $result.DestinationTable | Should -Be 'dbatoolsci_willexist' } It "Should warn if the source database doesn't exist" { - $result = Copy-DbaDbTableData -SqlInstance $script:instance2 -Database tempdb_invalid -Table dbatoolsci_example -DestinationTable dbatoolsci_doesntexist -WarningVariable tablewarning 3> $null - $result | Should -Be $null + $result = Copy-DbaDbTableData -SqlInstance $instance2 -Database tempdb_invalid -Table dbatoolsci_example -DestinationTable dbatoolsci_doesntexist -WarningVariable tablewarning 3> $null + $result | Should -BeNullOrEmpty $tablewarning | Should -Match "cannot open database" } } -} \ No newline at end of file +} diff --git a/tests/Copy-DbaEndpoint.Tests.ps1 b/tests/Copy-DbaEndpoint.Tests.ps1 index 9cadf3e517..c4c895fd4b 100644 --- a/tests/Copy-DbaEndpoint.Tests.ps1 +++ b/tests/Copy-DbaEndpoint.Tests.ps1 @@ -1,40 +1,53 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') + +Describe "Copy-DbaEndpoint" { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" + } -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'Source', 'SourceSqlCredential', 'Destination', 'DestinationSqlCredential', 'Endpoint', 'ExcludeEndpoint', 'Force', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + BeforeAll { + $command = Get-Command Copy-DbaEndpoint + } + $paramList = @( + 'Source', + 'SourceSqlCredential', + 'Destination', + 'DestinationSqlCredential', + 'Endpoint', + 'ExcludeEndpoint', + 'Force', + 'EnableException', + 'WhatIf', + 'Confirm' + ) + It "Should have parameter: <_>" -ForEach $paramList { + $command | Should -HaveParameter $PSItem } } } -<# - Integration test should appear below and are custom to the command you are writing. - Read https://github.com/dataplat/dbatools/blob/development/contributing.md#tests - for more guidence. -#> -Describe "$commandname Integration Tests" -Tag "IntegrationTests" { +Describe "Copy-DbaEndpoint Integration Tests" -Tag "IntegrationTests" { BeforeAll { - Get-DbaEndpoint -SqlInstance $script:instance2 -Type DatabaseMirroring | Remove-DbaEndpoint -Confirm:$false - New-DbaEndpoint -SqlInstance $script:instance2 -Name dbatoolsci_MirroringEndpoint -Type DatabaseMirroring -Port 5022 -Owner sa - Get-DbaEndpoint -SqlInstance $script:instance3 -Type DatabaseMirroring | Remove-DbaEndpoint -Confirm:$false + $global:instance2 = $script:instance2 + $global:instance3 = $script:instance3 + + Get-DbaEndpoint -SqlInstance $global:instance2 -Type DatabaseMirroring | Remove-DbaEndpoint -Confirm:$false + New-DbaEndpoint -SqlInstance $global:instance2 -Name dbatoolsci_MirroringEndpoint -Type DatabaseMirroring -Port 5022 -Owner sa + Get-DbaEndpoint -SqlInstance $global:instance3 -Type DatabaseMirroring | Remove-DbaEndpoint -Confirm:$false } + AfterAll { - Get-DbaEndpoint -SqlInstance $script:instance2 -Type DatabaseMirroring | Remove-DbaEndpoint -Confirm:$false - New-DbaEndpoint -SqlInstance $script:instance2 -Name dbatoolsci_MirroringEndpoint -Type DatabaseMirroring -Port 5022 -Owner sa - Get-DbaEndpoint -SqlInstance $script:instance3 -Type DatabaseMirroring | Remove-DbaEndpoint -Confirm:$false - New-DbaEndpoint -SqlInstance $script:instance3 -Name dbatoolsci_MirroringEndpoint -Type DatabaseMirroring -Port 5023 -Owner sa + Get-DbaEndpoint -SqlInstance $global:instance2 -Type DatabaseMirroring | Remove-DbaEndpoint -Confirm:$false + New-DbaEndpoint -SqlInstance $global:instance2 -Name dbatoolsci_MirroringEndpoint -Type DatabaseMirroring -Port 5022 -Owner sa + Get-DbaEndpoint -SqlInstance $global:instance3 -Type DatabaseMirroring | Remove-DbaEndpoint -Confirm:$false + New-DbaEndpoint -SqlInstance $global:instance3 -Name dbatoolsci_MirroringEndpoint -Type DatabaseMirroring -Port 5023 -Owner sa } It "copies an endpoint" { - $results = Copy-DbaEndpoint -Source $script:instance2 -Destination $script:instance3 -Endpoint dbatoolsci_MirroringEndpoint - $results.DestinationServer | Should -Be $script:instance3 + $results = Copy-DbaEndpoint -Source $global:instance2 -Destination $global:instance3 -Endpoint dbatoolsci_MirroringEndpoint + $results.DestinationServer | Should -Be $global:instance3 $results.Status | Should -Be 'Successful' $results.Name | Should -Be 'dbatoolsci_MirroringEndpoint' } -} \ No newline at end of file +} diff --git a/tests/Copy-DbaInstanceAudit.Tests.ps1 b/tests/Copy-DbaInstanceAudit.Tests.ps1 index cde4bc9f51..328d6ee25c 100644 --- a/tests/Copy-DbaInstanceAudit.Tests.ps1 +++ b/tests/Copy-DbaInstanceAudit.Tests.ps1 @@ -1,19 +1,35 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') + +Describe "Copy-DbaInstanceAudit Unit Tests" -Tag 'UnitTests' { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" + } -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'Source', 'SourceSqlCredential', 'Destination', 'DestinationSqlCredential', 'Audit', 'ExcludeAudit', 'Path', 'Force', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + BeforeAll { + $command = Get-Command Copy-DbaInstanceAudit + } + $paramList = @( + 'Source', + 'SourceSqlCredential', + 'Destination', + 'DestinationSqlCredential', + 'Audit', + 'ExcludeAudit', + 'Path', + 'Force', + 'EnableException', + 'WhatIf', + 'Confirm' + ) + It "Should have parameter: <_>" -ForEach $paramList { + $command | Should -HaveParameter $PSItem } } } + <# Integration test should appear below and are custom to the command you are writing. Read https://github.com/dataplat/dbatools/blob/development/contributing.md#tests - for more guidence. -#> \ No newline at end of file + for more guidance. +#> diff --git a/tests/Copy-DbaInstanceAuditSpecification.Tests.ps1 b/tests/Copy-DbaInstanceAuditSpecification.Tests.ps1 index e7ec302cc3..1c167719a1 100644 --- a/tests/Copy-DbaInstanceAuditSpecification.Tests.ps1 +++ b/tests/Copy-DbaInstanceAuditSpecification.Tests.ps1 @@ -1,19 +1,38 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') + +Describe "Copy-DbaInstanceAuditSpecification Unit Tests" -Tag 'UnitTests' { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" + } -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'Source', 'SourceSqlCredential', 'Destination', 'DestinationSqlCredential', 'AuditSpecification', 'ExcludeAuditSpecification', 'Force', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + BeforeAll { + $command = Get-Command Copy-DbaInstanceAuditSpecification + } + $paramCount = 10 + $knownParameters = [object[]]@( + 'Source', + 'SourceSqlCredential', + 'Destination', + 'DestinationSqlCredential', + 'AuditSpecification', + 'ExcludeAuditSpecification', + 'Force', + 'EnableException', + 'WhatIf', + 'Confirm' + ) + It "Should contain parameters" { + $command.Parameters.Count - $defaultParamCount | Should -Be $paramCount + } + It "Should contain parameter: <_>" -ForEach $knownParameters { + $command | Should -HaveParameter $_ } } } + <# Integration test should appear below and are custom to the command you are writing. Read https://github.com/dataplat/dbatools/blob/development/contributing.md#tests - for more guidence. -#> \ No newline at end of file + for more guidance. +#> diff --git a/tests/Copy-DbaInstanceTrigger.Tests.ps1 b/tests/Copy-DbaInstanceTrigger.Tests.ps1 index 91e5839e7f..12747a4af3 100644 --- a/tests/Copy-DbaInstanceTrigger.Tests.ps1 +++ b/tests/Copy-DbaInstanceTrigger.Tests.ps1 @@ -1,45 +1,57 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') + +Describe "Copy-DbaInstanceTrigger" { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" + } -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'Source', 'SourceSqlCredential', 'Destination', 'DestinationSqlCredential', 'ServerTrigger', 'ExcludeServerTrigger', 'Force', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + BeforeAll { + $command = Get-Command Copy-DbaInstanceTrigger + } + $paramList = @( + 'Source', + 'SourceSqlCredential', + 'Destination', + 'DestinationSqlCredential', + 'ServerTrigger', + 'ExcludeServerTrigger', + 'Force', + 'EnableException', + 'WhatIf', + 'Confirm' + ) + It "Should have parameter: <_>" -ForEach $paramList { + $command | Should -HaveParameter $PSItem } } -} -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { - Context "Setup" { + Context "Command actually works" { BeforeAll { $triggername = "dbatoolsci-trigger" $sql = "CREATE TRIGGER [$triggername] -- Trigger name ON ALL SERVER FOR LOGON -- Tells you it's a logon trigger AS PRINT 'hello'" - $server = Connect-DbaInstance -SqlInstance $script:instance1 + $server = Connect-DbaInstance -SqlInstance $global:instance1 $server.Query($sql) } AfterAll { $server.Query("DROP TRIGGER [$triggername] ON ALL SERVER") try { - $server1 = Connect-DbaInstance -SqlInstance $script:instance2 + $server1 = Connect-DbaInstance -SqlInstance $global:instance2 $server1.Query("DROP TRIGGER [$triggername] ON ALL SERVER") } catch { # don't care } } - $results = Copy-DbaInstanceTrigger -Source $script:instance1 -Destination $script:instance2 -WarningAction SilentlyContinue - - It "should report success" { - $results.Status | Should Be "Successful" + It "should copy the trigger successfully" { + $results = Copy-DbaInstanceTrigger -Source $global:instance1 -Destination $global:instance2 -WarningAction SilentlyContinue + $results.Status | Should -Be "Successful" } - # same properties need to be added + + # Additional tests can be added here to check other properties of the copied trigger } -} \ No newline at end of file +} diff --git a/tests/Copy-DbaLinkedServer.Tests.ps1 b/tests/Copy-DbaLinkedServer.Tests.ps1 index e23cf4121a..7d4b32f0cc 100644 --- a/tests/Copy-DbaLinkedServer.Tests.ps1 +++ b/tests/Copy-DbaLinkedServer.Tests.ps1 @@ -1,67 +1,82 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') + +Describe "Copy-DbaLinkedServer" { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" + } -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'Source', 'SourceSqlCredential', 'Destination', 'DestinationSqlCredential', 'LinkedServer', 'ExcludeLinkedServer', 'UpgradeSqlClient', 'ExcludePassword', 'Force', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + BeforeAll { + $command = Get-Command Copy-DbaLinkedServer + } + $parms = @( + 'Source', + 'SourceSqlCredential', + 'Destination', + 'DestinationSqlCredential', + 'LinkedServer', + 'ExcludeLinkedServer', + 'UpgradeSqlClient', + 'ExcludePassword', + 'Force', + 'EnableException', + 'WhatIf', + 'Confirm' + ) + It "Has required parameter: <_>" -ForEach $parms { + $command | Should -HaveParameter $PSItem } } -} -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { - BeforeAll { - $createsql = "EXEC master.dbo.sp_addlinkedserver @server = N'dbatoolsci_localhost', @srvproduct=N'SQL Server'; - EXEC master.dbo.sp_addlinkedsrvlogin @rmtsrvname=N'dbatoolsci_localhost',@useself=N'False',@locallogin=NULL,@rmtuser=N'testuser1',@rmtpassword='supfool'; - EXEC master.dbo.sp_addlinkedserver @server = N'dbatoolsci_localhost2', @srvproduct=N'', @provider=N'SQLNCLI10'; - EXEC master.dbo.sp_addlinkedsrvlogin @rmtsrvname=N'dbatoolsci_localhost2',@useself=N'False',@locallogin=NULL,@rmtuser=N'testuser1',@rmtpassword='supfool';" + Context "Copy linked server with the same properties" -Tag "IntegrationTests" { + BeforeAll { + $createsql = "EXEC master.dbo.sp_addlinkedserver @server = N'dbatoolsci_localhost', @srvproduct=N'SQL Server'; + EXEC master.dbo.sp_addlinkedsrvlogin @rmtsrvname=N'dbatoolsci_localhost',@useself=N'False',@locallogin=NULL,@rmtuser=N'testuser1',@rmtpassword='supfool'; + EXEC master.dbo.sp_addlinkedserver @server = N'dbatoolsci_localhost2', @srvproduct=N'', @provider=N'SQLNCLI10'; + EXEC master.dbo.sp_addlinkedsrvlogin @rmtsrvname=N'dbatoolsci_localhost2',@useself=N'False',@locallogin=NULL,@rmtuser=N'testuser1',@rmtpassword='supfool';" - $server1 = Connect-DbaInstance -SqlInstance $script:instance2 - $server2 = Connect-DbaInstance -SqlInstance $script:instance3 - $server1.Query($createsql) - } - AfterAll { - $dropsql = "EXEC master.dbo.sp_dropserver @server=N'dbatoolsci_localhost', @droplogins='droplogins'; - EXEC master.dbo.sp_dropserver @server=N'dbatoolsci_localhost2', @droplogins='droplogins'" + $global:server1 = Connect-DbaInstance -SqlInstance $global:instance2 + $global:server2 = Connect-DbaInstance -SqlInstance $global:instance3 + $global:server1.Query($createsql) + } - try { - $server1.Query($dropsql) - $server2.Query($dropsql) - } catch {} - } + AfterAll { + $dropsql = "EXEC master.dbo.sp_dropserver @server=N'dbatoolsci_localhost', @droplogins='droplogins'; + EXEC master.dbo.sp_dropserver @server=N'dbatoolsci_localhost2', @droplogins='droplogins'" + + try { + $global:server1.Query($dropsql) + $global:server2.Query($dropsql) + } catch {} + } - Context "Copy linked server with the same properties" { It "copies successfully" { - $result = Copy-DbaLinkedServer -Source $script:instance2 -Destination $script:instance3 -LinkedServer dbatoolsci_localhost -WarningAction SilentlyContinue - $result | Select-Object -ExpandProperty Name -Unique | Should Be "dbatoolsci_localhost" - $result | Select-Object -ExpandProperty Status -Unique | Should Be "Successful" + $result = Copy-DbaLinkedServer -Source $global:instance2 -Destination $global:instance3 -LinkedServer dbatoolsci_localhost -WarningAction SilentlyContinue + $result | Select-Object -ExpandProperty Name -Unique | Should -Be "dbatoolsci_localhost" + $result | Select-Object -ExpandProperty Status -Unique | Should -Be "Successful" } It "retains the same properties" { - $LinkedServer1 = Get-DbaLinkedServer -SqlInstance $server1 -LinkedServer dbatoolsci_localhost -WarningAction SilentlyContinue - $LinkedServer2 = Get-DbaLinkedServer -SqlInstance $server2 -LinkedServer dbatoolsci_localhost -WarningAction SilentlyContinue + $LinkedServer1 = Get-DbaLinkedServer -SqlInstance $global:server1 -LinkedServer dbatoolsci_localhost -WarningAction SilentlyContinue + $LinkedServer2 = Get-DbaLinkedServer -SqlInstance $global:server2 -LinkedServer dbatoolsci_localhost -WarningAction SilentlyContinue # Compare its value - $LinkedServer1.Name | Should Be $LinkedServer2.Name - $LinkedServer1.LinkedServer | Should Be $LinkedServer2.LinkedServer + $LinkedServer1.Name | Should -Be $LinkedServer2.Name + $LinkedServer1.LinkedServer | Should -Be $LinkedServer2.LinkedServer } It "skips existing linked servers" { - $results = Copy-DbaLinkedServer -Source $script:instance2 -Destination $script:instance3 -LinkedServer dbatoolsci_localhost -WarningAction SilentlyContinue - $results.Status | Should Be "Skipped" + $results = Copy-DbaLinkedServer -Source $global:instance2 -Destination $global:instance3 -LinkedServer dbatoolsci_localhost -WarningAction SilentlyContinue + $results.Status | Should -Be "Skipped" } # SQLNCLI10 and SQLNCLI11 are not used on newer versions, not sure which versions, but skipping if later than 2017 - It -Skip:$($server1.VersionMajor -gt 14 -or $server2.VersionMajor -gt 14) "upgrades SQLNCLI provider based on what is registered" { - $result = Copy-DbaLinkedServer -Source $script:instance2 -Destination $script:instance3 -LinkedServer dbatoolsci_localhost2 -UpgradeSqlClient - $server1 = Connect-DbaInstance -SqlInstance $script:instance2 - $server2 = Connect-DbaInstance -SqlInstance $script:instance3 + It "upgrades SQLNCLI provider based on what is registered" -Skip:($global:server1.VersionMajor -gt 14 -or $global:server2.VersionMajor -gt 14) { + $result = Copy-DbaLinkedServer -Source $global:instance2 -Destination $global:instance3 -LinkedServer dbatoolsci_localhost2 -UpgradeSqlClient + $server1 = Connect-DbaInstance -SqlInstance $global:instance2 + $server2 = Connect-DbaInstance -SqlInstance $global:instance3 $server1.LinkedServers.Script() -match 'SQLNCLI10' | Should -Be $true $server2.LinkedServers.Script() -match 'SQLNCLI11' | Should -Be $true } } -} \ No newline at end of file +} diff --git a/tests/Copy-DbaPolicyManagement.Tests.ps1 b/tests/Copy-DbaPolicyManagement.Tests.ps1 index bfa02e4d14..3054ac6d39 100644 --- a/tests/Copy-DbaPolicyManagement.Tests.ps1 +++ b/tests/Copy-DbaPolicyManagement.Tests.ps1 @@ -1,19 +1,36 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') + +Describe "Copy-DbaPolicyManagement Unit Tests" -Tag 'UnitTests' { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" + } -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'Source', 'SourceSqlCredential', 'Destination', 'DestinationSqlCredential', 'Policy', 'ExcludePolicy', 'Condition', 'ExcludeCondition', 'Force', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + BeforeAll { + $command = Get-Command Copy-DbaPolicyManagement + } + $paramList = @( + 'Source', + 'SourceSqlCredential', + 'Destination', + 'DestinationSqlCredential', + 'Policy', + 'ExcludePolicy', + 'Condition', + 'ExcludeCondition', + 'Force', + 'EnableException', + 'WhatIf', + 'Confirm' + ) + It "Should have parameter: <_>" -ForEach $paramList { + $command | Should -HaveParameter $PSItem } } } + <# Integration test should appear below and are custom to the command you are writing. Read https://github.com/dataplat/dbatools/blob/development/contributing.md#tests - for more guidence. -#> \ No newline at end of file + for more guidance. +#> diff --git a/tests/Copy-DbaRegServer.Tests.ps1 b/tests/Copy-DbaRegServer.Tests.ps1 index e8df0c654a..47492ce5a2 100644 --- a/tests/Copy-DbaRegServer.Tests.ps1 +++ b/tests/Copy-DbaRegServer.Tests.ps1 @@ -1,22 +1,34 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') + +Describe "Copy-DbaRegServer" { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" + } -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'Source', 'SourceSqlCredential', 'Destination', 'DestinationSqlCredential', 'Group', 'SwitchServerName', 'Force', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + BeforeAll { + $command = Get-Command Copy-DbaRegServer + } + $parms = @( + 'Source', + 'SourceSqlCredential', + 'Destination', + 'DestinationSqlCredential', + 'Group', + 'SwitchServerName', + 'Force', + 'EnableException', + 'WhatIf', + 'Confirm' + ) + It "Has required parameter: <_>" -ForEach $parms { + $command | Should -HaveParameter $PSItem } } -} -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { - Context "Setup" { + Context "Integration Tests" -Tag "IntegrationTests" { BeforeAll { - $server = Connect-DbaInstance $script:instance2 + $server = Connect-DbaInstance $global:instance2 $regstore = New-Object Microsoft.SqlServer.Management.RegisteredServers.RegisteredServersStore($server.ConnectionContext.SqlConnectionObject) $dbstore = $regstore.DatabaseEngineServerGroup @@ -35,21 +47,21 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { $newserver.Description = $regserverdescription $newserver.Create() } + AfterAll { $newgroup.Drop() - $server = Connect-DbaInstance $script:instance1 + $server = Connect-DbaInstance $global:instance1 $regstore = New-Object Microsoft.SqlServer.Management.RegisteredServers.RegisteredServersStore($server.ConnectionContext.SqlConnectionObject) $dbstore = $regstore.DatabaseEngineServerGroup $groupstore = $dbstore.ServerGroups[$group] $groupstore.Drop() } - $results = Copy-DbaRegServer -Source $script:instance2 -Destination $script:instance1 -WarningAction SilentlyContinue -CMSGroup $group - It "should report success" { - $results.Status | Should Be "Successful", "Successful" + $results = Copy-DbaRegServer -Source $global:instance2 -Destination $global:instance1 -WarningAction SilentlyContinue -CMSGroup $group + $results.Status | Should -Be @("Successful", "Successful") } # Property Comparisons will come later when we have the commands } -} \ No newline at end of file +} diff --git a/tests/Copy-DbaResourceGovernor.Tests.ps1 b/tests/Copy-DbaResourceGovernor.Tests.ps1 index 3cce240275..a54251918d 100644 --- a/tests/Copy-DbaResourceGovernor.Tests.ps1 +++ b/tests/Copy-DbaResourceGovernor.Tests.ps1 @@ -1,80 +1,100 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') + +Describe "Copy-DbaResourceGovernor" { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" + } -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'Source', 'SourceSqlCredential', 'Destination', 'DestinationSqlCredential', 'ResourcePool', 'ExcludeResourcePool', 'Force', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + BeforeAll { + $command = Get-Command Copy-DbaResourceGovernor + } + $knownParameters = @( + 'Source', + 'SourceSqlCredential', + 'Destination', + 'DestinationSqlCredential', + 'ResourcePool', + 'ExcludeResourcePool', + 'Force', + 'EnableException', + 'WhatIf', + 'Confirm' + ) + It "Should have the correct parameters" { + $command | Should -HaveParameter $knownParameters } } -} -Describe "$commandname Integration Tests" -Tag "IntegrationTests" { - BeforeAll { - $sql = "CREATE RESOURCE POOL dbatoolsci_prod - WITH - ( - MAX_CPU_PERCENT = 100, - MIN_CPU_PERCENT = 50 - )" - Invoke-DbaQuery -WarningAction SilentlyContinue -SqlInstance $script:instance2 -Query $sql - $sql = "CREATE WORKLOAD GROUP dbatoolsci_prodprocessing - WITH - ( - IMPORTANCE = MEDIUM - ) USING dbatoolsci_prod" - Invoke-DbaQuery -WarningAction SilentlyContinue -SqlInstance $script:instance2 -Query $sql - $sql = "CREATE RESOURCE POOL dbatoolsci_offhoursprocessing - WITH - ( - MAX_CPU_PERCENT = 50, - MIN_CPU_PERCENT = 0 - )" - Invoke-DbaQuery -WarningAction SilentlyContinue -SqlInstance $script:instance2 -Query $sql - $sql = "CREATE WORKLOAD GROUP dbatoolsci_goffhoursprocessing - WITH - ( - IMPORTANCE = LOW - ) - USING dbatoolsci_offhoursprocessing" - Invoke-DbaQuery -WarningAction SilentlyContinue -SqlInstance $script:instance2 -Query $sql - $sql = "ALTER RESOURCE GOVERNOR RECONFIGURE" - Invoke-DbaQuery -WarningAction SilentlyContinue -SqlInstance $script:instance2 -Query $sql - $sql = "CREATE FUNCTION dbatoolsci_fnRG() - RETURNS sysname - WITH SCHEMABINDING - AS - BEGIN - RETURN N'dbatoolsci_goffhoursprocessing' - END" - Invoke-DbaQuery -WarningAction SilentlyContinue -SqlInstance $script:instance2 -Query $sql - $sql = "ALTER RESOURCE GOVERNOR with (CLASSIFIER_FUNCTION = dbo.dbatoolsci_fnRG); ALTER RESOURCE GOVERNOR RECONFIGURE;" - Invoke-DbaQuery -WarningAction SilentlyContinue -SqlInstance $script:instance2 -Query $sql - } - AfterAll { - Get-DbaProcess -SqlInstance $script:instance2, $script:instance3 -Program 'dbatools PowerShell module - dbatools.io' | Stop-DbaProcess -WarningAction SilentlyContinue - Invoke-DbaQuery -WarningAction SilentlyContinue -SqlInstance $script:instance2, $script:instance3 -Query "ALTER RESOURCE GOVERNOR WITH (CLASSIFIER_FUNCTION = NULL); ALTER RESOURCE GOVERNOR RECONFIGURE" - Invoke-DbaQuery -WarningAction SilentlyContinue -SqlInstance $script:instance2, $script:instance3 -Query "DROP FUNCTION [dbo].[dbatoolsci_fnRG];ALTER RESOURCE GOVERNOR RECONFIGURE" - Invoke-DbaQuery -WarningAction SilentlyContinue -SqlInstance $script:instance2, $script:instance3 -Query "DROP WORKLOAD GROUP [dbatoolsci_prodprocessing];ALTER RESOURCE GOVERNOR RECONFIGURE" - Invoke-DbaQuery -WarningAction SilentlyContinue -SqlInstance $script:instance2, $script:instance3 -Query "DROP WORKLOAD GROUP [dbatoolsci_goffhoursprocessing];ALTER RESOURCE GOVERNOR RECONFIGURE" - Invoke-DbaQuery -WarningAction SilentlyContinue -SqlInstance $script:instance2, $script:instance3 -Query "DROP RESOURCE POOL [dbatoolsci_offhoursprocessing];ALTER RESOURCE GOVERNOR RECONFIGURE" - Invoke-DbaQuery -WarningAction SilentlyContinue -SqlInstance $script:instance2, $script:instance3 -Query "DROP RESOURCE POOL [dbatoolsci_prod];ALTER RESOURCE GOVERNOR RECONFIGURE" - } + Context "Command works" -Tag "IntegrationTests" { + BeforeAll { + $sql = @" +CREATE RESOURCE POOL dbatoolsci_prod +WITH +( + MAX_CPU_PERCENT = 100, + MIN_CPU_PERCENT = 50 +) +CREATE WORKLOAD GROUP dbatoolsci_prodprocessing +WITH +( + IMPORTANCE = MEDIUM +) USING dbatoolsci_prod +CREATE RESOURCE POOL dbatoolsci_offhoursprocessing +WITH +( + MAX_CPU_PERCENT = 50, + MIN_CPU_PERCENT = 0 +) +CREATE WORKLOAD GROUP dbatoolsci_goffhoursprocessing +WITH +( + IMPORTANCE = LOW +) +USING dbatoolsci_offhoursprocessing +ALTER RESOURCE GOVERNOR RECONFIGURE +CREATE FUNCTION dbatoolsci_fnRG() +RETURNS sysname +WITH SCHEMABINDING +AS +BEGIN + RETURN N'dbatoolsci_goffhoursprocessing' +END +ALTER RESOURCE GOVERNOR with (CLASSIFIER_FUNCTION = dbo.dbatoolsci_fnRG) +ALTER RESOURCE GOVERNOR RECONFIGURE +"@ + Invoke-DbaQuery -WarningAction SilentlyContinue -SqlInstance $global:instance2 -Query $sql + } + + AfterAll { + $cleanup = @" +ALTER RESOURCE GOVERNOR WITH (CLASSIFIER_FUNCTION = NULL) +ALTER RESOURCE GOVERNOR RECONFIGURE +DROP FUNCTION [dbo].[dbatoolsci_fnRG] +ALTER RESOURCE GOVERNOR RECONFIGURE +DROP WORKLOAD GROUP [dbatoolsci_prodprocessing] +ALTER RESOURCE GOVERNOR RECONFIGURE +DROP WORKLOAD GROUP [dbatoolsci_goffhoursprocessing] +ALTER RESOURCE GOVERNOR RECONFIGURE +DROP RESOURCE POOL [dbatoolsci_offhoursprocessing] +ALTER RESOURCE GOVERNOR RECONFIGURE +DROP RESOURCE POOL [dbatoolsci_prod] +ALTER RESOURCE GOVERNOR RECONFIGURE +"@ + Get-DbaProcess -SqlInstance $global:instance2, $global:instance3 -Program 'dbatools PowerShell module - dbatools.io' | Stop-DbaProcess -WarningAction SilentlyContinue + Invoke-DbaQuery -WarningAction SilentlyContinue -SqlInstance $global:instance2, $global:instance3 -Query $cleanup + } - Context "Command works" { It "copies the resource governor successfully" { - $results = Copy-DbaResourceGovernor -Source $script:instance2 -Destination $script:instance3 -Force -WarningAction SilentlyContinue + $results = Copy-DbaResourceGovernor -Source $global:instance2 -Destination $global:instance3 -Force -WarningAction SilentlyContinue $results.Status | Select-Object -Unique | Should -Be 'Successful' $results.Status.Count | Should -BeGreaterThan 3 $results.Name | Should -Contain 'dbatoolsci_prod' } + It "returns the proper classifier function" { - $results = Get-DbaRgClassifierFunction -SqlInstance $script:instance3 + $results = Get-DbaRgClassifierFunction -SqlInstance $global:instance3 $results.Name | Should -Be 'dbatoolsci_fnRG' } } -} \ No newline at end of file +} diff --git a/tests/Copy-DbaSpConfigure.Tests.ps1 b/tests/Copy-DbaSpConfigure.Tests.ps1 index 0a319cef8b..2a9dd16019 100644 --- a/tests/Copy-DbaSpConfigure.Tests.ps1 +++ b/tests/Copy-DbaSpConfigure.Tests.ps1 @@ -1,55 +1,67 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') + +Describe "Copy-DbaSpConfigure" { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" + } -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'Source', 'SourceSqlCredential', 'Destination', 'DestinationSqlCredential', 'ConfigName', 'ExcludeConfigName', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + BeforeAll { + $command = Get-Command Copy-DbaSpConfigure + } + $parms = @( + 'Source', + 'SourceSqlCredential', + 'Destination', + 'DestinationSqlCredential', + 'ConfigName', + 'ExcludeConfigName', + 'EnableException', + 'WhatIf', + 'Confirm' + ) + It "Has required parameter: <_>" -ForEach $parms { + $command | Should -HaveParameter $PSItem } } -} -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { - Context "Copy config with the same properties." { + Context "Copy config with the same properties" -Tag "IntegrationTests" { BeforeAll { - $sourceconfig = (Get-DbaSpConfigure -SqlInstance $script:instance1 -ConfigName RemoteQueryTimeout).ConfiguredValue - $destconfig = (Get-DbaSpConfigure -SqlInstance $script:instance2 -ConfigName RemoteQueryTimeout).ConfiguredValue + $global:sourceconfig = (Get-DbaSpConfigure -SqlInstance $global:instance1 -ConfigName RemoteQueryTimeout).ConfiguredValue + $global:destconfig = (Get-DbaSpConfigure -SqlInstance $global:instance2 -ConfigName RemoteQueryTimeout).ConfiguredValue # Set it so they don't match - if ($sourceconfig -and $destconfig) { - $newvalue = $sourceconfig + $destconfig - $null = Set-DbaSpConfigure -SqlInstance $script:instance2 -ConfigName RemoteQueryTimeout -Value $newvalue + if ($global:sourceconfig -and $global:destconfig) { + $newvalue = $global:sourceconfig + $global:destconfig + $null = Set-DbaSpConfigure -SqlInstance $global:instance2 -ConfigName RemoteQueryTimeout -Value $newvalue } } + AfterAll { - if ($destconfig -and $destconfig -ne $sourceconfig) { - $null = Set-DbaSpConfigure -SqlInstance $script:instance2 -ConfigName RemoteQueryTimeout -Value $destconfig + if ($global:destconfig -and $global:destconfig -ne $global:sourceconfig) { + $null = Set-DbaSpConfigure -SqlInstance $global:instance2 -ConfigName RemoteQueryTimeout -Value $global:destconfig } } It "starts with different values" { - $config1 = Get-DbaSpConfigure -SqlInstance $script:instance1 -ConfigName RemoteQueryTimeout - $config2 = Get-DbaSpConfigure -SqlInstance $script:instance2 -ConfigName RemoteQueryTimeout - $config1.ConfiguredValue -ne $config2.ConfiguredValue | Should be $true + $config1 = Get-DbaSpConfigure -SqlInstance $global:instance1 -ConfigName RemoteQueryTimeout + $config2 = Get-DbaSpConfigure -SqlInstance $global:instance2 -ConfigName RemoteQueryTimeout + $config1.ConfiguredValue | Should -Not -Be $config2.ConfiguredValue } It "copied successfully" { - $results = Copy-DbaSpConfigure -Source $script:instance1 -Destination $script:instance2 -ConfigName RemoteQueryTimeout - $results.Status | Should Be "Successful" + $results = Copy-DbaSpConfigure -Source $global:instance1 -Destination $global:instance2 -ConfigName RemoteQueryTimeout + $results.Status | Should -Be "Successful" } It "retains the same properties" { - $config1 = Get-DbaSpConfigure -SqlInstance $script:instance1 -ConfigName RemoteQueryTimeout - $config2 = Get-DbaSpConfigure -SqlInstance $script:instance2 -ConfigName RemoteQueryTimeout - $config1.ConfiguredValue | Should be $config2.ConfiguredValue + $config1 = Get-DbaSpConfigure -SqlInstance $global:instance1 -ConfigName RemoteQueryTimeout + $config2 = Get-DbaSpConfigure -SqlInstance $global:instance2 -ConfigName RemoteQueryTimeout + $config1.ConfiguredValue | Should -Be $config2.ConfiguredValue } It "didn't modify the source" { - $newconfig = (Get-DbaSpConfigure -SqlInstance $script:instance1 -ConfigName RemoteQueryTimeout).ConfiguredValue - $newconfig -eq $sourceconfig | Should Be $true + $newconfig = (Get-DbaSpConfigure -SqlInstance $global:instance1 -ConfigName RemoteQueryTimeout).ConfiguredValue + $newconfig | Should -Be $global:sourceconfig } } -} \ No newline at end of file +} diff --git a/tests/Copy-DbaSsisCatalog.Tests.ps1 b/tests/Copy-DbaSsisCatalog.Tests.ps1 index 55a02b0416..4297732972 100644 --- a/tests/Copy-DbaSsisCatalog.Tests.ps1 +++ b/tests/Copy-DbaSsisCatalog.Tests.ps1 @@ -1,19 +1,37 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') + +Describe "Copy-DbaSsisCatalog Unit Tests" -Tag 'UnitTests' { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" + } -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'Source', 'Destination', 'SourceSqlCredential', 'DestinationSqlCredential', 'Project', 'Folder', 'Environment', 'CreateCatalogPassword', 'EnableSqlClr', 'Force', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + BeforeAll { + $command = Get-Command Copy-DbaSsisCatalog + } + $paramList = @( + 'Source', + 'Destination', + 'SourceSqlCredential', + 'DestinationSqlCredential', + 'Project', + 'Folder', + 'Environment', + 'CreateCatalogPassword', + 'EnableSqlClr', + 'Force', + 'EnableException', + 'WhatIf', + 'Confirm' + ) + It "Should have parameter: <_>" -ForEach $paramList { + $command | Should -HaveParameter $PSItem } } } + <# Integration test should appear below and are custom to the command you are writing. Read https://github.com/sqlcollaborative/dbatools/blob/development/contributing.md#tests - for more guidence. -#> \ No newline at end of file + for more guidance. +#> diff --git a/tests/Copy-DbaStartupProcedure.Tests.ps1 b/tests/Copy-DbaStartupProcedure.Tests.ps1 index baf79491ae..df93f0b133 100644 --- a/tests/Copy-DbaStartupProcedure.Tests.ps1 +++ b/tests/Copy-DbaStartupProcedure.Tests.ps1 @@ -1,47 +1,54 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'Source', 'SourceSqlCredential', 'Destination', 'DestinationSqlCredential', 'Procedure', 'ExcludeProcedure', 'Force', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 - } +Describe "Copy-DbaStartupProcedure" { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" } -} -<# - Integration test should appear below and are custom to the command you are writing. - Read https://github.com/dataplat/dbatools/blob/development/contributing.md#tests - for more guidence. -#> -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { - BeforeAll { - $server = Connect-DbaInstance -SqlInstance $script:instance2 - $procName = "dbatoolsci_test_startup" - $server.Query("CREATE OR ALTER PROCEDURE $procName - AS - SELECT @@SERVERNAME - GO") - $server.Query("EXEC sp_procoption @ProcName = N'$procName' - , @OptionName = 'startup' - , @OptionValue = 'on'") + Context "Validate parameters" { + BeforeAll { + $command = Get-Command Copy-DbaStartupProcedure + } + $knownParameters = @( + 'Source', + 'SourceSqlCredential', + 'Destination', + 'DestinationSqlCredential', + 'Procedure', + 'ExcludeProcedure', + 'Force', + 'EnableException', + 'WhatIf', + 'Confirm' + ) + It "Should have the correct parameters" { + $command.Parameters.Keys | Where-Object { $_ -notin [System.Management.Automation.PSCmdlet]::CommonParameters } | Should -Be $knownParameters + } } - AfterAll { - Invoke-DbaQuery -SqlInstance $script:instance2, $script:instance3 -Database "master" -Query "DROP PROCEDURE dbatoolsci_test_startup" - } + Context "Command actually works" -ForEach @{ instance2 = $global:instance2; instance3 = $global:instance3 } { + BeforeAll { + $server = Connect-DbaInstance -SqlInstance $instance2 + $procName = "dbatoolsci_test_startup" + $server.Query("CREATE OR ALTER PROCEDURE $procName + AS + SELECT @@SERVERNAME + GO") + $server.Query("EXEC sp_procoption @ProcName = N'$procName' + , @OptionName = 'startup' + , @OptionValue = 'on'") + } - Context "Command actually works" { - $results = Copy-DbaStartupProcedure -Source $script:instance2 -Destination $script:instance3 - It "Should include test procedure: $procName" { - ($results | Where-Object Name -eq $procName).Name | Should -Be $procName + AfterAll { + Invoke-DbaQuery -SqlInstance $instance2, $instance3 -Database "master" -Query "DROP PROCEDURE IF EXISTS dbatoolsci_test_startup" } - It "Should be successful" { - ($results | Where-Object Name -eq $procName).Status | Should -Be 'Successful' + + It "Should copy the startup procedure successfully" { + $results = Copy-DbaStartupProcedure -Source $instance2 -Destination $instance3 + $copiedProcedure = $results | Where-Object Name -eq $procName + + $copiedProcedure.Name | Should -Be $procName + $copiedProcedure.Status | Should -Be 'Successful' } } -} \ No newline at end of file +} diff --git a/tests/Copy-DbaSystemDbUserObject.Tests.ps1 b/tests/Copy-DbaSystemDbUserObject.Tests.ps1 index 148284ae82..7e547a2dd1 100644 --- a/tests/Copy-DbaSystemDbUserObject.Tests.ps1 +++ b/tests/Copy-DbaSystemDbUserObject.Tests.ps1 @@ -1,22 +1,35 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') + +Describe "Copy-DbaSystemDbUserObject" { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" + } -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'Source', 'SourceSqlCredential', 'Destination', 'DestinationSqlCredential', 'Force', 'Classic', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + BeforeAll { + $command = Get-Command Copy-DbaSystemDbUserObject + } + $parms = @( + 'Source', + 'SourceSqlCredential', + 'Destination', + 'DestinationSqlCredential', + 'Force', + 'Classic', + 'EnableException', + 'WhatIf', + 'Confirm' + ) + It "Has required parameter: <_>" -ForEach $parms { + $command | Should -HaveParameter $PSItem } } -} -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { - BeforeAll { - #Function Scripts roughly From https://docs.microsoft.com/en-us/sql/t-sql/statements/create-function-transact-sql - #Rule Scripts roughly from https://docs.microsoft.com/en-us/sql/t-sql/statements/create-rule-transact-sql - $Function = @" + + Context "Integration Tests" -Tag "IntegrationTests" { + BeforeAll { + #Function Scripts roughly From https://docs.microsoft.com/en-us/sql/t-sql/statements/create-function-transact-sql + #Rule Scripts roughly from https://docs.microsoft.com/en-us/sql/t-sql/statements/create-rule-transact-sql + $Function = @" CREATE FUNCTION dbo.dbatoolscs_ISOweek (@DATE datetime) RETURNS int WITH EXECUTE AS CALLER @@ -39,7 +52,7 @@ GO SET DATEFIRST 1; SELECT dbo.ISOweek(CONVERT(DATETIME,'12/26/2004',101)) AS 'ISO Week'; "@ - $TableFunction = @" + $TableFunction = @" CREATE FUNCTION dbo.dbatoolsci_TableFunction (@pid int) RETURNS TABLE AS @@ -50,35 +63,37 @@ RETURN ); GO "@ - $Rule = @" + $Rule = @" CREATE RULE dbo.dbatoolsci_range_rule AS @range>= $1000 AND @range <$20000; "@ - $null = Invoke-DbaQuery -SqlInstance $script:instance2 -Query $Function - $null = Invoke-DbaQuery -SqlInstance $script:instance2 -Query $TableFunction - $null = Invoke-DbaQuery -SqlInstance $script:instance2 -Query $Rule - } - AfterAll { - $null = Invoke-DbaQuery -SqlInstance $script:instance2 -Query "DROP FUNCTION dbo.dbatoolscs_ISOweek;" - $null = Invoke-DbaQuery -SqlInstance $script:instance2 -Query "DROP FUNCTION dbo.dbatoolsci_TableFunction;" - $null = Invoke-DbaQuery -SqlInstance $script:instance2 -Query "DROP RULE dbo.dbatoolsci_range_rule;" - } - - Context "Should Copy Objects to the same instance" { - $results = Copy-DbaSystemDbUserObject -Source $script:instance2 -Destination $script:instance2 - It "Should execute with default parameters" { - $results | Should Not Be Null + $null = Invoke-DbaQuery -SqlInstance $global:instance2 -Query $Function + $null = Invoke-DbaQuery -SqlInstance $global:instance2 -Query $TableFunction + $null = Invoke-DbaQuery -SqlInstance $global:instance2 -Query $Rule } - $results = Copy-DbaSystemDbUserObject -Source $script:instance2 -Destination $script:instance2 -Classic - It "Should execute with -Classic parameter" { - $results | Should Not Be Null + AfterAll { + $null = Invoke-DbaQuery -SqlInstance $global:instance2 -Query "DROP FUNCTION dbo.dbatoolscs_ISOweek;" + $null = Invoke-DbaQuery -SqlInstance $global:instance2 -Query "DROP FUNCTION dbo.dbatoolsci_TableFunction;" + $null = Invoke-DbaQuery -SqlInstance $global:instance2 -Query "DROP RULE dbo.dbatoolsci_range_rule;" } - $results = Copy-DbaSystemDbUserObject -Source $script:instance2 -Destination $script:instance2 -Force - It "Should execute with -Classic parameter" { - $results | Should Not Be Null + Context "Should Copy Objects to the same instance" { + It "Should execute with default parameters" { + $results = Copy-DbaSystemDbUserObject -Source $global:instance2 -Destination $global:instance2 + $results | Should -Not -BeNullOrEmpty + } + + It "Should execute with -Classic parameter" { + $results = Copy-DbaSystemDbUserObject -Source $global:instance2 -Destination $global:instance2 -Classic + $results | Should -Not -BeNullOrEmpty + } + + It "Should execute with -Force parameter" { + $results = Copy-DbaSystemDbUserObject -Source $global:instance2 -Destination $global:instance2 -Force + $results | Should -Not -BeNullOrEmpty + } } } -} \ No newline at end of file +} diff --git a/tests/Copy-DbaXESession.Tests.ps1 b/tests/Copy-DbaXESession.Tests.ps1 index ec94e654a3..75b49fe22a 100644 --- a/tests/Copy-DbaXESession.Tests.ps1 +++ b/tests/Copy-DbaXESession.Tests.ps1 @@ -1,19 +1,34 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') + +Describe "Copy-DbaXESession Unit Tests" -Tag 'UnitTests' { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" + } -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'Source', 'Destination', 'SourceSqlCredential', 'DestinationSqlCredential', 'XeSession', 'ExcludeXeSession', 'Force', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + BeforeAll { + $command = Get-Command Copy-DbaXESession + } + $paramsList = @( + 'Source', + 'Destination', + 'SourceSqlCredential', + 'DestinationSqlCredential', + 'XeSession', + 'ExcludeXeSession', + 'Force', + 'EnableException', + 'WhatIf', + 'Confirm' + ) + It "Should have parameter: <_>" -ForEach $paramsList { + $command | Should -HaveParameter $PSItem } } } + <# Integration test should appear below and are custom to the command you are writing. Read https://github.com/dataplat/dbatools/blob/development/contributing.md#tests - for more guidence. -#> \ No newline at end of file + for more guidance. +#> diff --git a/tests/Copy-DbaXESessionTemplate.Tests.ps1 b/tests/Copy-DbaXESessionTemplate.Tests.ps1 index 23d8d6a8e5..317d31e1a5 100644 --- a/tests/Copy-DbaXESessionTemplate.Tests.ps1 +++ b/tests/Copy-DbaXESessionTemplate.Tests.ps1 @@ -1,24 +1,34 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') + +Describe "Copy-DbaXESessionTemplate" -Tag 'UnitTests' { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" + } -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'Path', 'Destination', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + BeforeAll { + $command = Get-Command Copy-DbaXESessionTemplate + } + $parms = @( + 'Path', + 'Destination', + 'EnableException' + ) + It "Has required parameter: <_>" -ForEach $parms { + $command | Should -HaveParameter $PSItem } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { - Context "Get Template Index" { +Describe "Copy-DbaXESessionTemplate Integration Tests" -Tags "IntegrationTests" { + BeforeAll { $null = Copy-DbaXESessionTemplate *>1 - $source = ((Get-DbaXESessionTemplate -Path $Path | Where-Object Source -ne Microsoft).Path | Select-Object -First 1).Name + $global:source = ((Get-DbaXESessionTemplate -Path $Path | Where-Object Source -ne Microsoft).Path | Select-Object -First 1).Name + } + + Context "Get Template Index" { It "copies the files properly" { - Get-ChildItem "$home\Documents\SQL Server Management Studio\Templates\XEventTemplates" | Where-Object Name -eq $source | Should Not Be Null + Get-ChildItem "$home\Documents\SQL Server Management Studio\Templates\XEventTemplates" | Where-Object Name -eq $global:source | Should -Not -BeNull } } -} \ No newline at end of file +} diff --git a/tests/Disable-DbaAgHadr.Tests.ps1 b/tests/Disable-DbaAgHadr.Tests.ps1 index 4c7792042f..19eab7a4e0 100644 --- a/tests/Disable-DbaAgHadr.Tests.ps1 +++ b/tests/Disable-DbaAgHadr.Tests.ps1 @@ -1,28 +1,39 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') + +Describe "Disable-DbaAgHadr" { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" + } -Describe "$CommandName Unit Tests" -Tag "UnitTests" { Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'Credential', 'Force', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + BeforeAll { + $command = Get-Command Disable-DbaAgHadr + } + $knownParameters = @( + 'SqlInstance', + 'Credential', + 'Force', + 'EnableException', + 'WhatIf', + 'Confirm' + ) + It "Should have the correct parameters" -ForEach $knownParameters { + $command | Should -HaveParameter $PSItem } } -} - -# $script:instance3 is used for Availability Group tests and needs Hadr service setting enabled -Describe "$commandname Integration Tests" -Tag "IntegrationTests" { - AfterAll { - Enable-DbaAgHadr -SqlInstance $script:instance3 -Confirm:$false -Force - } + Context "Integration Tests" -Tag "IntegrationTests" { + BeforeAll { + $global:instance3 = $script:instance3 # Ensure global scope for Pester v5 + } - $results = Disable-DbaAgHadr -SqlInstance $script:instance3 -Confirm:$false -Force + AfterAll { + Enable-DbaAgHadr -SqlInstance $global:instance3 -Confirm:$false -Force + } - It "disables hadr" { - $results.IsHadrEnabled | Should -Be $false + It "disables hadr" { + $results = Disable-DbaAgHadr -SqlInstance $global:instance3 -Confirm:$false -Force + $results.IsHadrEnabled | Should -Be $false + } } -} \ No newline at end of file +} diff --git a/tests/Disable-DbaDbEncryption.Tests.ps1 b/tests/Disable-DbaDbEncryption.Tests.ps1 index 79af457ac8..6caa4a9f9a 100644 --- a/tests/Disable-DbaDbEncryption.Tests.ps1 +++ b/tests/Disable-DbaDbEncryption.Tests.ps1 @@ -1,67 +1,78 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') -Describe "$CommandName Unit Tests" -Tags "UnitTests" { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'InputObject', 'EnableException', 'NoEncryptionKeyDrop' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 - } +Describe "Disable-DbaDbEncryption" { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" } -} -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { - BeforeAll { - $PSDefaultParameterValues["*:Confirm"] = $false - $passwd = ConvertTo-SecureString "dbatools.IO" -AsPlainText -Force - $masterkey = Get-DbaDbMasterKey -SqlInstance $script:instance2 -Database master - if (-not $masterkey) { - $delmasterkey = $true - $masterkey = New-DbaServiceMasterKey -SqlInstance $script:instance2 -SecurePassword $passwd + Context "Validate parameters" { + BeforeAll { + $command = Get-Command Disable-DbaDbEncryption } - $mastercert = Get-DbaDbCertificate -SqlInstance $script:instance2 -Database master | Where-Object Name -notmatch "##" | Select-Object -First 1 - if (-not $mastercert) { - $delmastercert = $true - $mastercert = New-DbaDbCertificate -SqlInstance $script:instance2 + $knownParameters = @( + 'SqlInstance', + 'SqlCredential', + 'Database', + 'InputObject', + 'NoEncryptionKeyDrop', + 'EnableException', + 'WhatIf', + 'Confirm' + ) + It "Should have the correct parameters" -ForEach $knownParameters { + $command | Should -HaveParameter $PSItem } - - $db = New-DbaDatabase -SqlInstance $script:instance2 - $db | New-DbaDbMasterKey -SecurePassword $passwd - $db | New-DbaDbCertificate - $db | New-DbaDbEncryptionKey -Force - $db | Enable-DbaDbEncryption -EncryptorName $mastercert.Name -Force } - AfterAll { - if ($db) { - $db | Remove-DbaDatabase - } - if ($delmastercert) { - $mastercert | Remove-DbaDbCertificate + Context "Command actually works" -Tag "IntegrationTests" { + BeforeAll { + $PSDefaultParameterValues["*:Confirm"] = $false + $passwd = ConvertTo-SecureString "dbatools.IO" -AsPlainText -Force + $masterkey = Get-DbaDbMasterKey -SqlInstance $global:instance2 -Database master + if (-not $masterkey) { + $global:delmasterkey = $true + $masterkey = New-DbaServiceMasterKey -SqlInstance $global:instance2 -SecurePassword $passwd + } + $mastercert = Get-DbaDbCertificate -SqlInstance $global:instance2 -Database master | Where-Object Name -notmatch "##" | Select-Object -First 1 + if (-not $mastercert) { + $global:delmastercert = $true + $mastercert = New-DbaDbCertificate -SqlInstance $global:instance2 + } + + $global:db = New-DbaDatabase -SqlInstance $global:instance2 + $global:db | New-DbaDbMasterKey -SecurePassword $passwd + $global:db | New-DbaDbCertificate + $global:db | New-DbaDbEncryptionKey -Force + $global:db | Enable-DbaDbEncryption -EncryptorName $mastercert.Name -Force } - if ($delmasterkey) { - $masterkey | Remove-DbaDbMasterKey + + AfterAll { + if ($global:db) { + $global:db | Remove-DbaDatabase + } + if ($global:delmastercert) { + $mastercert | Remove-DbaDbCertificate + } + if ($global:delmasterkey) { + $masterkey | Remove-DbaDbMasterKey + } } - } - Context "Command actually works" { It "should disable encryption on a database with piping" { # Give it time to finish encrypting or it'll error Start-Sleep 10 - $results = $db | Disable-DbaDbEncryption -NoEncryptionKeyDrop -WarningVariable warn 3> $null - $warn | Should -Be $null + $results = $global:db | Disable-DbaDbEncryption -NoEncryptionKeyDrop -WarningVariable warn 3> $null + $warn | Should -BeNullOrEmpty $results.EncryptionEnabled | Should -Be $false } + It "should disable encryption on a database" { - $null = $db | Enable-DbaDbEncryption -EncryptorName $mastercert.Name -Force + $null = $global:db | Enable-DbaDbEncryption -EncryptorName $mastercert.Name -Force # Give it time to finish encrypting or it'll error Start-Sleep 10 - $results = Disable-DbaDbEncryption -SqlInstance $script:instance2 -Database $db.Name -WarningVariable warn 3> $null - $warn | Should -Be $null + $results = Disable-DbaDbEncryption -SqlInstance $global:instance2 -Database $global:db.Name -WarningVariable warn 3> $null + $warn | Should -BeNullOrEmpty $results.EncryptionEnabled | Should -Be $false } } -} \ No newline at end of file +} diff --git a/tests/Disable-DbaFilestream.Tests.ps1 b/tests/Disable-DbaFilestream.Tests.ps1 index 826b132f1d..81f7669b73 100644 --- a/tests/Disable-DbaFilestream.Tests.ps1 +++ b/tests/Disable-DbaFilestream.Tests.ps1 @@ -1,33 +1,46 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') + +Describe "Disable-DbaFilestream" { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" + } -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Credential', 'Force', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + BeforeAll { + $command = Get-Command Disable-DbaFilestream + } + $paramList = @( + 'SqlInstance', + 'SqlCredential', + 'Credential', + 'Force', + 'EnableException', + 'WhatIf', + 'Confirm' + ) + It "Should have parameter: <_>" -ForEach $paramList { + $command | Should -HaveParameter $PSItem } } } <# -Describe "$commandname Integration Tests" -Tag "IntegrationTests" { +Describe "Disable-DbaFilestream Integration Tests" -Tag "IntegrationTests" { BeforeAll { - $OriginalFileStream = Get-DbaFilestream -SqlInstance $script:instance1 + $global:OriginalFileStream = Get-DbaFilestream -SqlInstance $global:instance1 } AfterAll { - Set-DbaFilestream -SqlInstance $script:instance1 -FileStreamLevel $OriginalFileStream.InstanceAccessLevel -force + Set-DbaFilestream -SqlInstance $global:instance1 -FileStreamLevel $global:OriginalFileStream.InstanceAccessLevel -Force } Context "Changing FileStream Level" { - $NewLevel = ($OriginalFileStream.FileStreamStateId + 1) % 3 #Move it on one, but keep it less than 4 with modulo division - $results = Set-DbaFilestream -SqlInstance $script:instance1 -FileStreamLevel $NewLevel -Force -WarningAction silentlyContinue -ErrorVariable errvar -Erroraction silentlyContinue + BeforeAll { + $NewLevel = ($global:OriginalFileStream.FileStreamStateId + 1) % 3 #Move it on one, but keep it less than 4 with modulo division + $results = Set-DbaFilestream -SqlInstance $global:instance1 -FileStreamLevel $NewLevel -Force -WarningAction SilentlyContinue -ErrorVariable errvar -ErrorAction SilentlyContinue + } It "Should have changed the FileStream Level" { - $results.InstanceAccessLevel | Should be $NewLevel + $results.InstanceAccessLevel | Should -Be $NewLevel } } } -#> \ No newline at end of file +#> diff --git a/tests/Disable-DbaForceNetworkEncryption.Tests.ps1 b/tests/Disable-DbaForceNetworkEncryption.Tests.ps1 index 10d1162dd3..9c8750f2c0 100644 --- a/tests/Disable-DbaForceNetworkEncryption.Tests.ps1 +++ b/tests/Disable-DbaForceNetworkEncryption.Tests.ps1 @@ -1,22 +1,33 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') + +Describe "Disable-DbaForceNetworkEncryption" { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" + } -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'Credential', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + BeforeAll { + $command = Get-Command Disable-DbaForceNetworkEncryption + } + $parms = @( + 'SqlInstance', + 'Credential', + 'EnableException', + 'WhatIf', + 'Confirm' + ) + It "Has required parameter: <_>" -ForEach $parms { + $command | Should -HaveParameter $PSItem } } -} -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { - $results = Disable-DbaForceNetworkEncryption $script:instance1 -EnableException + Context "Command actually works" { + BeforeAll { + $results = Disable-DbaForceNetworkEncryption -SqlInstance $global:instance1 -EnableException + } - It "returns false" { - $results.ForceEncryption -eq $false + It "returns false" { + $results.ForceEncryption | Should -Be $false + } } -} \ No newline at end of file +} diff --git a/tests/Disable-DbaHideInstance.Tests.ps1 b/tests/Disable-DbaHideInstance.Tests.ps1 index 4eb753cc23..f587e45ab4 100644 --- a/tests/Disable-DbaHideInstance.Tests.ps1 +++ b/tests/Disable-DbaHideInstance.Tests.ps1 @@ -1,22 +1,33 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') + +Describe "Disable-DbaHideInstance" { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" + } -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'SqlInstance', 'Credential', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 + BeforeAll { + $command = Get-Command Disable-DbaHideInstance + } + $knownParameters = @( + 'SqlInstance', + 'Credential', + 'EnableException', + 'WhatIf', + 'Confirm' + ) + It "Should have the correct parameters" -ForEach $knownParameters { + $command | Should -HaveParameter $PSItem } } -} -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { - $results = Disable-DbaHideInstance $script:instance1 -EnableException + Context "Integration Tests" -Tag "IntegrationTests" { + BeforeAll { + $results = Disable-DbaHideInstance -SqlInstance $global:instance1 -EnableException + } - It "returns false" { - $results.HideInstance -eq $false + It "returns false for HideInstance property" { + $results.HideInstance | Should -BeFalse + } } -} \ No newline at end of file +} diff --git a/tests/Disable-DbaReplDistributor.Tests.ps1 b/tests/Disable-DbaReplDistributor.Tests.ps1 index 8707c37e5a..16c0aaf3d2 100644 --- a/tests/Disable-DbaReplDistributor.Tests.ps1 +++ b/tests/Disable-DbaReplDistributor.Tests.ps1 @@ -1,20 +1,29 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') +Describe "Disable-DbaReplDistributor" { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" + Add-ReplicationLibrary + } -Add-ReplicationLibrary - -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Force', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + BeforeAll { + $command = Get-Command Disable-DbaReplDistributor + } + $knownParameters = @( + 'SqlInstance', + 'SqlCredential', + 'Force', + 'EnableException', + 'WhatIf', + 'Confirm' + ) + It "Should have the required parameter: <_>" -ForEach $knownParameters { + $command | Should -HaveParameter $PSItem } } } + <# Integration tests for replication are in GitHub Actions and run from \tests\gh-actions-repl-*.ps1.ps1 -#> \ No newline at end of file +#> diff --git a/tests/Disable-DbaReplPublishing.Tests.ps1 b/tests/Disable-DbaReplPublishing.Tests.ps1 index db1d3ce2fd..0151dcf68a 100644 --- a/tests/Disable-DbaReplPublishing.Tests.ps1 +++ b/tests/Disable-DbaReplPublishing.Tests.ps1 @@ -1,20 +1,29 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') +Describe "Disable-DbaReplPublishing" { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" + Add-ReplicationLibrary + } -Add-ReplicationLibrary - -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Force', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + BeforeAll { + $command = Get-Command Disable-DbaReplPublishing + } + $knownParameters = @( + 'SqlInstance', + 'SqlCredential', + 'Force', + 'EnableException', + 'WhatIf', + 'Confirm' + ) + It "Should have the required parameter: <_>" -ForEach $knownParameters { + $command | Should -HaveParameter $PSItem } } } + <# Integration tests for replication are in GitHub Actions and run from \tests\gh-actions-repl-*.ps1.ps1 #> diff --git a/tests/Disable-DbaStartupProcedure.Tests.ps1 b/tests/Disable-DbaStartupProcedure.Tests.ps1 index 50a5c00302..081e8aafae 100644 --- a/tests/Disable-DbaStartupProcedure.Tests.ps1 +++ b/tests/Disable-DbaStartupProcedure.Tests.ps1 @@ -1,68 +1,69 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" - -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('WhatIf', 'Confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'StartupProcedure', 'InputObject', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 - } +param($ModuleName = 'dbatools') +Describe "Disable-DbaStartupProcedure" { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" } -} -Describe "$commandname Integration Test" -Tag "IntegrationTests" { - BeforeAll { - $server = Connect-DbaInstance -SqlInstance $script:instance2 - $random = Get-Random - $startupProcName = "StartUpProc$random" - $startupProc = "dbo.$startupProcName" - $dbname = 'master' - - $null = $server.Query("CREATE PROCEDURE $startupProc AS Select 1", $dbname) - $null = $server.Query("EXEC sp_procoption '$startupProc', 'startup', 'on'", $dbname) - } - AfterAll { - $null = $server.Query("DROP PROCEDURE $startupProc", $dbname) + Context "Validate parameters" { + BeforeAll { + $command = Get-Command Disable-DbaStartupProcedure + } + $knownParameters = @( + 'SqlInstance', + 'SqlCredential', + 'StartupProcedure', + 'InputObject', + 'EnableException', + 'WhatIf', + 'Confirm' + ) + It "Should have the correct parameters" -ForEach $knownParameters { + $command | Should -HaveParameter $PSItem + } } - Context "Validate returns correct output for disable" { - $result = Disable-DbaStartupProcedure -SqlInstance $script:instance2 -StartupProcedure $startupProc -Confirm:$false + Context "Validate disabling startup procedure" -Tag "IntegrationTests" { + BeforeAll { + $server = Connect-DbaInstance -SqlInstance $global:instance2 + $random = Get-Random + $startupProcName = "StartUpProc$random" + $startupProc = "dbo.$startupProcName" + $dbname = 'master' - It "returns correct results" { - $result.Schema -eq "dbo" | Should Be $true - $result.Name -eq "$startupProcName" | Should Be $true - $result.Action -eq "Disable" | Should Be $true - $result.Status | Should Be $true - $result.Note -eq "Disable succeded" | Should Be $true + $null = $server.Query("CREATE PROCEDURE $startupProc AS Select 1", $dbname) + $null = $server.Query("EXEC sp_procoption '$startupProc', 'startup', 'on'", $dbname) + } + AfterAll { + $null = $server.Query("DROP PROCEDURE $startupProc", $dbname) } - } - - Context "Validate returns correct output for already existing state" { - $result = Disable-DbaStartupProcedure -SqlInstance $script:instance2 -StartupProcedure $startupProc -Confirm:$false - It "returns correct results" { - $result.Schema -eq "dbo" | Should Be $true - $result.Name -eq "$startupProcName" | Should Be $true - $result.Action -eq "Disable" | Should Be $true - $result.Status | Should Be $false - $result.Note -eq "Action Disable already performed" | Should Be $true + It "returns correct results when disabling" { + $result = Disable-DbaStartupProcedure -SqlInstance $global:instance2 -StartupProcedure $startupProc -Confirm:$false + $result.Schema | Should -Be "dbo" + $result.Name | Should -Be $startupProcName + $result.Action | Should -Be "Disable" + $result.Status | Should -BeTrue + $result.Note | Should -Be "Disable succeded" } - } - Context "Validate returns correct results for piped input" { - $null = Enable-DbaStartupProcedure -SqlInstance $script:instance2 -StartupProcedure $startupProc -Confirm:$false - $result = Get-DbaStartupProcedure -SqlInstance $script:instance2 | Disable-DbaStartupProcedure -Confirm:$false + It "returns correct results for already existing state" { + $result = Disable-DbaStartupProcedure -SqlInstance $global:instance2 -StartupProcedure $startupProc -Confirm:$false + $result.Schema | Should -Be "dbo" + $result.Name | Should -Be $startupProcName + $result.Action | Should -Be "Disable" + $result.Status | Should -BeFalse + $result.Note | Should -Be "Action Disable already performed" + } - It "returns correct results" { - $result.Schema -eq "dbo" | Should Be $true - $result.Name -eq "$startupProcName" | Should Be $true - $result.Action -eq "Disable" | Should Be $true - $result.Status | Should Be $true - $result.Note -eq "Disable succeded" | Should Be $true + It "returns correct results for piped input" { + $null = Enable-DbaStartupProcedure -SqlInstance $global:instance2 -StartupProcedure $startupProc -Confirm:$false + $result = Get-DbaStartupProcedure -SqlInstance $global:instance2 | Disable-DbaStartupProcedure -Confirm:$false + $result.Schema | Should -Be "dbo" + $result.Name | Should -Be $startupProcName + $result.Action | Should -Be "Disable" + $result.Status | Should -BeTrue + $result.Note | Should -Be "Disable succeded" } } -} \ No newline at end of file +} diff --git a/tests/Disable-DbaTraceFlag.Tests.ps1 b/tests/Disable-DbaTraceFlag.Tests.ps1 index dad0ec2542..f5908cf789 100644 --- a/tests/Disable-DbaTraceFlag.Tests.ps1 +++ b/tests/Disable-DbaTraceFlag.Tests.ps1 @@ -1,40 +1,45 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') + +Describe "Disable-DbaTraceFlag" { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" + } -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'TraceFlag', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + BeforeAll { + $command = Get-Command Disable-DbaTraceFlag + } + $parms = @( + 'SqlInstance', + 'SqlCredential', + 'TraceFlag', + 'EnableException' + ) + It "Has required parameter: <_>" -ForEach $parms { + $command | Should -HaveParameter $PSItem } } -} -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { - Context "Verifying TraceFlag output" { + Context "Verifying TraceFlag output" -Tag "IntegrationTests" { BeforeAll { - $server = Connect-DbaInstance -SqlInstance $script:instance1 + $server = Connect-DbaInstance -SqlInstance $global:instance1 $startingtfs = Get-DbaTraceFlag -SqlInstance $server $safetraceflag = 3226 if ($startingtfs.TraceFlag -notcontains $safetraceflag) { $null = $server.Query("DBCC TRACEON($safetraceflag,-1)") } - } + AfterAll { if ($startingtfs.TraceFlag -contains $safetraceflag) { $server.Query("DBCC TRACEON($safetraceflag,-1) WITH NO_INFOMSGS") } } - $results = Disable-DbaTraceFlag -SqlInstance $server -TraceFlag $safetraceflag - - It "Return $safetraceflag as disabled" { - $results.TraceFlag -contains $safetraceflag | Should Be $true + It "Returns $safetraceflag as disabled" { + $results = Disable-DbaTraceFlag -SqlInstance $server -TraceFlag $safetraceflag + $results.TraceFlag | Should -Contain $safetraceflag } } -} \ No newline at end of file +} diff --git a/tests/Disconnect-DbaInstance.Tests.ps1 b/tests/Disconnect-DbaInstance.Tests.ps1 index d3c36415b7..8b3142b038 100644 --- a/tests/Disconnect-DbaInstance.Tests.ps1 +++ b/tests/Disconnect-DbaInstance.Tests.ps1 @@ -1,26 +1,33 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') -Describe "$CommandName Unit Tests" -Tag "UnitTests" { - Context "Validate parameters" { - [array]$params = ([Management.Automation.CommandMetaData]$ExecutionContext.SessionState.InvokeCommand.GetCommand($CommandName, 'Function')).Parameters.Keys - [object[]]$knownParameters = 'InputObject', 'EnableException' +Describe "Disconnect-DbaInstance" { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" + } - It "Should only contain our specific parameters" { - Compare-Object -ReferenceObject $knownParameters -DifferenceObject $params | Should -BeNullOrEmpty + Context "Validate parameters" { + BeforeAll { + $command = Get-Command Disconnect-DbaInstance + } + $parms = @( + 'InputObject', + 'EnableException', + 'WhatIf', + 'Confirm' + ) + It "Has required parameter: <_>" -ForEach $parms { + $command | Should -HaveParameter $PSItem } } -} -Describe "$commandname Integration Tests" -Tag "IntegrationTests" { - BeforeAll { - $null = Connect-DbaInstance -SqlInstance $script:instance1 - } - Context "disconnets a server" { + Context "Disconnects a server" { + BeforeAll { + $null = Connect-DbaInstance -SqlInstance $global:instance1 + } + It "disconnects and returns some results" { $results = Get-DbaConnectedInstance | Disconnect-DbaInstance $results | Should -Not -BeNullOrEmpty } } -} \ No newline at end of file +} diff --git a/tests/Dismount-DbaDatabase.Tests.ps1 b/tests/Dismount-DbaDatabase.Tests.ps1 index 8c17a1f281..8750acf595 100644 --- a/tests/Dismount-DbaDatabase.Tests.ps1 +++ b/tests/Dismount-DbaDatabase.Tests.ps1 @@ -1,101 +1,102 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'InputObject', 'UpdateStatistics', 'Force', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 - } +Describe "Dismount-DbaDatabase" { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" } -} - -Describe "$commandname Integration Tests" -Tag "IntegrationTests" { - - # Setting up the environment we need to test the cmdlet - BeforeAll { - # Everything in here gets executed before anything else in this context - Get-DbaProcess -SqlInstance $script:instance3 -Program 'dbatools PowerShell module - dbatools.io' | Stop-DbaProcess -WarningAction SilentlyContinue - # Setting up variables names. If you want them to persist between all of the pester blocks, they can be moved outside - $dbname = "dbatoolsci_detachattach" - # making room in the remote case a db with the same name exists - $null = Get-DbaDatabase -SqlInstance $script:instance3 -Database $dbname | Remove-DbaDatabase -Confirm:$false - - $db1 = New-DbaDatabase -SqlInstance $script:instance3 -Name $dbname - # memorizing $fileStructure for a later test - $fileStructure = New-Object System.Collections.Specialized.StringCollection - - foreach ($file in (Get-DbaDbFile -SqlInstance $script:instance3 -Database $dbname).PhysicalName) { - $null = $fileStructure.Add($file) + Context "Validate parameters" { + BeforeAll { + $command = Get-Command Dismount-DbaDatabase + } + $knownParameters = @( + 'SqlInstance', + 'SqlCredential', + 'Database', + 'InputObject', + 'UpdateStatistics', + 'Force', + 'EnableException', + 'WhatIf', + 'Confirm' + ) + It "Should have the correct parameters" -ForEach $knownParameters { + $command | Should -HaveParameter $PSItem } } - # Everything we create/touch/mess with should be reverted to a "clean" state whenever possible - AfterAll { - # this gets executed always (think "finally" in try/catch/finally) and it's the best place for final cleanups - $null = Mount-DbaDatabase -SqlInstance $script:instance3 -Database $dbname -FileStructure $script:fileStructure - $null = Get-DbaDatabase -SqlInstance $script:instance3 -Database $dbname | Remove-DbaDatabase -Confirm:$false - } + Context "Detaches a single database and tests to ensure the alias still exists" -Tag "IntegrationTests" { + BeforeAll { + Get-DbaProcess -SqlInstance $global:instance3 -Program 'dbatools PowerShell module - dbatools.io' | Stop-DbaProcess -WarningAction SilentlyContinue + $dbname = "dbatoolsci_detachattach" + $null = Get-DbaDatabase -SqlInstance $global:instance3 -Database $dbname | Remove-DbaDatabase -Confirm:$false + $db1 = New-DbaDatabase -SqlInstance $global:instance3 -Name $dbname - # Actual tests - Context "Detaches a single database and tests to ensure the alias still exists" { - $results = Dismount-DbaDatabase -SqlInstance $script:instance3 -Database $dbname -Force + $global:fileStructure = New-Object System.Collections.Specialized.StringCollection + foreach ($file in (Get-DbaDbFile -SqlInstance $global:instance3 -Database $dbname).PhysicalName) { + $null = $global:fileStructure.Add($file) + } + } - It "was successfull" { - $results.DetachResult | Should Be "Success" - $results.DatabaseID | Should -Be $db1.ID + AfterAll { + $null = Mount-DbaDatabase -SqlInstance $global:instance3 -Database $dbname -FileStructure $global:fileStructure + $null = Get-DbaDatabase -SqlInstance $global:instance3 -Database $dbname | Remove-DbaDatabase -Confirm:$false } - It "removed just one database" { - $results.Database | Should Be $dbname + It "Detaches the database successfully" { + $results = Dismount-DbaDatabase -SqlInstance $global:instance3 -Database $dbname -Force + $results.DetachResult | Should -Be "Success" + $results.DatabaseID | Should -Be $db1.ID + $results.Database | Should -Be $dbname } - It "has the correct properties" { - $ExpectedProps = 'ComputerName,InstanceName,SqlInstance,Database,DatabaseID,DetachResult'.Split(',') - ($results.PsObject.Properties.Name | Sort-Object) | Should Be ($ExpectedProps | Sort-Object) + It "Has the correct properties" { + $results = Dismount-DbaDatabase -SqlInstance $global:instance3 -Database $dbname -Force + $ExpectedProps = 'ComputerName', 'InstanceName', 'SqlInstance', 'Database', 'DatabaseID', 'DetachResult' + $results.PSObject.Properties.Name | Should -Be $ExpectedProps } } - Context "Database Detachment" { + + Context "Database Detachment" -Tag "IntegrationTests" { BeforeAll { - Get-DbaProcess -SqlInstance $script:instance3 -Program 'dbatools PowerShell module - dbatools.io' | Stop-DbaProcess -WarningAction SilentlyContinue - $server = Connect-DbaInstance -SqlInstance $script:instance3 + Get-DbaProcess -SqlInstance $global:instance3 -Program 'dbatools PowerShell module - dbatools.io' | Stop-DbaProcess -WarningAction SilentlyContinue + $server = Connect-DbaInstance -SqlInstance $global:instance3 $db1 = "dbatoolsci_dbsetstate_detached" $server.Query("CREATE DATABASE $db1") - Get-DbaProcess -SqlInstance $script:instance3 -Program 'dbatools PowerShell module - dbatools.io' | Stop-DbaProcess -WarningAction SilentlyContinue - $server = Connect-DbaInstance -SqlInstance $script:instance3 + Get-DbaProcess -SqlInstance $global:instance3 -Program 'dbatools PowerShell module - dbatools.io' | Stop-DbaProcess -WarningAction SilentlyContinue + $server = Connect-DbaInstance -SqlInstance $global:instance3 $db2 = "dbatoolsci_dbsetstate_detached_withSnap" $server.Query("CREATE DATABASE $db2") - $null = New-DbaDbSnapshot -SqlInstance $script:instance3 -Database $db2 - $fileStructure = New-Object System.Collections.Specialized.StringCollection - foreach ($file in (Get-DbaDbFile -SqlInstance $script:instance3 -Database $db1).PhysicalName) { - $null = $fileStructure.Add($file) + $null = New-DbaDbSnapshot -SqlInstance $global:instance3 -Database $db2 + $global:fileStructure = New-Object System.Collections.Specialized.StringCollection + foreach ($file in (Get-DbaDbFile -SqlInstance $global:instance3 -Database $db1).PhysicalName) { + $null = $global:fileStructure.Add($file) } - Stop-DbaProcess -SqlInstance $script:instance3 -Database $db1 + Stop-DbaProcess -SqlInstance $global:instance3 -Database $db1 } + AfterAll { - $null = Remove-DbaDbSnapshot -SqlInstance $script:instance3 -Database $db2 -Force - $null = Mount-DbaDatabase -SqlInstance $script:instance3 -Database $db1 -FileStructure $fileStructure - $null = Get-DbaDatabase -SqlInstance $script:instance3 -Database $db1, $db2 | Remove-DbaDatabase -Confirm:$false + $null = Remove-DbaDbSnapshot -SqlInstance $global:instance3 -Database $db2 -Force + $null = Mount-DbaDatabase -SqlInstance $global:instance3 -Database $db1 -FileStructure $global:fileStructure + $null = Get-DbaDatabase -SqlInstance $global:instance3 -Database $db1, $db2 | Remove-DbaDatabase -Confirm:$false } It "Skips detachment if database is snapshotted" { - $result = Dismount-DbaDatabase -SqlInstance $script:instance3 -Database $db2 -Force -WarningAction SilentlyContinue -WarningVariable warn 3> $null - $result | Should Be $null - $warn -match "snapshot" | Should Be $true - $result = Get-DbaDatabase -SqlInstance $script:instance3 -Database $db2 - $result | Should Not Be $null + $result = Dismount-DbaDatabase -SqlInstance $global:instance3 -Database $db2 -Force -WarningAction SilentlyContinue -WarningVariable warn + $result | Should -BeNullOrEmpty + $warn | Should -Match "snapshot" + $result = Get-DbaDatabase -SqlInstance $global:instance3 -Database $db2 + $result | Should -Not -BeNullOrEmpty } - $null = Stop-DbaProcess -SqlInstance $script:instance3 -Database $db1 - $result = Dismount-DbaDatabase -SqlInstance $script:instance3 -Database $db1 + It "Detaches the database correctly" { - $result = Get-DbaDatabase -SqlInstance $script:instance3 -Database $db1 - $result | Should Be $null + $null = Stop-DbaProcess -SqlInstance $global:instance3 -Database $db1 + $null = Dismount-DbaDatabase -SqlInstance $global:instance3 -Database $db1 + $result = Get-DbaDatabase -SqlInstance $global:instance3 -Database $db1 + $result | Should -BeNullOrEmpty } } } -#$script:instance2 - to make it show up in appveyor, long story \ No newline at end of file + +#$global:instance2 for appveyor diff --git a/tests/Enable-DbaAgHadr.Tests.ps1 b/tests/Enable-DbaAgHadr.Tests.ps1 index aa6e266d56..10a1eccb19 100644 --- a/tests/Enable-DbaAgHadr.Tests.ps1 +++ b/tests/Enable-DbaAgHadr.Tests.ps1 @@ -1,26 +1,36 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') -Describe "$CommandName Unit Tests" -Tag "UnitTests" { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'Credential', 'Force', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 - } +Describe "Enable-DbaAgHadr" { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" } -} -Describe "$commandname Integration Tests" -Tag "IntegrationTests" { - BeforeAll { - Disable-DbaAgHadr -SqlInstance $script:instance3 -Confirm:$false -Force + Context "Validate parameters" { + BeforeAll { + $command = Get-Command Enable-DbaAgHadr + } + $parms = @( + 'SqlInstance', + 'Credential', + 'Force', + 'EnableException', + 'WhatIf', + 'Confirm' + ) + It "Has required parameter: <_>" -ForEach $parms { + $command | Should -HaveParameter $PSItem + } } - $results = Enable-DbaAgHadr -SqlInstance $script:instance3 -Confirm:$false -Force + Context "Command Execution" { + BeforeAll { + $global:instance3 = $script:instance3 # Maintaining the original variable for compatibility + Disable-DbaAgHadr -SqlInstance $global:instance3 -Confirm:$false -Force + } - It "enables hadr" { - $results.IsHadrEnabled | Should -Be $true + It "enables hadr" { + $results = Enable-DbaAgHadr -SqlInstance $global:instance3 -Confirm:$false -Force + $results.IsHadrEnabled | Should -Be $true + } } -} \ No newline at end of file +} diff --git a/tests/Enable-DbaDbEncryption.Tests.ps1 b/tests/Enable-DbaDbEncryption.Tests.ps1 index 15a7749ce2..3c9bf8a585 100644 --- a/tests/Enable-DbaDbEncryption.Tests.ps1 +++ b/tests/Enable-DbaDbEncryption.Tests.ps1 @@ -1,61 +1,72 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') -Describe "$CommandName Unit Tests" -Tags "UnitTests" { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'InputObject', 'EnableException', 'Force', 'EncryptorName' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 - } +Describe "Enable-DbaDbEncryption" { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" } -} - -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { - BeforeAll { - $PSDefaultParameterValues["*:Confirm"] = $false - $passwd = ConvertTo-SecureString "dbatools.IO" -AsPlainText -Force - $masterkey = Get-DbaDbMasterKey -SqlInstance $script:instance2 -Database master - if (-not $masterkey) { - $delmasterkey = $true - $masterkey = New-DbaServiceMasterKey -SqlInstance $script:instance2 -SecurePassword $passwd + Context "Validate parameters" { + BeforeAll { + $command = Get-Command Enable-DbaDbEncryption } - $mastercert = Get-DbaDbCertificate -SqlInstance $script:instance2 -Database master | Where-Object Name -notmatch "##" | Select-Object -First 1 - if (-not $mastercert) { - $delmastercert = $true - $mastercert = New-DbaDbCertificate -SqlInstance $script:instance2 + $knownParameters = @( + 'SqlInstance', + 'SqlCredential', + 'Database', + 'EncryptorName', + 'InputObject', + 'Force', + 'EnableException', + 'WhatIf', + 'Confirm' + ) + It "Should have the correct parameters" -ForEach $knownParameters { + $command | Should -HaveParameter $PSItem } - - $db = New-DbaDatabase -SqlInstance $script:instance2 - $db | New-DbaDbMasterKey -SecurePassword $passwd - $db | New-DbaDbCertificate - $db | New-DbaDbEncryptionKey -Force } - AfterAll { - if ($db) { - $db | Remove-DbaDatabase - } - if ($delmastercert) { - $mastercert | Remove-DbaDbCertificate + Context "Command actually works" -Tag "IntegrationTests" { + BeforeAll { + $global:PSDefaultParameterValues["*:Confirm"] = $false + $passwd = ConvertTo-SecureString "dbatools.IO" -AsPlainText -Force + $masterkey = Get-DbaDbMasterKey -SqlInstance $global:instance2 -Database master + if (-not $masterkey) { + $global:delmasterkey = $true + $masterkey = New-DbaServiceMasterKey -SqlInstance $global:instance2 -SecurePassword $passwd + } + $mastercert = Get-DbaDbCertificate -SqlInstance $global:instance2 -Database master | Where-Object Name -notmatch "##" | Select-Object -First 1 + if (-not $mastercert) { + $global:delmastercert = $true + $mastercert = New-DbaDbCertificate -SqlInstance $global:instance2 + } + + $global:db = New-DbaDatabase -SqlInstance $global:instance2 + $global:db | New-DbaDbMasterKey -SecurePassword $passwd + $global:db | New-DbaDbCertificate + $global:db | New-DbaDbEncryptionKey -Force } - if ($delmasterkey) { - $masterkey | Remove-DbaDbMasterKey + + AfterAll { + if ($global:db) { + $global:db | Remove-DbaDatabase + } + if ($global:delmastercert) { + $mastercert | Remove-DbaDbCertificate + } + if ($global:delmasterkey) { + $masterkey | Remove-DbaDbMasterKey + } } - } - Context "Command actually works" { It "should enable encryption on a database with piping" { - $results = $db | Enable-DbaDbEncryption -EncryptorName $mastercert.Name -Force + $results = $global:db | Enable-DbaDbEncryption -EncryptorName $mastercert.Name -Force $results.EncryptionEnabled | Should -Be $true } + It "should enable encryption on a database" { - $null = Disable-DbaDbEncryption -SqlInstance $script:instance2 -Database $db.Name - $results = Enable-DbaDbEncryption -SqlInstance $script:instance2 -EncryptorName $mastercert.Name -Database $db.Name -Force + $null = Disable-DbaDbEncryption -SqlInstance $global:instance2 -Database $global:db.Name + $results = Enable-DbaDbEncryption -SqlInstance $global:instance2 -EncryptorName $mastercert.Name -Database $global:db.Name -Force $results.EncryptionEnabled | Should -Be $true } } -} \ No newline at end of file +} diff --git a/tests/Enable-DbaFilestream.Tests.ps1 b/tests/Enable-DbaFilestream.Tests.ps1 index 4675b00944..6bb280db03 100644 --- a/tests/Enable-DbaFilestream.Tests.ps1 +++ b/tests/Enable-DbaFilestream.Tests.ps1 @@ -1,37 +1,46 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') + +Describe "Enable-DbaFilestream" { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" + } -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Credential', 'FileStreamLevel', 'ShareName', 'Force', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + BeforeAll { + $command = Get-Command Enable-DbaFilestream + } + $parms = @( + 'SqlInstance', + 'SqlCredential', + 'Credential', + 'FileStreamLevel', + 'ShareName', + 'Force', + 'EnableException', + 'WhatIf', + 'Confirm' + ) + It "Has required parameter: <_>" -ForEach $parms { + $command | Should -HaveParameter $PSItem } } -} -<# -Describe "$commandname Integration Tests" -Tag "IntegrationTests" { - BeforeAll { - $OriginalFileStream = Get-DbaFilestream -SqlInstance $script:instance1 - } - AfterAll { - if ($OriginalFileStream.InstanceAccessLevel -eq 0) { - Disable-DbaFilestream -SqlInstance $script:instance1 -Confirm:$false - } else { - Enable-DbaFilestream -SqlInstance $script:instance1 -FileStreamLevel $OriginalFileStream.InstanceAccessLevel -Confirm:$false + Context "Changing FileStream Level" -Tag "IntegrationTests" { + BeforeAll { + $global:OriginalFileStream = Get-DbaFilestream -SqlInstance $global:instance1 + } + AfterAll { + if ($global:OriginalFileStream.InstanceAccessLevel -eq 0) { + Disable-DbaFilestream -SqlInstance $global:instance1 -Confirm:$false + } else { + Enable-DbaFilestream -SqlInstance $global:instance1 -FileStreamLevel $global:OriginalFileStream.InstanceAccessLevel -Confirm:$false + } } - } - Context "Changing FileStream Level" { - $NewLevel = ($OriginalFileStream.FileStreamStateId + 1) % 3 #Move it on one, but keep it less than 4 with modulo division - $results = Enable-DbaFilestream -SqlInstance $script:instance1 -FileStreamLevel $NewLevel -Confirm:$false - It "Should have changed the FileStream Level" { - $results.InstanceAccessLevel | Should be $NewLevel + It "Should change the FileStream Level" { + $NewLevel = ($global:OriginalFileStream.FileStreamStateId + 1) % 3 #Move it on one, but keep it less than 4 with modulo division + $results = Enable-DbaFilestream -SqlInstance $global:instance1 -FileStreamLevel $NewLevel -Confirm:$false + $results.InstanceAccessLevel | Should -Be $NewLevel } } } -#> \ No newline at end of file diff --git a/tests/Enable-DbaForceNetworkEncryption.Tests.ps1 b/tests/Enable-DbaForceNetworkEncryption.Tests.ps1 index 7e0125746c..d65c20a175 100644 --- a/tests/Enable-DbaForceNetworkEncryption.Tests.ps1 +++ b/tests/Enable-DbaForceNetworkEncryption.Tests.ps1 @@ -1,22 +1,33 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') + +Describe "Enable-DbaForceNetworkEncryption" { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" + } -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'Credential', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + BeforeAll { + $command = Get-Command Enable-DbaForceNetworkEncryption + } + $parms = @( + 'SqlInstance', + 'Credential', + 'EnableException', + 'WhatIf', + 'Confirm' + ) + It "Has required parameter: <_>" -ForEach $parms { + $command | Should -HaveParameter $PSItem } } -} -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { - $results = Enable-DbaForceNetworkEncryption $script:instance1 -EnableException + Context "Command Execution" { + BeforeAll { + $results = Enable-DbaForceNetworkEncryption -SqlInstance $global:instance1 -EnableException + } - It "returns true" { - $results.ForceEncryption -eq $true + It "returns true" { + $results.ForceEncryption | Should -BeTrue + } } -} \ No newline at end of file +} diff --git a/tests/Enable-DbaHideInstance.Tests.ps1 b/tests/Enable-DbaHideInstance.Tests.ps1 index 00f0787e22..eaa48ddda8 100644 --- a/tests/Enable-DbaHideInstance.Tests.ps1 +++ b/tests/Enable-DbaHideInstance.Tests.ps1 @@ -1,26 +1,38 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') + +Describe "Enable-DbaHideInstance" { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" + } -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'SqlInstance', 'Credential', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 + BeforeAll { + $command = Get-Command Enable-DbaHideInstance + } + $parms = @( + 'SqlInstance', + 'Credential', + 'EnableException', + 'WhatIf', + 'Confirm' + ) + It "Has required parameter: <_>" -ForEach $parms { + $command | Should -HaveParameter $PSItem } } -} -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { - AfterAll { - $null = Disable-DbaHideInstance $script:instance1 - } + Context "Integration Tests" -Tag "IntegrationTests" { + BeforeAll { + $global:instance1 = $script:instance1 + } - $results = Enable-DbaHideInstance $script:instance1 -EnableException + AfterAll { + $null = Disable-DbaHideInstance -SqlInstance $global:instance1 + } - It "returns true" { - $results.HideInstance -eq $true + It "returns true" { + $results = Enable-DbaHideInstance -SqlInstance $global:instance1 -EnableException + $results.HideInstance | Should -BeTrue + } } -} \ No newline at end of file +} diff --git a/tests/Enable-DbaReplDistributor.Tests.ps1 b/tests/Enable-DbaReplDistributor.Tests.ps1 index c1f08019a0..bf852a91d5 100644 --- a/tests/Enable-DbaReplDistributor.Tests.ps1 +++ b/tests/Enable-DbaReplDistributor.Tests.ps1 @@ -1,20 +1,29 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') +Describe "Enable-DbaReplDistributor" { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" + Add-ReplicationLibrary + } -Add-ReplicationLibrary - -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'DistributionDatabase', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + BeforeAll { + $command = Get-Command Enable-DbaReplDistributor + } + $knownParameters = @( + 'SqlInstance', + 'SqlCredential', + 'DistributionDatabase', + 'EnableException', + 'WhatIf', + 'Confirm' + ) + It "Should have the correct parameters" -ForEach $knownParameters { + $command | Should -HaveParameter $PSItem } } } + <# 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/Enable-DbaReplPublishing.Tests.ps1 b/tests/Enable-DbaReplPublishing.Tests.ps1 index 08143c6619..833908910d 100644 --- a/tests/Enable-DbaReplPublishing.Tests.ps1 +++ b/tests/Enable-DbaReplPublishing.Tests.ps1 @@ -1,20 +1,30 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') +Describe "Enable-DbaReplPublishing" { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" + Add-ReplicationLibrary + } -Add-ReplicationLibrary - -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'SnapshotShare', 'PublisherSqlLogin', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + BeforeAll { + $command = Get-Command Enable-DbaReplPublishing + } + $parms = @( + 'SqlInstance', + 'SqlCredential', + 'SnapshotShare', + 'PublisherSqlLogin', + 'EnableException', + 'WhatIf', + 'Confirm' + ) + It "Has required parameter: <_>" -ForEach $parms { + $command | Should -HaveParameter $PSItem } } } + <# 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/Enable-DbaStartupProcedure.Tests.ps1 b/tests/Enable-DbaStartupProcedure.Tests.ps1 index 40bafadd4f..5689e0f5e3 100644 --- a/tests/Enable-DbaStartupProcedure.Tests.ps1 +++ b/tests/Enable-DbaStartupProcedure.Tests.ps1 @@ -1,69 +1,72 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') + +Describe "Enable-DbaStartupProcedure" { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" + } -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('WhatIf', 'Confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'StartupProcedure', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + BeforeAll { + $command = Get-Command Enable-DbaStartupProcedure + } + $parms = @( + 'SqlInstance', + 'SqlCredential', + 'StartupProcedure', + 'EnableException', + 'WhatIf', + 'Confirm' + ) + It "Has required parameter: <_>" -ForEach $parms { + $command | Should -HaveParameter $PSItem } - } -} -Describe "$commandname Integration Test" -Tag "IntegrationTests" { - BeforeAll { - $server = Connect-DbaInstance -SqlInstance $script:instance2 - $random = Get-Random - $startupProcName = "StartUpProc$random" - $startupProc = "dbo.$startupProcName" - $dbname = 'master' - $null = $server.Query("CREATE PROCEDURE $startupProc AS Select 1", $dbname) - } - AfterAll { - $null = $server.Query("DROP PROCEDURE $startupProc", $dbname) - } + Context "Integration Tests" -Tag "IntegrationTests" { + BeforeAll { + $server = Connect-DbaInstance -SqlInstance $global:instance2 + $random = Get-Random + $startupProcName = "StartUpProc$random" + $startupProc = "dbo.$startupProcName" + $dbname = 'master' - Context "Validate returns correct output for enable" { - $result = Enable-DbaStartupProcedure -SqlInstance $script:instance2 -StartupProcedure $startupProc -Confirm:$false + $null = $server.Query("CREATE PROCEDURE $startupProc AS Select 1", $dbname) + } - It "returns correct results" { - $result.Schema -eq "dbo" | Should Be $true - $result.Name -eq "$startupProcName" | Should Be $true - $result.Action -eq "Enable" | Should Be $true - $result.Status | Should Be $true - $result.Note -eq "Enable succeded" | Should Be $true + AfterAll { + $null = $server.Query("DROP PROCEDURE $startupProc", $dbname) } - } - Context "Validate returns correct output for already existing state" { - $result = Enable-DbaStartupProcedure -SqlInstance $script:instance2 -StartupProcedure $startupProc -Confirm:$false + It "Returns correct output for enable" { + $result = Enable-DbaStartupProcedure -SqlInstance $global:instance2 -StartupProcedure $startupProc -Confirm:$false - It "returns correct results" { - $result.Schema -eq "dbo" | Should Be $true - $result.Name -eq "$startupProcName" | Should Be $true - $result.Action -eq "Enable" | Should Be $true - $result.Status | Should Be $false - $result.Note -eq "Action Enable already performed" | Should Be $true + $result.Schema | Should -Be "dbo" + $result.Name | Should -Be $startupProcName + $result.Action | Should -Be "Enable" + $result.Status | Should -BeTrue + $result.Note | Should -Be "Enable succeded" } - } - Context "Validate returns correct output for missing procedures" { - $result = Enable-DbaStartupProcedure -SqlInstance $script:instance2 -StartupProcedure "Unknown.NotHere" -Confirm:$false + It "Returns correct output for already existing state" { + $result = Enable-DbaStartupProcedure -SqlInstance $global:instance2 -StartupProcedure $startupProc -Confirm:$false - It "returns correct results" { - $null -eq $result | Should Be $true + $result.Schema | Should -Be "dbo" + $result.Name | Should -Be $startupProcName + $result.Action | Should -Be "Enable" + $result.Status | Should -BeFalse + $result.Note | Should -Be "Action Enable already performed" } - } - Context "Validate returns correct output for incorrectly formed procedures" { - $result = Enable-DbaStartupProcedure -SqlInstance $script:instance2 -StartupProcedure "Four.Part.Schema.Name" -Confirm:$false + It "Returns correct output for missing procedures" { + $result = Enable-DbaStartupProcedure -SqlInstance $global:instance2 -StartupProcedure "Unknown.NotHere" -Confirm:$false - It "returns correct results" { - $null -eq $result | Should Be $true + $result | Should -BeNullOrEmpty + } + + It "Returns correct output for incorrectly formed procedures" { + $result = Enable-DbaStartupProcedure -SqlInstance $global:instance2 -StartupProcedure "Four.Part.Schema.Name" -Confirm:$false + + $result | Should -BeNullOrEmpty } } -} \ No newline at end of file +} diff --git a/tests/Enable-DbaTraceFlag.Tests.ps1 b/tests/Enable-DbaTraceFlag.Tests.ps1 index 58950b47b9..e3920dfd81 100644 --- a/tests/Enable-DbaTraceFlag.Tests.ps1 +++ b/tests/Enable-DbaTraceFlag.Tests.ps1 @@ -1,39 +1,44 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -. "$PSScriptRoot\constants.ps1" +param($ModuleName = 'dbatools') + +Describe "Enable-DbaTraceFlag" { + BeforeDiscovery { + . "$PSScriptRoot\constants.ps1" + } -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'TraceFlag', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + BeforeAll { + $command = Get-Command Enable-DbaTraceFlag + } + $parms = @( + 'SqlInstance', + 'SqlCredential', + 'TraceFlag', + 'EnableException' + ) + It "Has required parameter: <_>" -ForEach $parms { + $command | Should -HaveParameter $PSItem } } -} -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { - Context "Verifying TraceFlag output" { + Context "Verifying TraceFlag output" -Tag "IntegrationTests" { BeforeAll { - $server = Connect-DbaInstance -SqlInstance $script:instance2 - $startingtfs = Get-DbaTraceFlag -SqlInstance $script:instance2 - $safetraceflag = 3226 + $global:server = Connect-DbaInstance -SqlInstance $global:instance2 + $global:startingtfs = Get-DbaTraceFlag -SqlInstance $global:instance2 + $global:safetraceflag = 3226 - if ($startingtfs.TraceFlag -contains $safetraceflag) { - $server.Query("DBCC TRACEOFF($safetraceflag,-1)") + if ($global:startingtfs.TraceFlag -contains $global:safetraceflag) { + $global:server.Query("DBCC TRACEOFF($global:safetraceflag,-1)") } } AfterAll { - if ($startingtfs.TraceFlag -notcontains $safetraceflag) { - $server.Query("DBCC TRACEOFF($safetraceflag,-1)") + if ($global:startingtfs.TraceFlag -notcontains $global:safetraceflag) { + $global:server.Query("DBCC TRACEOFF($global:safetraceflag,-1)") } } - $results = Enable-DbaTraceFlag -SqlInstance $server -TraceFlag $safetraceflag - - It "Return $safetraceflag as enabled" { - $results.TraceFlag -contains $safetraceflag | Should Be $true + It "Returns $global:safetraceflag as enabled" { + $results = Enable-DbaTraceFlag -SqlInstance $global:server -TraceFlag $global:safetraceflag + $results.TraceFlag | Should -Contain $global:safetraceflag } } -} \ No newline at end of file +}