diff --git a/tests/Get-DbaDbMail.Tests.ps1 b/tests/Get-DbaDbMail.Tests.ps1 index dfc15fd8c86..df64e390c44 100644 --- a/tests/Get-DbaDbMail.Tests.ps1 +++ b/tests/Get-DbaDbMail.Tests.ps1 @@ -1,47 +1,69 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaDbMail", # Static command name for dbatools + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # Set variables. They are available in all the It blocks. $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 $mailSettings = @{ - AccountRetryAttempts = '1' - AccountRetryDelay = '60' - DatabaseMailExeMinimumLifeTime = '600' - DefaultAttachmentEncoding = 'MIME' - LoggingLevel = '2' - MaxFileSize = '1000' - ProhibitedExtensions = 'exe,dll,vbs,js' + AccountRetryAttempts = "1" + AccountRetryDelay = "60" + DatabaseMailExeMinimumLifeTime = "600" + DefaultAttachmentEncoding = "MIME" + LoggingLevel = "2" + MaxFileSize = "1000" + ProhibitedExtensions = "exe,dll,vbs,js" } foreach ($m in $mailSettings.GetEnumerator()) { $server.query("exec msdb.dbo.sysmail_configure_sp '$($m.key)','$($m.value)';") } + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } Context "Gets DbMail Settings" { - $results = Get-DbaDbMail -SqlInstance $TestConfig.instance2 + BeforeAll { + $results = Get-DbaDbMail -SqlInstance $TestConfig.instance2 + } + It "Gets results" { - $results | Should Not Be $null + $results | Should -Not -BeNullOrEmpty } - Foreach ($row in $($results.ConfigurationValues)) { - It "Should have ConfiguredValues of $($row.name)" { - $row.name | Should Bein $mailSettings.keys - } - It "Should have ConfiguredValues settings for $($row.name) of $($row.value)" { - $row.value | Should Bein $mailSettings.values + + It "Should have the expected mail settings" { + foreach ($row in $results.ConfigurationValues) { + $row.name | Should -BeIn $mailSettings.Keys + $row.value | Should -BeIn $mailSettings.Values } } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbMailAccount.Tests.ps1 b/tests/Get-DbaDbMailAccount.Tests.ps1 index dbb6f8a64a5..9530310f948 100644 --- a/tests/Get-DbaDbMailAccount.Tests.ps1 +++ b/tests/Get-DbaDbMailAccount.Tests.ps1 @@ -1,84 +1,135 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaDbMailAccount", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Account', 'ExcludeAccount', 'InputObject', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Account", + "ExcludeAccount", + "InputObject", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { - $accountname = "dbatoolsci_test_$(get-random)" + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # Set variables. They are available in all the It blocks. + $accountName = "dbatoolsci_test_$(Get-Random)" $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 $mailAccountSettings = "EXEC msdb.dbo.sysmail_add_account_sp - @account_name='$accountname', + @account_name='$accountName', @description='Mail account for email alerts', @email_address='dbatoolssci@dbatools.io', @display_name ='dbatoolsci mail alerts', @mailserver_name='smtp.dbatools.io', @replyto_address='no-reply@dbatools.io';" - $server.query($mailAccountSettings) + $server.Query($mailAccountSettings) + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } + AfterAll { + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # Cleanup all created object. $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 $mailAccountSettings = "EXEC msdb.dbo.sysmail_delete_account_sp - @account_name = '$accountname';" - $server.query($mailAccountSettings) + @account_name = '$accountName';" + $server.Query($mailAccountSettings) + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } Context "Gets DbMail Account" { - $results = Get-DbaDbMailAccount -SqlInstance $TestConfig.instance2 | Where-Object {$_.Name -eq "$accountname"} + BeforeAll { + $results = Get-DbaDbMailAccount -SqlInstance $TestConfig.instance2 | Where-Object Name -eq $accountName + } + It "Gets results" { - $results | Should Not Be $null + $results | Should -Not -BeNullOrEmpty } - It "Should have Name of $accounName" { - $results.name | Should Be $accountname + + It "Should have Name of $accountName" { + $results.Name | Should -Be $accountName } - It "Should have Desctiption of 'Mail account for email alerts' " { - $results.description | Should Be 'Mail account for email alerts' + + It "Should have Description of 'Mail account for email alerts' " { + $results.Description | Should -Be "Mail account for email alerts" } + It "Should have EmailAddress of 'dbatoolssci@dbatools.io' " { - $results.EmailAddress | Should Be 'dbatoolssci@dbatools.io' + $results.EmailAddress | Should -Be "dbatoolssci@dbatools.io" } + It "Should have ReplyToAddress of 'no-reply@dbatools.io' " { - $results.ReplyToAddress | Should Be 'no-reply@dbatools.io' + $results.ReplyToAddress | Should -Be "no-reply@dbatools.io" } + It "Should have MailServer of '[smtp.dbatools.io]' " { - $results.MailServers | Should Be '[smtp.dbatools.io]' + $results.MailServers | Should -Be "[smtp.dbatools.io]" } } + Context "Gets DbMail when using -Account" { - $results = Get-DbaDbMailAccount -SqlInstance $TestConfig.instance2 -Account $accountname + BeforeAll { + $results = Get-DbaDbMailAccount -SqlInstance $TestConfig.instance2 -Account $accountName + } + It "Gets results" { - $results | Should Not Be $null + $results | Should -Not -BeNullOrEmpty } - It "Should have Name of $accounName" { - $results.name | Should Be $accountname + + It "Should have Name of $accountName" { + $results.Name | Should -Be $accountName } - It "Should have Desctiption of 'Mail account for email alerts' " { - $results.description | Should Be 'Mail account for email alerts' + + It "Should have Description of 'Mail account for email alerts' " { + $results.Description | Should -Be "Mail account for email alerts" } + It "Should have EmailAddress of 'dbatoolssci@dbatools.io' " { - $results.EmailAddress | Should Be 'dbatoolssci@dbatools.io' + $results.EmailAddress | Should -Be "dbatoolssci@dbatools.io" } + It "Should have ReplyToAddress of 'no-reply@dbatools.io' " { - $results.ReplyToAddress | Should Be 'no-reply@dbatools.io' + $results.ReplyToAddress | Should -Be "no-reply@dbatools.io" } + It "Should have MailServer of '[smtp.dbatools.io]' " { - $results.MailServers | Should Be '[smtp.dbatools.io]' + $results.MailServers | Should -Be "[smtp.dbatools.io]" } } + Context "Gets no DbMail when using -ExcludeAccount" { - $results = Get-DbaDbMailAccount -SqlInstance $TestConfig.instance2 -ExcludeAccount $accountname + BeforeAll { + $results = Get-DbaDbMailAccount -SqlInstance $TestConfig.instance2 -ExcludeAccount $accountName + } + It "Gets no results" { - $results | Should Be $null + $results | Should -BeNullOrEmpty } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbMailConfig.Tests.ps1 b/tests/Get-DbaDbMailConfig.Tests.ps1 index 395dc5aa4b7..74c21ca1b18 100644 --- a/tests/Get-DbaDbMailConfig.Tests.ps1 +++ b/tests/Get-DbaDbMailConfig.Tests.ps1 @@ -1,62 +1,110 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaDbMailConfig", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Name', 'InputObject', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Name", + "InputObject", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { - $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 $mailSettings = @{ - AccountRetryAttempts = '1' - AccountRetryDelay = '60' - DatabaseMailExeMinimumLifeTime = '600' - DefaultAttachmentEncoding = 'MIME' - LoggingLevel = '2' - MaxFileSize = '1000' - ProhibitedExtensions = 'exe,dll,vbs,js' + AccountRetryAttempts = "1" + AccountRetryDelay = "60" + DatabaseMailExeMinimumLifeTime = "600" + DefaultAttachmentEncoding = "MIME" + LoggingLevel = "2" + MaxFileSize = "1000" + ProhibitedExtensions = "exe,dll,vbs,js" } foreach ($m in $mailSettings.GetEnumerator()) { $server.query("exec msdb.dbo.sysmail_configure_sp '$($m.key)','$($m.value)';") } + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') + } + + AfterAll { + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # No specific cleanup needed for DbMail config tests + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } Context "Gets DbMail Settings" { - $results = Get-DbaDbMailConfig -SqlInstance $TestConfig.instance2 + BeforeAll { + $results = Get-DbaDbMailConfig -SqlInstance $TestConfig.instance2 + $mailSettings = @{ + AccountRetryAttempts = "1" + AccountRetryDelay = "60" + DatabaseMailExeMinimumLifeTime = "600" + DefaultAttachmentEncoding = "MIME" + LoggingLevel = "2" + MaxFileSize = "1000" + ProhibitedExtensions = "exe,dll,vbs,js" + } + } + It "Gets results" { - $results | Should Not Be $null + $results | Should -Not -BeNullOrEmpty } - Foreach ($row in $($results)) { - It "Should have Configured Value of $($row.name)" { - $row.name | Should Bein $mailSettings.keys - } - It "Should have Configured Value settings for $($row.name) of $($row.value)" { - $row.value | Should Bein $mailSettings.values + + It "Should have all configured settings" { + foreach ($row in $results) { + $row.name | Should -BeIn $mailSettings.keys + $row.value | Should -BeIn $mailSettings.values } } } + Context "Gets DbMail Settings when using -Name" { - $results = Get-DbaDbMailConfig -SqlInstance $TestConfig.instance2 -Name "ProhibitedExtensions" + BeforeAll { + $results = Get-DbaDbMailConfig -SqlInstance $TestConfig.instance2 -Name "ProhibitedExtensions" + } + It "Gets results" { - $results | Should Not Be $null + $results | Should -Not -BeNullOrEmpty } + It "Should have Name 'ProhibitedExtensions'" { - $results.name | Should Be "ProhibitedExtensions" + $results.name | Should -BeExactly "ProhibitedExtensions" } + It "Should have Value 'exe,dll,vbs,js'" { - $results.value | Should Be "exe,dll,vbs,js" + $results.value | Should -BeExactly "exe,dll,vbs,js" } + It "Should have Description 'Extensions not allowed in outgoing mails'" { - $results.description | Should Be "Extensions not allowed in outgoing mails" + $results.description | Should -BeExactly "Extensions not allowed in outgoing mails" } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbMailHistory.Tests.ps1 b/tests/Get-DbaDbMailHistory.Tests.ps1 index 1a7b1f3846e..ee42442d989 100644 --- a/tests/Get-DbaDbMailHistory.Tests.ps1 +++ b/tests/Get-DbaDbMailHistory.Tests.ps1 @@ -1,20 +1,38 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaDbMailHistory", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Since', 'Status', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Since", + "Status", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 $server.Query("INSERT INTO msdb.[dbo].[sysmail_profile] ([name] @@ -59,49 +77,76 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { ($profile_id,'dbatoolssci@dbatools.io',NULL,NULL,'Test Job',NULL,NULL,'A Test Job failed to run','TEXT','Normal','Normal',NULL,'MIME',NULL,NULL, 0,1,256,'',0,0,'2018-12-9 11:44:32.600','dbatools\dbatoolssci',1,1,'2018-12-9 11:44:33.000','2018-12-9 11:44:33.273','sa')" ) + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } + AfterAll { + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + $server.Query("DELETE FROM msdb.dbo.sysmail_profile WHERE profile_id = '$profile_id'") $server.Query("DELETE FROM msdb.dbo.sysmail_mailitems WHERE profile_id = '$profile_id'") + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } Context "Gets Db Mail History" { - $results = Get-DbaDbMailHistory -SqlInstance $TestConfig.instance2 | Where-Object {$_.Subject -eq 'Test Job'} + BeforeAll { + $results = Get-DbaDbMailHistory -SqlInstance $TestConfig.instance2 | Where-Object { $PSItem.Subject -eq "Test Job" } + } + It "Gets results" { - $results | Should Not Be $null + $results | Should -Not -BeNullOrEmpty } + It "Should have created subject" { - $results.subject | Should be 'Test Job' + $results.subject | Should -Be "Test Job" } + It "Should have recipient of dbatoolssci@dbatools.io" { - $results.recipients | Should be 'dbatoolssci@dbatools.io' + $results.recipients | Should -Be "dbatoolssci@dbatools.io" } } + Context "Gets Db Mail History using -Status" { - $results = Get-DbaDbMailHistory -SqlInstance $TestConfig.instance2 -Status Sent + BeforeAll { + $results = Get-DbaDbMailHistory -SqlInstance $TestConfig.instance2 -Status Sent + } + It "Gets results" { - $results | Should Not Be $null + $results | Should -Not -BeNullOrEmpty } + It "Should have a Normal Importance" { - $results.Importance | Should be 'Normal' + $results.Importance | Should -Be "Normal" } + It "Should have a Normal Sensitivity" { - $results.sensitivity | Should be 'Normal' + $results.sensitivity | Should -Be "Normal" } + It "Should have SentStatus of Sent" { - $results.SentStatus | Should be 'Sent' + $results.SentStatus | Should -Be "Sent" } } + Context "Gets Db Mail History using -Since" { - $results = Get-DbaDbMailHistory -SqlInstance $TestConfig.instance2 -Since '2018-01-01' + BeforeAll { + $results = Get-DbaDbMailHistory -SqlInstance $TestConfig.instance2 -Since "2018-01-01" + } + It "Gets results" { - $results | Should Not Be $null + $results | Should -Not -BeNullOrEmpty } + It "Should have a SentDate greater than 2018-01-01" { - $results.SentDate | Should Begreaterthan '2018-01-01' + $results.SentDate | Should -BeGreaterThan "2018-01-01" } + It "Should have a SendRequestDate greater than 2018-01-01" { - $results.SendRequestDate | Should Begreaterthan '2018-01-01' + $results.SendRequestDate | Should -BeGreaterThan "2018-01-01" } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbMailLog.Tests.ps1 b/tests/Get-DbaDbMailLog.Tests.ps1 index 574d6617ef8..4122688ab1a 100644 --- a/tests/Get-DbaDbMailLog.Tests.ps1 +++ b/tests/Get-DbaDbMailLog.Tests.ps1 @@ -1,20 +1,38 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaDbMailLog", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Since', '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 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Since", + "Type", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 $server.Query("INSERT INTO msdb.[dbo].[sysmail_log] ([event_type] @@ -27,45 +45,72 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { ,[last_mod_user]) VALUES (1,'2018-12-09 12:18:14.920','DatabaseMail process is started',4890,NULL,NULL,'2018-12-09 12:18:14.920','dbatools\dbatoolssci')") + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } + AfterAll { + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 $server.Query("DELETE FROM msdb.[dbo].[sysmail_log] WHERE last_mod_user = 'dbatools\dbatoolssci'") + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } Context "Gets Db Mail Log" { - $results = Get-DbaDbMailLog -SqlInstance $TestConfig.instance2 | Where-Object {$_.Login -eq 'dbatools\dbatoolssci'} + BeforeAll { + $results = Get-DbaDbMailLog -SqlInstance $TestConfig.instance2 | Where-Object Login -eq "dbatools\dbatoolssci" + } + It "Gets results" { - $results | Should Not Be $null + $results | Should -Not -BeNullOrEmpty } + It "Should have created Description" { - $results.description | Should be 'DatabaseMail process is started' + $results.description | Should -Be "DatabaseMail process is started" } + It "Should have last modified user of dbatools\dbatoolssci " { - $results.lastmoduser | Should be 'dbatools\dbatoolssci' + $results.lastmoduser | Should -Be "dbatools\dbatoolssci" } } + Context "Gets Db Mail Log using -Type" { - $results = Get-DbaDbMailLog -SqlInstance $TestConfig.instance2 -Type Information + BeforeAll { + $results = Get-DbaDbMailLog -SqlInstance $TestConfig.instance2 -Type Information + } + It "Gets results" { - $results | Should Not Be $null + $results | Should -Not -BeNullOrEmpty } + It "Should have Log Id" { - $results.logid | Should not be $null + $results.logid | Should -Not -BeNullOrEmpty } + It "Should have an Event Type of Information" { - $results.eventtype | Should be 'Information' + $results.eventtype | Should -Be "Information" } } + Context "Gets Db Mail History using -Since" { - $results = Get-DbaDbMailLog -SqlInstance $TestConfig.instance2 -Since '2018-01-01' + BeforeAll { + $results = Get-DbaDbMailLog -SqlInstance $TestConfig.instance2 -Since "2018-01-01" + } + It "Gets results" { - $results | Should Not Be $null + $results | Should -Not -BeNullOrEmpty } + It "Should have a LogDate greater than 2018-01-01" { - $results.LogDate | Should Begreaterthan '2018-01-01' + $results.LogDate | Should -BeGreaterThan "2018-01-01" } + It "Should have a LastModDate greater than 2018-01-01" { - $results.LastModDate | Should Begreaterthan '2018-01-01' + $results.LastModDate | Should -BeGreaterThan "2018-01-01" } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbMailProfile.Tests.ps1 b/tests/Get-DbaDbMailProfile.Tests.ps1 index 7d076b739f7..ef0e96bfe9e 100644 --- a/tests/Get-DbaDbMailProfile.Tests.ps1 +++ b/tests/Get-DbaDbMailProfile.Tests.ps1 @@ -1,67 +1,111 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaDbMailProfile", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Profile', 'ExcludeProfile', 'InputObject', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Profile", + "ExcludeProfile", + "InputObject", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { - $profilename = "dbatoolsci_test_$(get-random)" + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true + + $profilename = "dbatoolsci_test_$(Get-Random)" $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2, $TestConfig.instance3 $mailProfile = "EXEC msdb.dbo.sysmail_add_profile_sp @profile_name='$profilename', @description='Profile for system email';" - $server.query($mailProfile) + $server.Query($mailProfile) + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove("*-Dba*:EnableException") } + AfterAll { + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true + $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2, $TestConfig.instance3 $mailProfile = "EXEC msdb.dbo.sysmail_delete_profile_sp @profile_name='$profilename';" - $server.query($mailProfile) + $server.Query($mailProfile) + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } Context "Gets DbMail Profile" { - $results = Get-DbaDbMailProfile -SqlInstance $TestConfig.instance2 | Where-Object {$_.name -eq "$profilename"} + BeforeAll { + $results = Get-DbaDbMailProfile -SqlInstance $TestConfig.instance2 | Where-Object Name -eq $profilename + $results2 = Get-DbaDbMailProfile -SqlInstance $server | Where-Object Name -eq $profilename + } + It "Gets results" { - $results | Should Not Be $null + $results | Should -Not -BeNullOrEmpty } + It "Should have Name of $profilename" { - $results.name | Should Be $profilename + $results.Name | Should -BeExactly $profilename } - It "Should have Desctiption of 'Profile for system email' " { - $results.description | Should Be 'Profile for system email' + + It "Should have Description of 'Profile for system email'" { + $results.Description | Should -BeExactly "Profile for system email" } - $results2 = Get-DbaDbMailProfile -SqlInstance $server | Where-Object {$_.name -eq "$profilename"} + It "Gets results from multiple instances" { - $results2 | Should Not Be $null - ($results2 | Select-Object SqlInstance -Unique).count | Should -Be 2 + $results2 | Should -Not -BeNullOrEmpty + ($results2 | Select-Object SqlInstance -Unique).Count | Should -BeExactly 2 } } + Context "Gets DbMailProfile when using -Profile" { - $results = Get-DbaDbMailProfile -SqlInstance $TestConfig.instance2 -Profile $profilename + BeforeAll { + $results = Get-DbaDbMailProfile -SqlInstance $TestConfig.instance2 -Profile $profilename + } + It "Gets results" { - $results | Should Not Be $null + $results | Should -Not -BeNullOrEmpty } + It "Should have Name of $profilename" { - $results.name | Should Be $profilename + $results.Name | Should -BeExactly $profilename } - It "Should have Desctiption of 'Profile for system email' " { - $results.description | Should Be 'Profile for system email' + + It "Should have Description of 'Profile for system email'" { + $results.Description | Should -BeExactly "Profile for system email" } } + Context "Gets no DbMailProfile when using -ExcludeProfile" { - $results = Get-DbaDbMailProfile -SqlInstance $TestConfig.instance2 -ExcludeProfile $profilename + BeforeAll { + $results = Get-DbaDbMailProfile -SqlInstance $TestConfig.instance2 -ExcludeProfile $profilename + } + It "Gets no results" { - $results | Should -Not -Contain $profilename + $results.Name | Should -Not -Contain $profilename } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbMailServer.Tests.ps1 b/tests/Get-DbaDbMailServer.Tests.ps1 index 7257734cceb..ab138433a78 100644 --- a/tests/Get-DbaDbMailServer.Tests.ps1 +++ b/tests/Get-DbaDbMailServer.Tests.ps1 @@ -1,69 +1,117 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaDbMailServer", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Server', 'Account', 'InputObject', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Server", + "Account", + "InputObject", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { - $accountname = "dbatoolsci_test_$(get-random)" - $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true + + # Set variables. They are available in all the It blocks. + $mailAccountName = "dbatoolsci_test_$(Get-Random)" + + # Create the mail account for testing + $primaryServer = Connect-DbaInstance -SqlInstance $TestConfig.instance2 $mailAccountSettings = "EXEC msdb.dbo.sysmail_add_account_sp - @account_name='$accountname', + @account_name='$mailAccountName', @description='Mail account for email alerts', @email_address='dbatoolssci@dbatools.io', @display_name ='dbatoolsci mail alerts', @mailserver_name='smtp.dbatools.io', @replyto_address='no-reply@dbatools.io';" - $server.query($mailAccountSettings) + $primaryServer.Query($mailAccountSettings) + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove("*-Dba*:EnableException") } + AfterAll { - $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true + + # Cleanup all created objects. + $cleanupServer = Connect-DbaInstance -SqlInstance $TestConfig.instance2 $mailAccountSettings = "EXEC msdb.dbo.sysmail_delete_account_sp - @account_name = '$accountname';" - $server.query($mailAccountSettings) + @account_name = '$mailAccountName';" + $cleanupServer.Query($mailAccountSettings) + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } Context "Gets DbMailServer" { - $results = Get-DbaDbMailServer -SqlInstance $TestConfig.instance2 | Where-Object {$_.account -eq "$accountname"} + BeforeAll { + $mailServerResults = Get-DbaDbMailServer -SqlInstance $TestConfig.instance2 | Where-Object Account -eq $mailAccountName + } + It "Gets results" { - $results | Should Not Be $null + $mailServerResults | Should -Not -BeNullOrEmpty } - It "Should have Account of $accounName" { - $results.Account | Should Be $accountname + + It "Should have Account of $mailAccountName" { + $mailServerResults.Account | Should -Be $mailAccountName } - It "Should have Name of 'smtp.dbatools.io' " { - $results.Name | Should Be 'smtp.dbatools.io' + + It "Should have Name of 'smtp.dbatools.io'" { + $mailServerResults.Name | Should -Be "smtp.dbatools.io" } + It "Should have Port on 25" { - $results.Port | Should Be 25 + $mailServerResults.Port | Should -Be 25 } + It "Should have SSL Disabled" { - $results.EnableSSL | Should Be $false + $mailServerResults.EnableSSL | Should -Be $false } - It "Should have ServerType of 'SMTP' " { - $results.ServerType | Should Be 'SMTP' + + It "Should have ServerType of 'SMTP'" { + $mailServerResults.ServerType | Should -Be "SMTP" } } + Context "Gets DbMailServer using -Server" { - $results = Get-DbaDbMailServer -SqlInstance $TestConfig.instance2 -Server 'smtp.dbatools.io' + BeforeAll { + $serverFilterResults = Get-DbaDbMailServer -SqlInstance $TestConfig.instance2 -Server "smtp.dbatools.io" + } + It "Gets results" { - $results | Should Not Be $null + $serverFilterResults | Should -Not -BeNullOrEmpty } } + Context "Gets DbMailServer using -Account" { - $results = Get-DbaDbMailServer -SqlInstance $TestConfig.instance2 -Account $accounname + BeforeAll { + $accountFilterResults = Get-DbaDbMailServer -SqlInstance $TestConfig.instance2 -Account $mailAccountName + } + It "Gets results" { - $results | Should Not Be $null + $accountFilterResults | Should -Not -BeNullOrEmpty } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbMasterKey.Tests.ps1 b/tests/Get-DbaDbMasterKey.Tests.ps1 index dd697c12a23..2036872c5d7 100644 --- a/tests/Get-DbaDbMasterKey.Tests.ps1 +++ b/tests/Get-DbaDbMasterKey.Tests.ps1 @@ -1,58 +1,96 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaDbMasterKey", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'ExcludeDatabase', 'InputObject', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Database", + "ExcludeDatabase", + "InputObject", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { - $dbname = "dbatoolsci_test_$(get-random)" + $dbname = "dbatoolsci_test_$(Get-Random)" $server = Connect-DbaInstance -SqlInstance $TestConfig.instance1 $null = $server.Query("Create Database [$dbname]") - $null = New-DbaDbMasterKey -SqlInstance $TestConfig.instance1 -Database $dbname -Password (ConvertTo-SecureString -AsPlainText -Force -String 'ThisIsAPassword!') -Confirm:$false + $splatMasterKey = @{ + SqlInstance = $TestConfig.instance1 + Database = $dbname + Password = (ConvertTo-SecureString -AsPlainText -Force -String "ThisIsAPassword!") + Confirm = $false + } + $null = New-DbaDbMasterKey @splatMasterKey } + AfterAll { Remove-DbaDbMasterKey -SqlInstance $TestConfig.instance1 -Database $dbname -Confirm:$false Remove-DbaDatabase -SqlInstance $TestConfig.instance1 -Database $dbname -Confirm:$false } Context "Gets DbMasterKey" { - $results = Get-DbaDbMasterKey -SqlInstance $TestConfig.instance1 | Where-Object {$_.Database -eq "$dbname"} + BeforeAll { + $results = Get-DbaDbMasterKey -SqlInstance $TestConfig.instance1 | Where-Object Database -eq $dbname + } + It "Gets results" { - $results | Should Not Be $null + $results | Should -Not -BeNullOrEmpty } + It "Should be the key on $dbname" { - $results.Database | Should Be $dbname + $results.Database | Should -BeExactly $dbname } + It "Should be encrypted by the server" { - $results.isEncryptedByServer | Should Be $true + $results.isEncryptedByServer | Should -BeTrue } } + Context "Gets DbMasterKey when using -database" { - $results = Get-DbaDbMasterKey -SqlInstance $TestConfig.instance1 -Database $dbname + BeforeAll { + $results = Get-DbaDbMasterKey -SqlInstance $TestConfig.instance1 -Database $dbname + } + It "Gets results" { - $results | Should Not Be $null + $results | Should -Not -BeNullOrEmpty } + It "Should be the key on $dbname" { - $results.Database | Should Be $dbname + $results.Database | Should -BeExactly $dbname } + It "Should be encrypted by the server" { - $results.isEncryptedByServer | Should Be $true + $results.isEncryptedByServer | Should -BeTrue } } + Context "Gets no DbMasterKey when using -ExcludeDatabase" { - $results = Get-DbaDbMasterKey -SqlInstance $TestConfig.instance1 -ExcludeDatabase $dbname + BeforeAll { + $results = Get-DbaDbMasterKey -SqlInstance $TestConfig.instance1 -ExcludeDatabase $dbname + } + It "Gets no results" { - $results | Should Be $null + $results | Should -BeNullOrEmpty } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbMemoryUsage.Tests.ps1 b/tests/Get-DbaDbMemoryUsage.Tests.ps1 index 52f0e48bb99..0c29c1dc525 100644 --- a/tests/Get-DbaDbMemoryUsage.Tests.ps1 +++ b/tests/Get-DbaDbMemoryUsage.Tests.ps1 @@ -1,41 +1,58 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaDbMemoryUsage", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tags "UnitTests" { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'ExcludeDatabase', 'IncludeSystemDb', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Database", + "ExcludeDatabase", + "IncludeSystemDb", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { $instance = Connect-DbaInstance -SqlInstance $TestConfig.instance2 } + Context "Functionality" { - It 'Returns data' { + It "Returns data" { $result = Get-DbaDbMemoryUsage -SqlInstance $instance -IncludeSystemDb - $result.Count | Should -BeGreaterOrEqual 1 + $result.Status.Count | Should -BeGreaterOrEqual 1 } - It 'Accepts a list of databases' { - $result = Get-DbaDbMemoryUsage -SqlInstance $instance -Database 'ResourceDb' -IncludeSystemDb + It "Accepts a list of databases" { + $result = Get-DbaDbMemoryUsage -SqlInstance $instance -Database "ResourceDb" -IncludeSystemDb $uniqueDbs = $result.Database | Select-Object -Unique - $uniqueDbs | Should -Be 'ResourceDb' + $uniqueDbs | Should -Be "ResourceDb" } - It 'Excludes databases' { - $result = Get-DbaDbMemoryUsage -SqlInstance $instance -IncludeSystemDb -ExcludeDatabase 'ResourceDb' + It "Excludes databases" { + $result = Get-DbaDbMemoryUsage -SqlInstance $instance -IncludeSystemDb -ExcludeDatabase "ResourceDb" $uniqueDbs = $result.Database | Select-Object -Unique - $uniqueDbs | Should -Not -Contain 'ResourceDb' - $uniqueDbs | Should -Contain 'master' + $uniqueDbs | Should -Not -Contain "ResourceDb" + $uniqueDbs | Should -Contain "master" } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbMirror.Tests.ps1 b/tests/Get-DbaDbMirror.Tests.ps1 index 4ff5e8e4dc5..ecd9781bffb 100644 --- a/tests/Get-DbaDbMirror.Tests.ps1 +++ b/tests/Get-DbaDbMirror.Tests.ps1 @@ -1,48 +1,79 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaDbMirror", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Database", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tag "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { - $null = Get-DbaProcess -SqlInstance $TestConfig.instance2, $TestConfig.instance3 | Where-Object Program -Match dbatools | Stop-DbaProcess -Confirm:$false -WarningAction SilentlyContinue - $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # Set variables. They are available in all the It blocks. $db1 = "dbatoolsci_mirroring" $db2 = "dbatoolsci_mirroring_db2" + # Clean up any existing processes and databases + $null = Get-DbaProcess -SqlInstance $TestConfig.instance2, $TestConfig.instance3 | Where-Object Program -Match dbatools | Stop-DbaProcess -Confirm:$false -WarningAction SilentlyContinue + Remove-DbaDbMirror -SqlInstance $TestConfig.instance2, $TestConfig.instance3 -Database $db1, $db2 -Confirm:$false $null = Get-DbaDatabase -SqlInstance $TestConfig.instance2, $TestConfig.instance3 -Database $db1, $db2 | Remove-DbaDatabase -Confirm:$false + # Create test databases + $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 $null = $server.Query("CREATE DATABASE $db1") $null = $server.Query("CREATE DATABASE $db2") + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } + AfterAll { + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # Cleanup all created objects. $null = Get-DbaDatabase -SqlInstance $TestConfig.instance2, $TestConfig.instance3 -Database $db1, $db2 | Remove-DbaDbMirror -Confirm:$false $null = Remove-DbaDatabase -Confirm:$false -SqlInstance $TestConfig.instance2, $TestConfig.instance3 -Database $db1, $db2 -ErrorAction SilentlyContinue + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } - It -Skip "returns more than one database" { + It "returns more than one database" -Skip:$true { $null = Invoke-DbaDbMirroring -Primary $TestConfig.instance2 -Mirror $TestConfig.instance3 -Database $db1, $db2 -Confirm:$false -Force -SharedPath C:\temp -WarningAction Continue - (Get-DbaDbMirror -SqlInstance $TestConfig.instance3).Count | Should -Be 2 + @(Get-DbaDbMirror -SqlInstance $TestConfig.instance3).Count | Should -Be 2 } - It -Skip "returns just one database" { - (Get-DbaDbMirror -SqlInstance $TestConfig.instance3 -Database $db2).Count | Should -Be 1 + It "returns just one database" -Skip:$true { + @(Get-DbaDbMirror -SqlInstance $TestConfig.instance3 -Database $db2).Count | Should -Be 1 } - It -Skip "returns 2x1 database" { - (Get-DbaDbMirror -SqlInstance $TestConfig.instance2, $TestConfig.instance3 -Database $db2).Count | Should -Be 2 + It "returns 2x1 database" -Skip:$true { + @(Get-DbaDbMirror -SqlInstance $TestConfig.instance2, $TestConfig.instance3 -Database $db2).Count | Should -Be 2 } -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbMirrorMonitor.Tests.ps1 b/tests/Get-DbaDbMirrorMonitor.Tests.ps1 index 5b0d06de617..4372193cf75 100644 --- a/tests/Get-DbaDbMirrorMonitor.Tests.ps1 +++ b/tests/Get-DbaDbMirrorMonitor.Tests.ps1 @@ -1,14 +1,31 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaDbMirrorMonitor", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'InputObject', 'Update', 'LimitResults', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Database", + "InputObject", + "Update", + "LimitResults", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } diff --git a/tests/Get-DbaDbObjectTrigger.Tests.ps1 b/tests/Get-DbaDbObjectTrigger.Tests.ps1 index 4f51c3e2a03..71c1d86901c 100644 --- a/tests/Get-DbaDbObjectTrigger.Tests.ps1 +++ b/tests/Get-DbaDbObjectTrigger.Tests.ps1 @@ -1,24 +1,40 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaDbObjectTrigger", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - $paramCount = 7 - $defaultParamCount = 11 - [object[]]$params = (Get-ChildItem function:\Get-DbaDbObjectTrigger).Parameters.Keys - $knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'ExcludeDatabase', 'Type', 'InputObject', 'EnableException' - It "Should contain our specific parameters" { - ( (Compare-Object -ReferenceObject $knownParameters -DifferenceObject $params -IncludeEqual | Where-Object SideIndicator -eq "==").Count ) | Should Be $paramCount - } - It "Should only contain $paramCount parameters" { - $params.Count - $defaultParamCount | Should Be $paramCount +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Database", + "ExcludeDatabase", + "Type", + "InputObject", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + $dbname = "dbatoolsci_addtriggertoobject" $tablename = "dbo.dbatoolsci_trigger" $triggertablename = "dbatoolsci_triggerontable" @@ -53,13 +69,23 @@ CREATE TRIGGER $triggerviewname $server.Query("$triggerview", $dbname) $systemDbs = Get-DbaDatabase -SqlInstance $TestConfig.instance2 -ExcludeUser + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } AfterAll { + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + $null = Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname | Remove-DbaDatabase -Confirm:$false + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } Context "Gets Table Trigger" { - $results = Get-DbaDbObjectTrigger -SqlInstance $TestConfig.instance2 -ExcludeDatabase $systemDbs.Name | Where-Object { $_.name -eq "dbatoolsci_triggerontable" } + BeforeAll { + $results = Get-DbaDbObjectTrigger -SqlInstance $TestConfig.instance2 -ExcludeDatabase $systemDbs.Name | Where-Object Name -eq "dbatoolsci_triggerontable" + } It "Gets results" { $results | Should -Not -Be $null } @@ -71,7 +97,9 @@ CREATE TRIGGER $triggerviewname } } Context "Gets Table Trigger when using -Database" { - $results = Get-DbaDbObjectTrigger -SqlInstance $TestConfig.instance2 -Database $dbname | Where-Object { $_.name -eq "dbatoolsci_triggerontable" } + BeforeAll { + $results = Get-DbaDbObjectTrigger -SqlInstance $TestConfig.instance2 -Database $dbname | Where-Object Name -eq "dbatoolsci_triggerontable" + } It "Gets results" { $results | Should -Not -Be $null } @@ -83,7 +111,9 @@ CREATE TRIGGER $triggerviewname } } Context "Gets Table Trigger passing table object using pipeline" { - $results = Get-DbaDbTable -SqlInstance $TestConfig.instance2 -Database $dbname -Table "dbatoolsci_trigger" | Get-DbaDbObjectTrigger + BeforeAll { + $results = Get-DbaDbTable -SqlInstance $TestConfig.instance2 -Database $dbname -Table "dbatoolsci_trigger" | Get-DbaDbObjectTrigger + } It "Gets results" { $results | Should -Not -Be $null } @@ -95,7 +125,9 @@ CREATE TRIGGER $triggerviewname } } Context "Gets View Trigger" { - $results = Get-DbaDbObjectTrigger -SqlInstance $TestConfig.instance2 -ExcludeDatabase $systemDbs.Name | Where-Object { $_.name -eq "dbatoolsci_triggeronview" } + BeforeAll { + $results = Get-DbaDbObjectTrigger -SqlInstance $TestConfig.instance2 -ExcludeDatabase $systemDbs.Name | Where-Object Name -eq "dbatoolsci_triggeronview" + } It "Gets results" { $results | Should -Not -Be $null } @@ -107,7 +139,9 @@ CREATE TRIGGER $triggerviewname } } Context "Gets View Trigger when using -Database" { - $results = Get-DbaDbObjectTrigger -SqlInstance $TestConfig.instance2 -Database $dbname | Where-Object { $_.name -eq "dbatoolsci_triggeronview" } + BeforeAll { + $results = Get-DbaDbObjectTrigger -SqlInstance $TestConfig.instance2 -Database $dbname | Where-Object Name -eq "dbatoolsci_triggeronview" + } It "Gets results" { $results | Should -Not -Be $null } @@ -119,7 +153,9 @@ CREATE TRIGGER $triggerviewname } } Context "Gets View Trigger passing table object using pipeline" { - $results = Get-DbaDbView -SqlInstance $TestConfig.instance2 -Database $dbname -ExcludeSystemView | Get-DbaDbObjectTrigger + BeforeAll { + $results = Get-DbaDbView -SqlInstance $TestConfig.instance2 -Database $dbname -ExcludeSystemView | Get-DbaDbObjectTrigger + } It "Gets results" { $results | Should -Not -Be $null } @@ -131,47 +167,55 @@ CREATE TRIGGER $triggerviewname } } Context "Gets Table and View Trigger passing both objects using pipeline" { - $tableResults = Get-DbaDbTable -SqlInstance $TestConfig.instance2 -Database $dbname -Table "dbatoolsci_trigger" - $viewResults = Get-DbaDbView -SqlInstance $TestConfig.instance2 -Database $dbname -ExcludeSystemView - $results = $tableResults, $viewResults | Get-DbaDbObjectTrigger + BeforeAll { + $tableResults = Get-DbaDbTable -SqlInstance $TestConfig.instance2 -Database $dbname -Table "dbatoolsci_trigger" + $viewResults = Get-DbaDbView -SqlInstance $TestConfig.instance2 -Database $dbname -ExcludeSystemView + $results = $tableResults, $viewResults | Get-DbaDbObjectTrigger + } It "Gets results" { $results | Should -Not -Be $null } - It "Should be enabled" { + It "Should return two triggers" { $results.Count | Should -Be 2 } } Context "Gets All types Trigger when using -Type" { - $results = Get-DbaDbObjectTrigger -SqlInstance $TestConfig.instance2 -Database $dbname -Type All + BeforeAll { + $results = Get-DbaDbObjectTrigger -SqlInstance $TestConfig.instance2 -Database $dbname -Type All + } It "Gets results" { $results | Should -Not -Be $null } - It "Should be only one" { + It "Should return two triggers" { $results.Count | Should -Be 2 } } Context "Gets only Table Trigger when using -Type" { - $results = Get-DbaDbObjectTrigger -SqlInstance $TestConfig.instance2 -Database $dbname -Type Table + BeforeAll { + $results = Get-DbaDbObjectTrigger -SqlInstance $TestConfig.instance2 -Database $dbname -Type Table + } It "Gets results" { $results | Should -Not -Be $null } It "Should be only one" { $results.Count | Should -Be 1 } - It "Should have text of Trigger" { + It "Should be a Table trigger" { $results.Parent.GetType().Name | Should -Be "Table" } } Context "Gets only View Trigger when using -Type" { - $results = Get-DbaDbObjectTrigger -SqlInstance $TestConfig.instance2 -Database $dbname -Type View + BeforeAll { + $results = Get-DbaDbObjectTrigger -SqlInstance $TestConfig.instance2 -Database $dbname -Type View + } It "Gets results" { $results | Should -Not -Be $null } It "Should be only one" { $results.Count | Should -Be 1 } - It "Should have text of Trigger" { + It "Should be a View trigger" { $results.Parent.GetType().Name | Should -Be "View" } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbOrphanUser.Tests.ps1 b/tests/Get-DbaDbOrphanUser.Tests.ps1 index 0dfdd511908..da5e47e0ae5 100644 --- a/tests/Get-DbaDbOrphanUser.Tests.ps1 +++ b/tests/Get-DbaDbOrphanUser.Tests.ps1 @@ -1,59 +1,101 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaDbOrphanUser", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'ExcludeDatabase', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Database", + "ExcludeDatabase", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tag "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { - $loginsq = @' + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + $loginsq = @" CREATE LOGIN [dbatoolsci_orphan1] WITH PASSWORD = N'password1', CHECK_EXPIRATION = OFF, CHECK_POLICY = OFF; CREATE LOGIN [dbatoolsci_orphan2] WITH PASSWORD = N'password2', CHECK_EXPIRATION = OFF, CHECK_POLICY = OFF; CREATE LOGIN [dbatoolsci_orphan3] WITH PASSWORD = N'password3', CHECK_EXPIRATION = OFF, CHECK_POLICY = OFF; CREATE DATABASE dbatoolsci_orphan; -'@ +"@ $server = Connect-DbaInstance -SqlInstance $TestConfig.instance1 - $null = Remove-DbaLogin -SqlInstance $server -Login dbatoolsci_orphan1, dbatoolsci_orphan2, dbatoolsci_orphan3 -Force -Confirm:$false - $null = Remove-DbaDatabase -SqlInstance $server -Database dbatoolsci_orphan -Confirm:$false + $null = Remove-DbaLogin -SqlInstance $server -Login dbatoolsci_orphan1, dbatoolsci_orphan2, dbatoolsci_orphan3 -Force + $null = Remove-DbaDatabase -SqlInstance $server -Database dbatoolsci_orphan $null = Invoke-DbaQuery -SqlInstance $server -Query $loginsq - $usersq = @' + $usersq = @" CREATE USER [dbatoolsci_orphan1] FROM LOGIN [dbatoolsci_orphan1]; CREATE USER [dbatoolsci_orphan2] FROM LOGIN [dbatoolsci_orphan2]; CREATE USER [dbatoolsci_orphan3] FROM LOGIN [dbatoolsci_orphan3]; -'@ +"@ Invoke-DbaQuery -SqlInstance $server -Query $usersq -Database dbatoolsci_orphan $dropOrphan = "DROP LOGIN [dbatoolsci_orphan1];DROP LOGIN [dbatoolsci_orphan2];" Invoke-DbaQuery -SqlInstance $server -Query $dropOrphan + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } + AfterAll { + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + $server = Connect-DbaInstance -SqlInstance $TestConfig.instance1 - $null = Remove-DbaLogin -SqlInstance $server -Login dbatoolsci_orphan1, dbatoolsci_orphan2, dbatoolsci_orphan3 -Force -Confirm:$false - $null = Remove-DbaDatabase -SqlInstance $server -Database dbatoolsci_orphan -Confirm:$false - } - It "shows time taken for preparation" { - 1 | Should -Be 1 + $null = Remove-DbaLogin -SqlInstance $server -Login dbatoolsci_orphan1, dbatoolsci_orphan2, dbatoolsci_orphan3 -Force -ErrorAction SilentlyContinue + $null = Remove-DbaDatabase -SqlInstance $server -Database dbatoolsci_orphan -ErrorAction SilentlyContinue + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } - $results = Get-DbaDbOrphanUser -SqlInstance $TestConfig.instance1 -Database dbatoolsci_orphan - It "Finds two orphans" { - $results.Count | Should -Be 2 - foreach ($user in $Users) { - $user.User | Should -BeIn @('dbatoolsci_orphan1', 'dbatoolsci_orphan2') - $user.DatabaseName | Should -Be 'dbatoolsci_orphan' + + Context "When checking for orphan users" { + BeforeAll { + $results = @(Get-DbaDbOrphanUser -SqlInstance $TestConfig.instance1 -Database dbatoolsci_orphan) + } + + It "Shows time taken for preparation" { + 1 | Should -BeExactly 1 + } + + It "Finds two orphans" { + $results.Count | Should -BeExactly 2 + foreach ($user in $results) { + $user.User | Should -BeIn @("dbatoolsci_orphan1", "dbatoolsci_orphan2") + $user.DatabaseName | Should -Be "dbatoolsci_orphan" + } + } + + It "Has the correct properties" { + $result = $results[0] + $ExpectedProps = @( + "ComputerName", + "InstanceName", + "SqlInstance", + "DatabaseName", + "User", + "SmoUser" + ) + ($result.PsObject.Properties.Name | Sort-Object) | Should -Be ($ExpectedProps | Sort-Object) } } - It "has the correct properties" { - $result = $results[0] - $ExpectedProps = 'ComputerName,InstanceName,SqlInstance,DatabaseName,User,SmoUser'.Split(',') - ($result.PsObject.Properties.Name | Sort-Object) | Should Be ($ExpectedProps | Sort-Object) - } -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbPageInfo.Tests.ps1 b/tests/Get-DbaDbPageInfo.Tests.ps1 index f612519117c..3ba9e9711dc 100644 --- a/tests/Get-DbaDbPageInfo.Tests.ps1 +++ b/tests/Get-DbaDbPageInfo.Tests.ps1 @@ -1,26 +1,55 @@ -$commandname = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaDbPageInfo", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { +Describe $CommandName -Tag UnitTests { Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'Schema', 'Table', 'InputObject', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Database", + "Schema", + "Table", + "InputObject", + "EnableException" + ) + } + It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Test" -Tag "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + $random = Get-Random $dbname = "dbatoolsci_pageinfo_$random" - Get-DbaProcess -SqlInstance $TestConfig.instance2 -Program 'dbatools PowerShell module - dbatools.io' | Stop-DbaProcess -WarningAction SilentlyContinue + + # Clean up any existing connections + $splatStopProcess = @{ + SqlInstance = $TestConfig.instance2 + Program = "dbatools PowerShell module - dbatools.io" + WarningAction = "SilentlyContinue" + EnableException = $true + } + Get-DbaProcess @splatStopProcess | Stop-DbaProcess -WarningAction SilentlyContinue + $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 $server.Query("CREATE DATABASE $dbname;") - $server.Databases[$dbname].Query('CREATE TABLE [dbo].[TestTable](TestText VARCHAR(MAX) NOT NULL)') + $server.Databases[$dbname].Query("CREATE TABLE [dbo].[TestTable](TestText VARCHAR(MAX) NOT NULL)") $query = " INSERT INTO dbo.TestTable ( @@ -34,16 +63,27 @@ Describe "$CommandName Integration Test" -Tag "IntegrationTests" { $query += ",('AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA')" } $server.Databases[$dbname].Query($query) + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } AfterAll { - Remove-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname -Confirm:$false + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + Remove-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname -Confirm:$false -ErrorAction SilentlyContinue + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } Context "Count Pages" { - $result = Get-DbaDbPageInfo -SqlInstance $TestConfig.instance2 -Database $dbname + BeforeAll { + $result = Get-DbaDbPageInfo -SqlInstance $TestConfig.instance2 -Database $dbname + } + It "returns the proper results" { - ($result).Count | Should -Be 9 - ($result | Where-Object { $_.IsAllocated -eq $false }).Count | Should -Be 5 - ($result | Where-Object { $_.IsAllocated -eq $true }).Count | Should -Be 4 + @($result).Count | Should -Be 9 + @($result | Where-Object IsAllocated -eq $false).Count | Should -Be 5 + @($result | Where-Object IsAllocated -eq $true).Count | Should -Be 4 } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbPartitionFunction.Tests.ps1 b/tests/Get-DbaDbPartitionFunction.Tests.ps1 index 2bd6287299a..d6d2cdb9877 100644 --- a/tests/Get-DbaDbPartitionFunction.Tests.ps1 +++ b/tests/Get-DbaDbPartitionFunction.Tests.ps1 @@ -1,33 +1,58 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaDbPartitionFunction", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'ExcludeDatabase', 'PartitionFunction', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Database", + "ExcludeDatabase", + "PartitionFunction", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { - $tempguid = [guid]::newguid(); + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + $tempguid = [guid]::newguid() $PFName = "dbatoolssci_$($tempguid.guid)" - $CreateTestPartitionFunction = "CREATE PARTITION FUNCTION [$PFName] (int) AS RANGE LEFT FOR VALUES (1, 100, 1000, 10000, 100000);" + $CreateTestPartitionFunction = "CREATE PARTITION FUNCTION [$PFName] (int) AS RANGE LEFT FOR VALUES (1, 100, 1000, 10000, 100000);" Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Query $CreateTestPartitionFunction -Database master + + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } + AfterAll { + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + $DropTestPartitionFunction = "DROP PARTITION FUNCTION [$PFName];" - Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Query $DropTestPartitionFunction -Database master + Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Query $DropTestPartitionFunction -Database master -ErrorAction SilentlyContinue } Context "Partition Functions are correctly located" { - $results1 = Get-DbaDbPartitionFunction -SqlInstance $TestConfig.instance2 -Database master | Select-Object * - $results2 = Get-DbaDbPartitionFunction -SqlInstance $TestConfig.instance2 + BeforeAll { + $results1 = Get-DbaDbPartitionFunction -SqlInstance $TestConfig.instance2 -Database master | Select-Object * + $results2 = Get-DbaDbPartitionFunction -SqlInstance $TestConfig.instance2 + } It "Should execute and return results" { $results2 | Should -Not -Be $null @@ -50,7 +75,7 @@ Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { } It "Should not Throw an Error" { - {Get-DbaDbPartitionFunction -SqlInstance $TestConfig.instance2 -ExcludeDatabase master } | Should -not -Throw + { Get-DbaDbPartitionFunction -SqlInstance $TestConfig.instance2 -ExcludeDatabase master } | Should -Not -Throw } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbPartitionScheme.Tests.ps1 b/tests/Get-DbaDbPartitionScheme.Tests.ps1 index 2c769ef401d..c16bf1720d1 100644 --- a/tests/Get-DbaDbPartitionScheme.Tests.ps1 +++ b/tests/Get-DbaDbPartitionScheme.Tests.ps1 @@ -1,44 +1,88 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaDbPartitionScheme", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'ExcludeDatabase', 'PartitionScheme', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Database", + "ExcludeDatabase", + "PartitionScheme", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { - $tempguid = [guid]::newguid(); - $PFName = "dbatoolssci_$($tempguid.guid)" - $PFScheme = "dbatoolssci_PFScheme" + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + # Set variables. They are available in all the It blocks. + $tempguid = [guid]::newguid() + $PFName = "dbatoolssci_$($tempguid.guid)" + $PFScheme = "dbatoolssci_PFScheme" + + # Create the test partition scheme $CreateTestPartitionScheme = @" CREATE PARTITION FUNCTION [$PFName] (int) AS RANGE LEFT FOR VALUES (1, 100, 1000, 10000, 100000); GO CREATE PARTITION SCHEME $PFScheme AS PARTITION [$PFName] ALL TO ( [PRIMARY] ); "@ - Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Query $CreateTestPartitionScheme -Database master + $splatCreate = @{ + SqlInstance = $TestConfig.instance2 + Query = $CreateTestPartitionScheme + Database = "master" + } + Invoke-DbaQuery @splatCreate + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } + AfterAll { + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # Cleanup all created objects. $DropTestPartitionScheme = @" DROP PARTITION SCHEME [$PFScheme]; GO DROP PARTITION FUNCTION [$PFName]; "@ - Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Query $DropTestPartitionScheme -Database master + $splatDrop = @{ + SqlInstance = $TestConfig.instance2 + Query = $DropTestPartitionScheme + Database = "master" + EnableException = $true + } + Invoke-DbaQuery @splatDrop -ErrorAction SilentlyContinue + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } Context "Partition Schemes are correctly located" { - $results1 = Get-DbaDbPartitionScheme -SqlInstance $TestConfig.instance2 -Database master | Select-Object * - $results2 = Get-DbaDbPartitionScheme -SqlInstance $TestConfig.instance2 + BeforeAll { + $results1 = Get-DbaDbPartitionScheme -SqlInstance $TestConfig.instance2 -Database master | Select-Object * + $results2 = Get-DbaDbPartitionScheme -SqlInstance $TestConfig.instance2 + } It "Should execute and return results" { $results2 | Should -Not -Be $null @@ -57,11 +101,11 @@ DROP PARTITION FUNCTION [$PFName]; } It "Should have FileGroups of [Primary]" { - $results1.FileGroups | Should -Be @('PRIMARY', 'PRIMARY', 'PRIMARY', 'PRIMARY', 'PRIMARY', 'PRIMARY') + $results1.FileGroups | Should -Be @("PRIMARY", "PRIMARY", "PRIMARY", "PRIMARY", "PRIMARY", "PRIMARY") } It "Should not Throw an Error" { - {Get-DbaDbPartitionScheme -SqlInstance $TestConfig.instance2 -ExcludeDatabase master } | Should -not -Throw + { Get-DbaDbPartitionScheme -SqlInstance $TestConfig.instance2 -ExcludeDatabase master } | Should -Not -Throw } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbQueryStoreOption.Tests.ps1 b/tests/Get-DbaDbQueryStoreOption.Tests.ps1 index 0e30b0f1fd0..3e7d0947aeb 100644 --- a/tests/Get-DbaDbQueryStoreOption.Tests.ps1 +++ b/tests/Get-DbaDbQueryStoreOption.Tests.ps1 @@ -1,14 +1,29 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaDbQueryStoreOption", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'ExcludeDatabase', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Database", + "ExcludeDatabase", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } diff --git a/tests/Get-DbaDbRecoveryModel.Tests.ps1 b/tests/Get-DbaDbRecoveryModel.Tests.ps1 index 86faedfb9fa..8994117dc54 100644 --- a/tests/Get-DbaDbRecoveryModel.Tests.ps1 +++ b/tests/Get-DbaDbRecoveryModel.Tests.ps1 @@ -1,36 +1,54 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaDbRecoveryModel", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { +Describe $CommandName -Tag UnitTests { Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'RecoveryModel', 'Database', 'ExcludeDatabase', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "RecoveryModel", + "Database", + "ExcludeDatabase", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { Context "Recovery model is correctly identified" { - $results = Get-DbaDbRecoveryModel -SqlInstance $TestConfig.instance2 -Database master + BeforeAll { + $masterResults = Get-DbaDbRecoveryModel -SqlInstance $TestConfig.instance2 -Database master + $allResults = Get-DbaDbRecoveryModel -SqlInstance $TestConfig.instance2 + } It "returns a single database" { - $results.Count | Should Be 1 + $masterResults.Status.Count | Should -BeExactly 1 } It "returns the correct recovery model" { - $results.RecoveryModel -eq 'Simple' | Should Be $true + $masterResults.RecoveryModel -eq "Simple" | Should -BeTrue } - $results = Get-DbaDbRecoveryModel -SqlInstance $TestConfig.instance2 - It "returns accurate number of results" { - $results.Count -ge 4 | Should Be $true + $allResults.Status.Count -ge 4 | Should -BeTrue } } + Context "RecoveryModel parameter works" { BeforeAll { $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 @@ -38,17 +56,19 @@ Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { Get-DbaDatabase -SqlInstance $server -Database $dbname | Remove-DbaDatabase -Confirm:$false $server.Query("CREATE DATABASE $dbname; ALTER DATABASE $dbname SET RECOVERY BULK_LOGGED WITH NO_WAIT;") } + AfterAll { - Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname | Remove-DbaDatabase -Confirm:$false + Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname | Remove-DbaDatabase -Confirm:$false -ErrorAction SilentlyContinue } It "gets the newly created database with the correct recovery model" { $results = Get-DbaDbRecoveryModel -SqlInstance $TestConfig.instance2 -Database $dbname - $results.RecoveryModel -eq 'BulkLogged' | Should Be $true + $results.RecoveryModel -eq "BulkLogged" | Should -BeTrue } + It "honors the RecoveryModel parameter filter" { $results = Get-DbaDbRecoveryModel -SqlInstance $TestConfig.instance2 -RecoveryModel BulkLogged - $results.Name -contains $dbname | Should Be $true + $results.Name -contains $dbname | Should -BeTrue } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbRestoreHistory.Tests.ps1 b/tests/Get-DbaDbRestoreHistory.Tests.ps1 index 521d4d26f83..34e9197301f 100644 --- a/tests/Get-DbaDbRestoreHistory.Tests.ps1 +++ b/tests/Get-DbaDbRestoreHistory.Tests.ps1 @@ -1,39 +1,101 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaDbRestoreHistory", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { +Describe $CommandName -Tag UnitTests { Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'ExcludeDatabase', 'Since', 'RestoreType', 'Force', 'Last', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Database", + "ExcludeDatabase", + "Since", + "RestoreType", + "Force", + "Last", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { + +Describe $CommandName -Tag IntegrationTests { BeforeAll { + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + $random = Get-Random $dbname1 = "dbatoolsci_restorehistory1_$random" $dbname2 = "dbatoolsci_restorehistory2_$random" + $null = Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname1, $dbname2 | Remove-DbaDatabase -Confirm:$false - $null = Restore-DbaDatabase -SqlInstance $TestConfig.instance2 -Path "$($TestConfig.appveyorlabrepo)\singlerestore\singlerestore.bak" -DatabaseName $dbname1 -DestinationFilePrefix $dbname1 - $null = Restore-DbaDatabase -SqlInstance $TestConfig.instance2 -Path "$($TestConfig.appveyorlabrepo)\singlerestore\singlerestore.bak" -DatabaseName $dbname2 -DestinationFilePrefix $dbname2 - $null = Restore-DbaDatabase -SqlInstance $TestConfig.instance2 -Path "$($TestConfig.appveyorlabrepo)\singlerestore\singlerestore.bak" -DatabaseName $dbname2 -DestinationFilePrefix "rsh_pre_$dbname2" -WithReplace + + $splatRestore1 = @{ + SqlInstance = $TestConfig.instance2 + Path = "$($TestConfig.appveyorlabrepo)\singlerestore\singlerestore.bak" + DatabaseName = $dbname1 + DestinationFilePrefix = $dbname1 + } + $null = Restore-DbaDatabase @splatRestore1 + + $splatRestore2 = @{ + SqlInstance = $TestConfig.instance2 + Path = "$($TestConfig.appveyorlabrepo)\singlerestore\singlerestore.bak" + DatabaseName = $dbname2 + DestinationFilePrefix = $dbname2 + } + $null = Restore-DbaDatabase @splatRestore2 + + $splatRestore3 = @{ + SqlInstance = $TestConfig.instance2 + Path = "$($TestConfig.appveyorlabrepo)\singlerestore\singlerestore.bak" + DatabaseName = $dbname2 + DestinationFilePrefix = "rsh_pre_$dbname2" + WithReplace = $true + } + $null = Restore-DbaDatabase @splatRestore3 + $fullBackup = Backup-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname1 -Type Full $diffBackup = Backup-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname1 -Type Diff $logBackup = Backup-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname1 -Type Log - $null = Restore-DbaDatabase -SqlInstance $TestConfig.instance2 -Path $diffBackup.BackupPath, $logBackup.BackupPath -DatabaseName $dbname1 -WithReplace + $splatRestoreFinal = @{ + SqlInstance = $TestConfig.instance2 + Path = $diffBackup.BackupPath, $logBackup.BackupPath + DatabaseName = $dbname1 + WithReplace = $true + } + $null = Restore-DbaDatabase @splatRestoreFinal + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } AfterAll { + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + $null = Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname1, $dbname2 | Remove-DbaDatabase -Confirm:$false - Remove-Item -Path $fullBackup.BackupPath -Force - Remove-Item -Path $logBackup.BackupPath -Force + Remove-Item -Path $fullBackup.BackupPath -Force -ErrorAction SilentlyContinue + Remove-Item -Path $logBackup.BackupPath -Force -ErrorAction SilentlyContinue + Remove-Item -Path $diffBackup.BackupPath -Force -ErrorAction SilentlyContinue + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } Context "Preparation" { It "Should have prepared" { @@ -41,9 +103,12 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { } } Context "Get last restore history for single database" { - $results = @(Get-DbaDbRestoreHistory -SqlInstance $TestConfig.instance2 -Database $dbname2 -Last) + BeforeAll { + $results = @(Get-DbaDbRestoreHistory -SqlInstance $TestConfig.instance2 -Database $dbname2 -Last) + } + It "Results holds 1 object" { - $results.count | Should -Be 1 + $results.Count | Should -Be 1 } It "Should return the full restore with the correct properties" { $results[0].RestoreType | Should -Be "Database" @@ -52,9 +117,12 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { } } Context "Get last restore history for multiple database" { - $results = @(Get-DbaDbRestoreHistory -SqlInstance $TestConfig.instance2 -Database $dbname1, $dbname2 -Last) + BeforeAll { + $results = @(Get-DbaDbRestoreHistory -SqlInstance $TestConfig.instance2 -Database $dbname1, $dbname2 -Last) + } + It "Results holds 2 objects" { - $results.count | Should -Be 2 + $results.Count | Should -Be 2 } It "Should return the full restore with the correct properties" { $results[0].RestoreType | Should -Be "Database" @@ -66,7 +134,10 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { } } Context "Get complete restore history for multiple database" { - $results = @(Get-DbaDbRestoreHistory -SqlInstance $TestConfig.instance2 -Database $dbname1, $dbname2) + BeforeAll { + $results = @(Get-DbaDbRestoreHistory -SqlInstance $TestConfig.instance2 -Database $dbname1, $dbname2) + } + It "Results holds correct number of objects" { $results.Count | Should -Be 6 } @@ -76,30 +147,68 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { } } Context "return object properties" { - It "has the correct properties" { + BeforeAll { $results = Get-DbaDbRestoreHistory -SqlInstance $TestConfig.instance2 -Database $dbname1, $dbname2 $result = $results[0] - $ExpectedProps = 'ComputerName,InstanceName,SqlInstance,Database,Username,RestoreType,Date,From,To,first_lsn,last_lsn,checkpoint_lsn,database_backup_lsn,backup_finish_date,BackupFinishDate,RowError,RowState,Table,ItemArray,HasErrors'.Split(',') - ($result.PsObject.Properties.Name | Sort-Object) | Should Be ($ExpectedProps | Sort-Object) - $ExpectedPropsDefault = 'ComputerName,InstanceName,SqlInstance,Database,Username,RestoreType,Date,From,To,BackupFinishDate'.Split(',') - ($result.PSStandardMembers.DefaultDisplayPropertySet.ReferencedPropertyNames | Sort-Object) | Should Be ($ExpectedPropsDefault | Sort-Object) + } + + It "has the correct properties" { + $ExpectedProps = @( + "ComputerName", + "InstanceName", + "SqlInstance", + "Database", + "Username", + "RestoreType", + "Date", + "From", + "To", + "first_lsn", + "last_lsn", + "checkpoint_lsn", + "database_backup_lsn", + "backup_finish_date", + "BackupFinishDate", + "RowError", + "RowState", + "Table", + "ItemArray", + "HasErrors" + ) + ($result.PsObject.Properties.Name | Sort-Object) | Should -Be ($ExpectedProps | Sort-Object) + + $ExpectedPropsDefault = @( + "ComputerName", + "InstanceName", + "SqlInstance", + "Database", + "Username", + "RestoreType", + "Date", + "From", + "To", + "BackupFinishDate" + ) + ($result.PSStandardMembers.DefaultDisplayPropertySet.ReferencedPropertyNames | Sort-Object) | Should -Be ($ExpectedPropsDefault | Sort-Object) } } Context "Get restore history by restore type" { It "returns the correct history records for full db restore" { $results = Get-DbaDbRestoreHistory -SqlInstance $TestConfig.instance2 -Database $dbname1, $dbname2 -RestoreType Database - $results.count | Should -Be 4 + $results.Count | Should -Be 4 @($results | Where-Object RestoreType -eq Database).Count | Should -Be 4 } + It "returns the correct history records for diffential restore" { $results = Get-DbaDbRestoreHistory -SqlInstance $TestConfig.instance2 -Database $dbname1 -RestoreType Differential $results.Database | Should -Be $dbname1 $results.RestoreType | Should -Be Differential } + It "returns the correct history records for log restore" { $results = Get-DbaDbRestoreHistory -SqlInstance $TestConfig.instance2 -Database $dbname1 -RestoreType Log $results.Database | Should -Be $dbname1 $results.RestoreType | Should -Be Log } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbRole.Tests.ps1 b/tests/Get-DbaDbRole.Tests.ps1 index 1eee8780ecc..99cf4c2e073 100644 --- a/tests/Get-DbaDbRole.Tests.ps1 +++ b/tests/Get-DbaDbRole.Tests.ps1 @@ -1,75 +1,100 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaDbRole", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tags "UnitTests" { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'ExcludeDatabase', 'Role', 'ExcludeRole', 'ExcludeFixedRole', 'InputObject', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Database", + "ExcludeDatabase", + "Role", + "ExcludeRole", + "ExcludeFixedRole", + "InputObject", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + $instance = Connect-DbaInstance -SqlInstance $TestConfig.instance2 $allDatabases = $instance.Databases + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } Context "Functionality" { - It 'Returns Results' { - $result = Get-DbaDbRole -SqlInstance $instance + It "Returns Results" { + $result = Get-DbaDbRole -SqlInstance $TestConfig.instance2 - $result.Count | Should BeGreaterThan $allDatabases.Count + $result.Count | Should -BeGreaterThan $allDatabases.Count } - It 'Includes Fixed Roles' { - $result = Get-DbaDbRole -SqlInstance $instance + It "Includes Fixed Roles" { + $result = Get-DbaDbRole -SqlInstance $TestConfig.instance2 $result.IsFixedRole | Select-Object -Unique | Should -Contain $true } - It 'Returns all role membership for all databases' { - $result = Get-DbaDbRole -SqlInstance $instance + It "Returns all role membership for all databases" { + $result = Get-DbaDbRole -SqlInstance $TestConfig.instance2 $uniqueDatabases = $result.Database | Select-Object -Unique $uniqueDatabases.Count | Should -BeExactly $allDatabases.Count } - It 'Accepts a list of databases' { - $result = Get-DbaDbRole -SqlInstance $instance -Database 'msdb' + It "Accepts a list of databases" { + $result = Get-DbaDbRole -SqlInstance $TestConfig.instance2 -Database "msdb" - $result.Database | Select-Object -Unique | Should -Be 'msdb' + $result.Database | Select-Object -Unique | Should -Be "msdb" } - It 'Excludes databases' { - $result = Get-DbaDbRole -SqlInstance $instance -ExcludeDatabase 'msdb' + It "Excludes databases" { + $result = Get-DbaDbRole -SqlInstance $TestConfig.instance2 -ExcludeDatabase "msdb" $uniqueDatabases = $result.Database | Select-Object -Unique $uniqueDatabases.Count | Should -BeExactly ($allDatabases.Count - 1) - $uniqueDatabases | Should -Not -Contain 'msdb' + $uniqueDatabases | Should -Not -Contain "msdb" } - It 'Accepts a list of roles' { - $result = Get-DbaDbRole -SqlInstance $instance -Role 'db_owner' + It "Accepts a list of roles" { + $result = Get-DbaDbRole -SqlInstance $TestConfig.instance2 -Role "db_owner" - $result.Name | Select-Object -Unique | Should -Be 'db_owner' + $result.Name | Select-Object -Unique | Should -Be "db_owner" } - It 'Excludes roles' { - $result = Get-DbaDbRole -SqlInstance $instance -ExcludeRole 'db_owner' + It "Excludes roles" { + $result = Get-DbaDbRole -SqlInstance $TestConfig.instance2 -ExcludeRole "db_owner" - $result.Name | Select-Object -Unique | Should -Not -Contain 'db_owner' + $result.Name | Select-Object -Unique | Should -Not -Contain "db_owner" } - It 'Excludes fixed roles' { - $result = Get-DbaDbRole -SqlInstance $instance -ExcludeFixedRole + It "Excludes fixed roles" { + $result = Get-DbaDbRole -SqlInstance $TestConfig.instance2 -ExcludeFixedRole - $results.IsFixedRole | Should Not Contain $true - $result.Name | Select-Object -Unique | Should -Not -Contain 'db_owner' + $result.IsFixedRole | Should -Not -Contain $true + $result.Name | Select-Object -Unique | Should -Not -Contain "db_owner" } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbRoleMember.Tests.ps1 b/tests/Get-DbaDbRoleMember.Tests.ps1 index 8cbd3a8ec81..43d423bae97 100644 --- a/tests/Get-DbaDbRoleMember.Tests.ps1 +++ b/tests/Get-DbaDbRoleMember.Tests.ps1 @@ -1,74 +1,109 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaDbRoleMember", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tags "UnitTests" { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'ExcludeDatabase', 'Role', 'ExcludeRole', 'ExcludeFixedRole', 'IncludeSystemUser', 'InputObject', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Database", + "ExcludeDatabase", + "Role", + "ExcludeRole", + "ExcludeFixedRole", + "IncludeSystemUser", + "InputObject", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true + $instance = Connect-DbaInstance -SqlInstance $TestConfig.instance2 $allDatabases = $instance.Databases + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove("*-Dba*:EnableException") + } + + AfterAll { + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true + + # No specific cleanup needed for this test as we're only reading data + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } Context "Functionality" { - It 'Excludes system users by default' { + It "Excludes system users by default" { $result = Get-DbaDbRoleMember -SqlInstance $instance $result.IsSystemObject | Select-Object -Unique | Should -Not -Contain $true } - It 'Includes system users' { + It "Includes system users" { $result = Get-DbaDbRoleMember -SqlInstance $instance -IncludeSystemUser $result.SmoUser.IsSystemObject | Select-Object -Unique | Should -Contain $true } - It 'Returns all role membership for all databases' { + It "Returns all role membership for all databases" { $result = Get-DbaDbRoleMember -SqlInstance $instance -IncludeSystemUser $uniqueDatabases = $result.Database | Select-Object -Unique $uniqueDatabases.Count | Should -BeExactly $allDatabases.Count } - It 'Accepts a list of databases' { - $result = Get-DbaDbRoleMember -SqlInstance $instance -Database 'msdb' -IncludeSystemUser + It "Accepts a list of databases" { + $result = Get-DbaDbRoleMember -SqlInstance $instance -Database "msdb" -IncludeSystemUser - $result.Database | Select-Object -Unique | Should -Be 'msdb' + $result.Database | Select-Object -Unique | Should -Be "msdb" } - It 'Excludes databases' { - $result = Get-DbaDbRoleMember -SqlInstance $instance -ExcludeDatabase 'msdb' -IncludeSystemUser + It "Excludes databases" { + $result = Get-DbaDbRoleMember -SqlInstance $instance -ExcludeDatabase "msdb" -IncludeSystemUser $uniqueDatabases = $result.Database | Select-Object -Unique $uniqueDatabases.Count | Should -BeExactly ($allDatabases.Count - 1) - $uniqueDatabases | Should -Not -Contain 'msdb' + $uniqueDatabases | Should -Not -Contain "msdb" } - It 'Accepts a list of roles' { - $result = Get-DbaDbRoleMember -SqlInstance $instance -Role 'db_owner' -IncludeSystemUser + It "Accepts a list of roles" { + $result = Get-DbaDbRoleMember -SqlInstance $instance -Role "db_owner" -IncludeSystemUser - $result.Role | Select-Object -Unique | Should -Be 'db_owner' + $result.Role | Select-Object -Unique | Should -Be "db_owner" } - It 'Excludes roles' { - $result = Get-DbaDbRoleMember -SqlInstance $instance -ExcludeRole 'db_owner' -IncludeSystemUser + It "Excludes roles" { + $result = Get-DbaDbRoleMember -SqlInstance $instance -ExcludeRole "db_owner" -IncludeSystemUser - $result.Role | Select-Object -Unique | Should -Not -Contain 'db_owner' + $result.Role | Select-Object -Unique | Should -Not -Contain "db_owner" } - It 'Excludes fixed roles' { + It "Excludes fixed roles" { $result = Get-DbaDbRoleMember -SqlInstance $instance -ExcludeFixedRole -IncludeSystemUser - $result.Role | Select-Object -Unique | Should -Not -Contain 'db_owner' + $result.Role | Select-Object -Unique | Should -Not -Contain "db_owner" } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbSchema.Tests.ps1 b/tests/Get-DbaDbSchema.Tests.ps1 index 3ac00c4526b..db26e3b872e 100644 --- a/tests/Get-DbaDbSchema.Tests.ps1 +++ b/tests/Get-DbaDbSchema.Tests.ps1 @@ -1,20 +1,42 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaDbSchema", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { +Describe $CommandName -Tag UnitTests { Context "Validate parameters" { - [array]$params = ([Management.Automation.CommandMetaData]$ExecutionContext.SessionState.InvokeCommand.GetCommand($CommandName, 'Function')).Parameters.Keys - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'Schema', 'SchemaOwner', 'IncludeSystemDatabases', 'IncludeSystemSchemas', 'InputObject', 'EnableException' - It "Should only contain our specific parameters" { - Compare-Object -ReferenceObject $knownParameters -DifferenceObject $params | Should -BeNullOrEmpty + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Database", + "Schema", + "SchemaOwner", + "IncludeSystemDatabases", + "IncludeSystemSchemas", + "InputObject", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { - +Describe $CommandName -Tag IntegrationTests { BeforeAll { + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true + $random = Get-Random $server1 = Connect-DbaInstance -SqlInstance $TestConfig.instance1 $server2 = Connect-DbaInstance -SqlInstance $TestConfig.instance2 @@ -27,7 +49,7 @@ Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { $userName = "user_$random" $userName2 = "user2_$random" - $password = 'MyV3ry$ecur3P@ssw0rd' + $password = "MyV3ry$ecur3P@ssw0rd" $securePassword = ConvertTo-SecureString $password -AsPlainText -Force $logins = New-DbaLogin -SqlInstance $server1, $server2 -Login $userName, $userName2 -Password $securePassword -Force @@ -38,15 +60,22 @@ Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { $newDbs[0].Schemas.Refresh() $newDbs[1].Query("CREATE SCHEMA $schemaName2 AUTHORIZATION [$userName2]") $newDbs[1].Schemas.Refresh() + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove("*-Dba*:EnableException") } AfterAll { + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true + $null = $newDbs | Remove-DbaDatabase -Confirm:$false $null = $logins | Remove-DbaLogin -Confirm:$false + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } Context "commands work as expected" { - It "get all schemas from all databases including system dbs and schemas" { $schemas = Get-DbaDbSchema -SqlInstance $server1 -IncludeSystemDatabases -IncludeSystemSchemas $schemas.Count | Should -BeGreaterThan 1 @@ -136,4 +165,4 @@ Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { $schemas | Should -BeNullOrEmpty } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbSequence.Tests.ps1 b/tests/Get-DbaDbSequence.Tests.ps1 index 7e3dbaf52b1..1f7c277e23f 100644 --- a/tests/Get-DbaDbSequence.Tests.ps1 +++ b/tests/Get-DbaDbSequence.Tests.ps1 @@ -1,20 +1,41 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaDbSequence", # Static command name for dbatools + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [array]$params = ([Management.Automation.CommandMetaData]$ExecutionContext.SessionState.InvokeCommand.GetCommand($CommandName, 'Function')).Parameters.Keys - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'Sequence', 'Schema', 'InputObject', 'EnableException' - It "Should only contain our specific parameters" { - Compare-Object -ReferenceObject $knownParameters -DifferenceObject $params | Should -BeNullOrEmpty +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Database", + "Sequence", + "Schema", + "InputObject", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + $random = Get-Random $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 $newDbName = "dbatoolsci_newdb_$random" @@ -26,14 +47,21 @@ Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { $sequence3 = New-DbaDbSequence -SqlInstance $server -Database $newDbName -Sequence "Sequence1_$random" -Schema "Schema2_$random" $sequence4 = New-DbaDbSequence -SqlInstance $server -Database $newDbName -Sequence "Sequence2_$random" -Schema "Schema_$random" $sequence5 = New-DbaDbSequence -SqlInstance $server -Database $newDbName2 -Sequence "Sequence1_$random" -Schema "Schema_$random" + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } AfterAll { + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + $null = $newDb, $newDb2 | Remove-DbaDatabase -Confirm:$false + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } Context "commands work as expected" { - It "finds a sequence on an instance" { $sequence = Get-DbaDbSequence -SqlInstance $server $sequence.Count | Should -BeGreaterOrEqual 5 @@ -86,4 +114,4 @@ Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { $sequence.Parent.Name | Should -Be $newDbName } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbServiceBrokerQueue.Tests.ps1 b/tests/Get-DbaDbServiceBrokerQueue.Tests.ps1 index a3a50cec718..3419f9969e8 100644 --- a/tests/Get-DbaDbServiceBrokerQueue.Tests.ps1 +++ b/tests/Get-DbaDbServiceBrokerQueue.Tests.ps1 @@ -1,41 +1,79 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaDbServiceBrokerQueue", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'EnableException', 'Database', 'ExcludeDatabase', 'ExcludeSystemQueue' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Database", + "ExcludeDatabase", + "ExcludeSystemQueue", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { - $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 - $procname = ("dbatools_{0}" -f $(Get-Random)) - $server.Query("CREATE PROCEDURE $procname AS SELECT 1", 'tempdb') - $queuename = ("dbatools_{0}" -f $(Get-Random)) - $server.Query("CREATE QUEUE $queuename WITH STATUS = ON , RETENTION = OFF , ACTIVATION ( STATUS = ON , PROCEDURE_NAME = $procname , MAX_QUEUE_READERS = 1 , EXECUTE AS OWNER ), POISON_MESSAGE_HANDLING (STATUS = ON)", 'tempdb') + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 + $procname = "dbatools_$(Get-Random)" + $server.Query("CREATE PROCEDURE $procname AS SELECT 1", "tempdb") + $queuename = "dbatools_$(Get-Random)" + $server.Query("CREATE QUEUE $queuename WITH STATUS = ON , RETENTION = OFF , ACTIVATION ( STATUS = ON , PROCEDURE_NAME = $procname , MAX_QUEUE_READERS = 1 , EXECUTE AS OWNER ), POISON_MESSAGE_HANDLING (STATUS = ON)", "tempdb") + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } + AfterAll { - $null = $server.Query("DROP QUEUE $queuename", 'tempdb') - $null = $server.Query("DROP PROCEDURE $procname", 'tempdb') + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + $null = $server.Query("DROP QUEUE $queuename", "tempdb") + $null = $server.Query("DROP PROCEDURE $procname", "tempdb") + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } Context "Gets the service broker queue" { - $results = Get-DbaDbServiceBrokerQueue -SqlInstance $TestConfig.instance2 -database tempdb -ExcludeSystemQueue:$true + BeforeAll { + $splatGetQueue = @{ + SqlInstance = $TestConfig.instance2 + Database = "tempdb" + ExcludeSystemQueue = $true + } + $results = Get-DbaDbServiceBrokerQueue @splatGetQueue + } + It "Gets results" { - $results | Should Not Be $Null + $results | Should -Not -BeNullOrEmpty } + It "Should have a name of $queuename" { - $results.name | Should Be "$queuename" + $results.Name | Should -BeExactly $queuename } - It "Should have an schema of dbo" { - $results.schema | Should Be "dbo" + + It "Should have a schema of dbo" { + $results.Schema | Should -BeExactly "dbo" } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbServiceBrokerService.Tests.ps1 b/tests/Get-DbaDbServiceBrokerService.Tests.ps1 index 4d31c5e84e1..1f8f25865d6 100644 --- a/tests/Get-DbaDbServiceBrokerService.Tests.ps1 +++ b/tests/Get-DbaDbServiceBrokerService.Tests.ps1 @@ -1,47 +1,79 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaDbServiceBrokerService", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'EnableException', 'Database', 'ExcludeDatabase', 'ExcludeSystemService' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Database", + "ExcludeDatabase", + "ExcludeSystemService", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 - $procname = ("dbatools_{0}" -f $(Get-Random)) - $server.Query("CREATE PROCEDURE $procname AS SELECT 1", 'tempdb') - $queuename = ("dbatools_{0}" -f $(Get-Random)) - $server.Query("CREATE QUEUE $queuename WITH STATUS = ON , RETENTION = OFF , ACTIVATION ( STATUS = ON , PROCEDURE_NAME = $procname , MAX_QUEUE_READERS = 1 , EXECUTE AS OWNER ), POISON_MESSAGE_HANDLING (STATUS = ON)", 'tempdb') - $servicename = ("dbatools_{0}" -f $(Get-Random)) - $server.Query("CREATE SERVICE $servicename ON QUEUE $queuename ([DEFAULT])", 'tempdb') + $procname = "dbatools_$(Get-Random)" + $server.Query("CREATE PROCEDURE $procname AS SELECT 1", "tempdb") + $queuename = "dbatools_$(Get-Random)" + $server.Query("CREATE QUEUE $queuename WITH STATUS = ON , RETENTION = OFF , ACTIVATION ( STATUS = ON , PROCEDURE_NAME = $procname , MAX_QUEUE_READERS = 1 , EXECUTE AS OWNER ), POISON_MESSAGE_HANDLING (STATUS = ON)", "tempdb") + $servicename = "dbatools_$(Get-Random)" + $server.Query("CREATE SERVICE $servicename ON QUEUE $queuename ([DEFAULT])", "tempdb") } + AfterAll { - $null = $server.Query("DROP SERVICE $servicename", 'tempdb') - $null = $server.Query("DROP QUEUE $queuename", 'tempdb') - $null = $server.Query("DROP PROCEDURE $procname", 'tempdb') + try { + $null = $server.Query("DROP SERVICE $servicename", "tempdb") + $null = $server.Query("DROP QUEUE $queuename", "tempdb") + $null = $server.Query("DROP PROCEDURE $procname", "tempdb") + } catch { + # Suppress errors during cleanup + } } Context "Gets the service broker service" { - $results = Get-DbaDbServiceBrokerService -SqlInstance $TestConfig.instance2 -database tempdb -ExcludeSystemService:$true + BeforeAll { + $splatServiceBroker = @{ + SqlInstance = $TestConfig.instance2 + Database = "tempdb" + ExcludeSystemService = $true + } + $results = Get-DbaDbServiceBrokerService @splatServiceBroker + } + It "Gets results" { - $results | Should Not Be $Null + $results | Should -Not -BeNullOrEmpty } + It "Should have a name of $servicename" { - $results.name | Should Be "$servicename" + $results.Name | Should -BeExactly $servicename } + It "Should have an owner of dbo" { - $results.owner | Should Be "dbo" + $results.Owner | Should -BeExactly "dbo" } + It "Should have a queuename of $queuename" { - $results.QueueName | Should be "$QueueName" + $results.QueueName | Should -BeExactly $queuename } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbSharePoint.Tests.ps1 b/tests/Get-DbaDbSharePoint.Tests.ps1 index 406c87922e7..ad9db93648c 100644 --- a/tests/Get-DbaDbSharePoint.Tests.ps1 +++ b/tests/Get-DbaDbSharePoint.Tests.ps1 @@ -1,29 +1,57 @@ -$commandname = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaDbSharePoint", + $PSDefaultParameterValues = $TestConfig.Defaults +) -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'ConfigDatabase', 'InputObject', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "ConfigDatabase", + "InputObject", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tag "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + $skip = $false - $spdb = 'SharePoint_Admin_7c0c491d0e6f43858f75afa5399d49ab', 'WSS_Logging', 'SecureStoreService_20e1764876504335a6d8dd0b1937f4bf', 'DefaultWebApplicationDB', 'SharePoint_Config_4c524cb90be44c6f906290fe3e34f2e0', 'DefaultPowerPivotServiceApplicationDB-5b638361-c6fc-4ad9-b8ba-d05e63e48ac6', 'SharePoint_Config_4c524cb90be44c6f906290fe3e34f2e0' - Get-DbaProcess -SqlInstance $TestConfig.instance2 -Program 'dbatools PowerShell module - dbatools.io' | Stop-DbaProcess -WarningAction SilentlyContinue + $spdb = @( + "SharePoint_Admin_7c0c491d0e6f43858f75afa5399d49ab", + "WSS_Logging", + "SecureStoreService_20e1764876504335a6d8dd0b1937f4bf", + "DefaultWebApplicationDB", + "SharePoint_Config_4c524cb90be44c6f906290fe3e34f2e0", + "DefaultPowerPivotServiceApplicationDB-5b638361-c6fc-4ad9-b8ba-d05e63e48ac6", + "SharePoint_Config_4c524cb90be44c6f906290fe3e34f2e0" + ) + + Get-DbaProcess -SqlInstance $TestConfig.instance2 -Program "dbatools PowerShell module - dbatools.io" | Stop-DbaProcess -WarningAction SilentlyContinue $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 + foreach ($db in $spdb) { try { $null = $server.Query("Create Database [$db]") - } catch { continue } + } catch { + continue + } } + # Andreas Jordan: We should try to get a backup working again or even better just a sql script to set this up. # This takes a long time but I cannot figure out why every backup of this db is malformed $bacpac = "$($TestConfig.appveyorlabrepo)\bacpac\sharepoint_config.bacpac" @@ -31,7 +59,7 @@ Describe "$commandname Integration Tests" -Tag "IntegrationTests" { $sqlpackage = (Get-Command sqlpackage -ErrorAction Ignore).Source if (-not $sqlpackage) { $libraryPath = Get-DbatoolsLibraryPath - if ($libraryPath -match 'desktop$') { + if ($libraryPath -match "desktop$") { $sqlpackage = Join-DbaPath -Path (Get-DbatoolsLibraryPath) -ChildPath lib, dac, sqlpackage.exe } elseif ($isWindows) { $sqlpackage = Join-DbaPath -Path (Get-DbatoolsLibraryPath) -ChildPath lib, dac, sqlpackage.exe @@ -50,16 +78,29 @@ Describe "$commandname Integration Tests" -Tag "IntegrationTests" { Write-Warning -Message "No bacpac found in path [$bacpac], skipping tests." $skip = $true } + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } + AfterAll { - Remove-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $spdb -Confirm:$false + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + Remove-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $spdb -Confirm:$false -ErrorAction SilentlyContinue + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } + Context "Command gets SharePoint Databases" { - $results = Get-DbaDbSharePoint -SqlInstance $TestConfig.instance2 + BeforeAll { + $results = Get-DbaDbSharePoint -SqlInstance $TestConfig.instance2 + } + foreach ($db in $spdb) { - It -Skip:$skip "returns $db from in the SharePoint database list" { + It "returns $db from in the SharePoint database list" -Skip:$skip { $db | Should -BeIn $results.Name } } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbSnapshot.Tests.ps1 b/tests/Get-DbaDbSnapshot.Tests.ps1 index 6c13aff1501..1e70b114738 100644 --- a/tests/Get-DbaDbSnapshot.Tests.ps1 +++ b/tests/Get-DbaDbSnapshot.Tests.ps1 @@ -1,22 +1,42 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaDbSnapshot", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'ExcludeDatabase', 'Snapshot', 'ExcludeSnapshot', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Database", + "ExcludeDatabase", + "Snapshot", + "ExcludeSnapshot", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } # Targets only instance2 because it's the only one where Snapshots can happen -Describe "$commandname Integration Tests" -Tag "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { Context "Operations on snapshots" { BeforeAll { + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + Get-DbaProcess -SqlInstance $TestConfig.instance2 | Where-Object Program -match dbatools | Stop-DbaProcess -Confirm:$false -WarningAction SilentlyContinue $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 $db1 = "dbatoolsci_GetSnap" @@ -31,40 +51,62 @@ Describe "$commandname Integration Tests" -Tag "IntegrationTests" { $null = New-DbaDbSnapshot -SqlInstance $TestConfig.instance2 -Database $db1 -Name $db1_snap1 -WarningAction SilentlyContinue $null = New-DbaDbSnapshot -SqlInstance $TestConfig.instance2 -Database $db1 -Name $db1_snap2 -WarningAction SilentlyContinue $null = New-DbaDbSnapshot -SqlInstance $TestConfig.instance2 -Database $db2 -Name $db2_snap1 -WarningAction SilentlyContinue + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } + AfterAll { + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + Remove-DbaDbSnapshot -SqlInstance $TestConfig.instance2 -Database $db1, $db2 -ErrorAction SilentlyContinue -Confirm:$false Remove-DbaDatabase -Confirm:$false -SqlInstance $TestConfig.instance2 -Database $db1, $db2 -ErrorAction SilentlyContinue + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } It "Gets all snapshots by default" { $results = Get-DbaDbSnapshot -SqlInstance $TestConfig.instance2 - ($results | Where-Object Name -Like 'dbatoolsci_GetSnap*').Count | Should Be 3 + ($results | Where-Object Name -Like "dbatoolsci_GetSnap*").Count | Should -BeExactly 3 } + It "Honors the Database parameter, returning only snapshots of that database" { $results = Get-DbaDbSnapshot -SqlInstance $TestConfig.instance2 -Database $db1 - $results.Count | Should Be 2 + $results.Count | Should -BeExactly 2 $result = Get-DbaDbSnapshot -SqlInstance $TestConfig.instance2 -Database $db2 - $result.SnapshotOf | Should Be $db2 + $result.SnapshotOf | Should -Be $db2 } + It "Honors the ExcludeDatabase parameter, returning relevant snapshots" { $alldbs = (Get-DbaDatabase -SqlInstance $TestConfig.instance2 | Where-Object IsDatabaseSnapShot -eq $false | Where-Object Name -notin @($db1, $db2)).Name $results = Get-DbaDbSnapshot -SqlInstance $TestConfig.instance2 -ExcludeDatabase $alldbs - $results.Count | Should Be 3 + $results.Count | Should -BeExactly 3 } + It "Honors the Snapshot parameter" { $result = Get-DbaDbSnapshot -SqlInstance $TestConfig.instance2 -Snapshot $db1_snap1 - $result.Name | Should Be $db1_snap1 - $result.SnapshotOf | Should Be $db1 + $result.Name | Should -Be $db1_snap1 + $result.SnapshotOf | Should -Be $db1 } + It "Honors the ExcludeSnapshot parameter" { $result = Get-DbaDbSnapshot -SqlInstance $TestConfig.instance2 -ExcludeSnapshot $db1_snap1 -Database $db1 - $result.Name | Should Be $db1_snap2 + $result.Name | Should -Be $db1_snap2 } + It "has the correct default properties" { $result = Get-DbaDbSnapshot -SqlInstance $TestConfig.instance2 -Database $db2 - $ExpectedPropsDefault = 'ComputerName', 'CreateDate', 'InstanceName', 'Name', 'SnapshotOf', 'SqlInstance', 'DiskUsage' - ($result.PSStandardMembers.DefaultDisplayPropertySet.ReferencedPropertyNames | Sort-Object) | Should Be ($ExpectedPropsDefault | Sort-Object) + $ExpectedPropsDefault = @( + "ComputerName", + "CreateDate", + "InstanceName", + "Name", + "SnapshotOf", + "SqlInstance", + "DiskUsage" + ) + ($result.PSStandardMembers.DefaultDisplayPropertySet.ReferencedPropertyNames | Sort-Object) | Should -Be ($ExpectedPropsDefault | Sort-Object) } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbSpace.Tests.ps1 b/tests/Get-DbaDbSpace.Tests.ps1 index d87417e44e7..9dd0ecf2fe2 100644 --- a/tests/Get-DbaDbSpace.Tests.ps1 +++ b/tests/Get-DbaDbSpace.Tests.ps1 @@ -1,63 +1,106 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaDbSpace", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'ExcludeDatabase', 'IncludeSystemDBs', 'InputObject', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Database", + "ExcludeDatabase", + "IncludeSystemDBs", + "InputObject", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { - $dbname = "dbatoolsci_test_$(get-random)" + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # Create test database for space testing + $dbname = "dbatoolsci_test_$(Get-Random)" $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 $null = $server.Query("Create Database [$dbname]") + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } + AfterAll { - Remove-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname -Confirm:$false + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # Cleanup test database + $null = Remove-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } + #Skipping these tests as internals of Get-DbaDbSpace seems to be unreliable in CI Context "Gets DbSpace" { - $results = Get-DbaDbSpace -SqlInstance $TestConfig.instance2 | Where-Object { $_.Database -eq "$dbname" } + BeforeAll { + $results = Get-DbaDbSpace -SqlInstance $TestConfig.instance2 | Where-Object Database -eq $dbname + } + It "Gets results" { $results | Should -Not -BeNullOrEmpty } - foreach ($row in $results) { - It "Should retreive space for $dbname" { - $row.Database | Should -Be $dbname - $row.UsedSpace | Should -Not -BeNullOrEmpty - } - It "Should have a physical path for $dbname" { - $row.physicalname | Should -Not -BeNullOrEmpty - } + + It "Should retrieve space for test database" { + $results[0].Database | Should -Be $dbname + $results[0].UsedSpace | Should -Not -BeNullOrEmpty + } + + It "Should have a physical path for test database" { + $results[0].physicalname | Should -Not -BeNullOrEmpty } } + #Skipping these tests as internals of Get-DbaDbSpace seems to be unreliable in CI Context "Gets DbSpace when using -Database" { - $results = Get-DbaDbSpace -SqlInstance $TestConfig.instance2 -Database $dbname + BeforeAll { + $results = Get-DbaDbSpace -SqlInstance $TestConfig.instance2 -Database $dbname + } + It "Gets results" { - $results | Should Not Be $null + $results | Should -Not -BeNullOrEmpty + } + + It "Should retrieve space for test database" { + $results[0].Database | Should -Be $dbname + $results[0].UsedSpace | Should -Not -BeNullOrEmpty } - Foreach ($row in $results) { - It "Should retreive space for $dbname" { - $row.Database | Should -Be $dbname - $row.UsedSpace | Should -Not -BeNullOrEmpty - } - It "Should have a physical path for $dbname" { - $row.physicalname | Should -Not -BeNullOrEmpty - } + + It "Should have a physical path for test database" { + $results[0].physicalname | Should -Not -BeNullOrEmpty } } + Context "Gets no DbSpace for specific database when using -ExcludeDatabase" { - $results = Get-DbaDbSpace -SqlInstance $TestConfig.instance2 -ExcludeDatabase $dbname + BeforeAll { + $results = Get-DbaDbSpace -SqlInstance $TestConfig.instance2 -ExcludeDatabase $dbname + } + It "Gets no results" { $results.database | Should -Not -Contain $dbname } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbState.Tests.ps1 b/tests/Get-DbaDbState.Tests.ps1 index 77456ed57ac..6e57dfab9c1 100644 --- a/tests/Get-DbaDbState.Tests.ps1 +++ b/tests/Get-DbaDbState.Tests.ps1 @@ -1,21 +1,39 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaDbState", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'ExcludeDatabase', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Database", + "ExcludeDatabase", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { Context "Reading db statuses" { BeforeAll { + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 $db1 = "dbatoolsci_dbstate_online" $db2 = "dbatoolsci_dbstate_offline" @@ -25,7 +43,14 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { $db6 = "dbatoolsci_dbstate_multi" $db7 = "dbatoolsci_dbstate_rw" $db8 = "dbatoolsci_dbstate_ro" - Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $db1, $db2, $db3, $db4, $db5, $db6, $db7, $db8 | Remove-DbaDatabase -Confirm:$false + + $splatRemoveDb = @{ + SqlInstance = $TestConfig.instance2 + Database = $db1, $db2, $db3, $db4, $db5, $db6, $db7, $db8 + Confirm = $false + } + Get-DbaDatabase @splatRemoveDb | Remove-DbaDatabase -Confirm $false + $server.Query("CREATE DATABASE $db1") $server.Query("CREATE DATABASE $db2; ALTER DATABASE $db2 SET OFFLINE WITH ROLLBACK IMMEDIATE") $server.Query("CREATE DATABASE $db3; ALTER DATABASE $db3 SET EMERGENCY WITH ROLLBACK IMMEDIATE") @@ -34,89 +59,136 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { $server.Query("CREATE DATABASE $db6; ALTER DATABASE $db6 SET MULTI_USER WITH ROLLBACK IMMEDIATE") $server.Query("CREATE DATABASE $db7; ALTER DATABASE $db7 SET READ_WRITE WITH ROLLBACK IMMEDIATE") $server.Query("CREATE DATABASE $db8; ALTER DATABASE $db8 SET READ_ONLY WITH ROLLBACK IMMEDIATE") + $setupright = $true $needed_ = $server.Query("select name from sys.databases") $needed = $needed_ | Where-Object name -in $db1, $db2, $db3, $db4, $db5, $db6, $db7, $db8 if ($needed.Count -ne 8) { $setupright = $false - It "has failed setup" { - Set-TestInconclusive -Message "Setup failed" - } } + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } + AfterAll { - $null = Set-DbaDbState -Sqlinstance $TestConfig.instance2 -Database $db2, $db3, $db4, $db5, $db7 -Online -ReadWrite -MultiUser -Force - Remove-DbaDatabase -Confirm:$false -SqlInstance $TestConfig.instance2 -Database $db1, $db2, $db3, $db4, $db5, $db6, $db7, $db8 - } - if ($setupright) { - # just to have a correct report on how much time BeforeAll takes - It "Waits for BeforeAll to finish" { - $true | Should Be $true - } - It "Honors the Database parameter" { - $result = Get-DbaDbState -SqlInstance $TestConfig.instance2 -Database $db2 - $result.DatabaseName | Should be $db2 - $results = Get-DbaDbState -SqlInstance $TestConfig.instance2 -Database $db1, $db2 - $results.Count | Should be 2 - } - It "Honors the ExcludeDatabase parameter" { - $alldbs_ = $server.Query("select name from sys.databases") - $alldbs = ($alldbs_ | Where-Object Name -notin @($db1, $db2, $db3, $db4, $db5, $db6, $db7, $db8)).name - $results = Get-DbaDbState -SqlInstance $TestConfig.instance2 -ExcludeDatabase $alldbs - $comparison = Compare-Object -ReferenceObject ($results.DatabaseName) -DifferenceObject (@($db1, $db2, $db3, $db4, $db5, $db6, $db7, $db8)) - $comparison.Count | Should Be 0 - } - It "Identifies online database" { - $result = Get-DbaDbState -SqlInstance $TestConfig.instance2 -Database $db1 - $result.DatabaseName | Should Be $db1 - $result.Status | Should Be "ONLINE" - } - It "Identifies offline database" { - $result = Get-DbaDbState -SqlInstance $TestConfig.instance2 -Database $db2 - $result.DatabaseName | Should Be $db2 - $result.Status | Should Be "OFFLINE" - } - It "Identifies emergency database" { - $result = Get-DbaDbState -SqlInstance $TestConfig.instance2 -Database $db3 - $result.DatabaseName | Should Be $db3 - $result.Status | Should Be "EMERGENCY" - } - It "Identifies single_user database" { - $result = Get-DbaDbState -SqlInstance $TestConfig.instance2 -Database $db4 - $result.DatabaseName | Should Be $db4 - $result.Access | Should Be "SINGLE_USER" - } - It "Identifies restricted_user database" { - $result = Get-DbaDbState -SqlInstance $TestConfig.instance2 -Database $db5 - $result.DatabaseName | Should Be $db5 - $result.Access | Should Be "RESTRICTED_USER" - } - It "Identifies multi_user database" { - $result = Get-DbaDbState -SqlInstance $TestConfig.instance2 -Database $db6 - $result.DatabaseName | Should Be $db6 - $result.Access | Should Be "MULTI_USER" - } - It "Identifies read_write database" { - $result = Get-DbaDbState -SqlInstance $TestConfig.instance2 -Database $db7 - $result.DatabaseName | Should Be $db7 - $result.RW | Should Be "READ_WRITE" + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + $splatSetState = @{ + SqlInstance = $TestConfig.instance2 + Database = $db2, $db3, $db4, $db5, $db7 + Online = $true + ReadWrite = $true + MultiUser = $true + Force = $true } - It "Identifies read_only database" { - $result = Get-DbaDbState -SqlInstance $TestConfig.instance2 -Database $db8 - $result.DatabaseName | Should Be $db8 - $result.RW | Should Be "READ_ONLY" + $null = Set-DbaDbState @splatSetState + + $splatRemoveDbCleanup = @{ + SqlInstance = $TestConfig.instance2 + Database = $db1, $db2, $db3, $db4, $db5, $db6, $db7, $db8 + Confirm = $false } + Remove-DbaDatabase @splatRemoveDbCleanup -ErrorAction SilentlyContinue + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. + } + + It "Waits for BeforeAll to finish" -Skip:(-not $setupright) { + $true | Should -BeTrue + } + It "Honors the Database parameter" -Skip:(-not $setupright) { + $result = Get-DbaDbState -SqlInstance $TestConfig.instance2 -Database $db2 + $result.DatabaseName | Should -Be $db2 + $results = Get-DbaDbState -SqlInstance $TestConfig.instance2 -Database $db1, $db2 + $results.Count | Should -Be 2 + } + + It "Honors the ExcludeDatabase parameter" -Skip:(-not $setupright) { + $alldbs_ = $server.Query("select name from sys.databases") + $alldbs = ($alldbs_ | Where-Object Name -notin @($db1, $db2, $db3, $db4, $db5, $db6, $db7, $db8)).name + $results = Get-DbaDbState -SqlInstance $TestConfig.instance2 -ExcludeDatabase $alldbs + $comparison = Compare-Object -ReferenceObject ($results.DatabaseName) -DifferenceObject (@($db1, $db2, $db3, $db4, $db5, $db6, $db7, $db8)) + $comparison.Count | Should -Be 0 + } + + It "Identifies online database" -Skip:(-not $setupright) { $result = Get-DbaDbState -SqlInstance $TestConfig.instance2 -Database $db1 - It "Has the correct properties" { - $ExpectedProps = 'SqlInstance,InstanceName,ComputerName,DatabaseName,RW,Status,Access,Database'.Split(',') - ($result.PsObject.Properties.Name | Sort-Object) | Should Be ($ExpectedProps | Sort-Object) - } + $result.DatabaseName | Should -Be $db1 + $result.Status | Should -Be "ONLINE" + } - It "Has the correct default properties" { - $ExpectedPropsDefault = 'SqlInstance,InstanceName,ComputerName,DatabaseName,RW,Status,Access'.Split(',') - ($result.PSStandardMembers.DefaultDisplayPropertySet.ReferencedPropertyNames | Sort-Object) | Should Be ($ExpectedPropsDefault | Sort-Object) - } + It "Identifies offline database" -Skip:(-not $setupright) { + $result = Get-DbaDbState -SqlInstance $TestConfig.instance2 -Database $db2 + $result.DatabaseName | Should -Be $db2 + $result.Status | Should -Be "OFFLINE" + } + + It "Identifies emergency database" -Skip:(-not $setupright) { + $result = Get-DbaDbState -SqlInstance $TestConfig.instance2 -Database $db3 + $result.DatabaseName | Should -Be $db3 + $result.Status | Should -Be "EMERGENCY" + } + + It "Identifies single_user database" -Skip:(-not $setupright) { + $result = Get-DbaDbState -SqlInstance $TestConfig.instance2 -Database $db4 + $result.DatabaseName | Should -Be $db4 + $result.Access | Should -Be "SINGLE_USER" + } + + It "Identifies restricted_user database" -Skip:(-not $setupright) { + $result = Get-DbaDbState -SqlInstance $TestConfig.instance2 -Database $db5 + $result.DatabaseName | Should -Be $db5 + $result.Access | Should -Be "RESTRICTED_USER" + } + + It "Identifies multi_user database" -Skip:(-not $setupright) { + $result = Get-DbaDbState -SqlInstance $TestConfig.instance2 -Database $db6 + $result.DatabaseName | Should -Be $db6 + $result.Access | Should -Be "MULTI_USER" + } + + It "Identifies read_write database" -Skip:(-not $setupright) { + $result = Get-DbaDbState -SqlInstance $TestConfig.instance2 -Database $db7 + $result.DatabaseName | Should -Be $db7 + $result.RW | Should -Be "READ_WRITE" + } + + It "Identifies read_only database" -Skip:(-not $setupright) { + $result = Get-DbaDbState -SqlInstance $TestConfig.instance2 -Database $db8 + $result.DatabaseName | Should -Be $db8 + $result.RW | Should -Be "READ_ONLY" + } + + It "Has the correct properties" -Skip:(-not $setupright) { + $result = Get-DbaDbState -SqlInstance $TestConfig.instance2 -Database $db1 + $ExpectedProps = @( + "SqlInstance", + "InstanceName", + "ComputerName", + "DatabaseName", + "RW", + "Status", + "Access", + "Database" + ) + ($result.PsObject.Properties.Name | Sort-Object) | Should -Be ($ExpectedProps | Sort-Object) + } + + It "Has the correct default properties" -Skip:(-not $setupright) { + $result = Get-DbaDbState -SqlInstance $TestConfig.instance2 -Database $db1 + $ExpectedPropsDefault = @( + "SqlInstance", + "InstanceName", + "ComputerName", + "DatabaseName", + "RW", + "Status", + "Access" + ) + ($result.PSStandardMembers.DefaultDisplayPropertySet.ReferencedPropertyNames | Sort-Object) | Should -Be ($ExpectedPropsDefault | Sort-Object) } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbStoredProcedure.Tests.ps1 b/tests/Get-DbaDbStoredProcedure.Tests.ps1 index 925ae2a6c92..9f0eb6c6659 100644 --- a/tests/Get-DbaDbStoredProcedure.Tests.ps1 +++ b/tests/Get-DbaDbStoredProcedure.Tests.ps1 @@ -1,26 +1,48 @@ +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaDbStoredProcedure", + $PSDefaultParameterValues = $TestConfig.Defaults +) + <# The below statement stays in for every test you build. #> -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig <# Unit test is required for any command added #> -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('WhatIf', 'Confirm') } - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'ExcludeDatabase', 'ExcludeSystemSp', 'Name', 'Schema', 'InputObject', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Database", + "ExcludeDatabase", + "ExcludeSystemSp", + "Name", + "Schema", + "InputObject", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } # Get-DbaNoun -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 $random = Get-Random $db1Name = "dbatoolsci_$random" @@ -32,33 +54,48 @@ Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { $procName2 = "proc2" $db1.Query("CREATE SCHEMA $schemaName") $db1.Query("CREATE PROCEDURE $schemaName.$procName2 AS SELECT 1") + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } + AfterAll { + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + $db1 | Remove-DbaDatabase -Confirm:$false + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } Context "Command actually works" { - $results = Get-DbaDbStoredProcedure -SqlInstance $TestConfig.instance2 -Database $db1Name + BeforeAll { + $results = Get-DbaDbStoredProcedure -SqlInstance $TestConfig.instance2 -Database $db1Name + } + It "Should have standard properties" { - $ExpectedProps = 'ComputerName,InstanceName,SqlInstance'.Split(',') - ($results[0].PsObject.Properties.Name | Where-Object { $_ -in $ExpectedProps } | Sort-Object) | Should Be ($ExpectedProps | Sort-Object) + $ExpectedProps = @("ComputerName", "InstanceName", "SqlInstance") + ($results[0].PsObject.Properties.Name | Where-Object { $PSItem -in $ExpectedProps } | Sort-Object) | Should -Be ($ExpectedProps | Sort-Object) } + It "Should get test procedure: $procName" { - ($results | Where-Object Name -eq $procName).Name | Should -Be $true + ($results | Where-Object Name -eq $procName).Name | Should -Not -BeNullOrEmpty } + It "Should include system procedures" { - ($results | Where-Object Name -eq 'sp_columns') | Should -Be $true + ($results | Where-Object Name -eq "sp_columns") | Should -Not -BeNullOrEmpty } } Context "Exclusions work correctly" { It "Should contain no procs from master database" { $results = Get-DbaDbStoredProcedure -SqlInstance $TestConfig.instance2 -ExcludeDatabase master - $results.Database | Should -Not -Contain 'master' + $results.Database | Should -Not -Contain "master" } + It "Should exclude system procedures" { $results = Get-DbaDbStoredProcedure -SqlInstance $TestConfig.instance2 -Database $db1Name -ExcludeSystemSp - $results | Where-Object Name -eq 'sp_helpdb' | Should -BeNullOrEmpty + $results | Where-Object Name -eq "sp_helpdb" | Should -BeNullOrEmpty } } @@ -67,6 +104,7 @@ Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { $results = $TestConfig.instance2 | Get-DbaDbStoredProcedure -Database $db1Name ($results | Where-Object Name -eq $procName).Name | Should -Not -BeNullOrEmpty } + It "Should allow piping from Get-DbaDatabase" { $results = Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $db1Name | Get-DbaDbStoredProcedure ($results | Where-Object Name -eq $procName).Name | Should -Not -BeNullOrEmpty @@ -79,26 +117,30 @@ Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { $results.Name | Should -Be $procName $results.DatabaseId | Should -Be $db1.Id } + It "Search by 2 part name" { $results = $TestConfig.instance2 | Get-DbaDbStoredProcedure -Database $db1Name -Name "$schemaName.$procName2" $results.Name | Should -Be $procName2 $results.Schema | Should -Be $schemaName } + It "Search by 3 part name and omit the -Database param" { $results = $TestConfig.instance2 | Get-DbaDbStoredProcedure -Name "$db1Name.$schemaName.$procName2" $results.Name | Should -Be $procName2 $results.Schema | Should -Be $schemaName $results.Database | Should -Be $db1Name } + It "Search by name and schema params" { $results = $TestConfig.instance2 | Get-DbaDbStoredProcedure -Database $db1Name -Name $procName2 -Schema $schemaName $results.Name | Should -Be $procName2 $results.Schema | Should -Be $schemaName } + It "Search by schema name" { $results = $TestConfig.instance2 | Get-DbaDbStoredProcedure -Database $db1Name -Schema $schemaName $results.Name | Should -Be $procName2 $results.Schema | Should -Be $schemaName } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbSynonym.Tests.ps1 b/tests/Get-DbaDbSynonym.Tests.ps1 index ce7493e94d7..9b6a99b4802 100644 --- a/tests/Get-DbaDbSynonym.Tests.ps1 +++ b/tests/Get-DbaDbSynonym.Tests.ps1 @@ -1,42 +1,76 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaDbSynonym", # Static command name for dbatools + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tags "UnitTests" { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'ExcludeDatabase', 'Schema', 'ExcludeSchema', 'Synonym', 'ExcludeSynonym', 'InputObject', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Database", + "ExcludeDatabase", + "Schema", + "ExcludeSchema", + "Synonym", + "ExcludeSynonym", + "InputObject", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # Set up test databases and synonyms $dbname = "dbatoolsscidb_$(Get-Random)" $dbname2 = "dbatoolsscidb2_$(Get-Random)" + $null = New-DbaDatabase -SqlInstance $TestConfig.instance2 -Name $dbname $null = New-DbaDatabase -SqlInstance $TestConfig.instance2 -Name $dbname2 $null = New-DbaDbSchema -SqlInstance $TestConfig.instance2 -Database $dbname2 -Schema sch2 $null = New-DbaDbSynonym -SqlInstance $TestConfig.instance2 -Database $dbname -Synonym syn1 -BaseObject obj1 $null = New-DbaDbSynonym -SqlInstance $TestConfig.instance2 -Database $dbname2 -Synonym syn2 -BaseObject obj2 $null = New-DbaDbSynonym -SqlInstance $TestConfig.instance2 -Database $dbname2 -Schema sch2 -Synonym syn3 -BaseObject obj2 + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } AfterAll { - $null = Remove-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname, $dbname2 -Confirm:$false - $null = Remove-DbaDbSynonym -SqlInstance $TestConfig.instance2 -Confirm:$false + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # Cleanup all created objects + $null = Remove-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname, $dbname2 -Confirm:$false -ErrorAction SilentlyContinue + $null = Remove-DbaDbSynonym -SqlInstance $TestConfig.instance2 -Confirm:$false -ErrorAction SilentlyContinue + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } Context "Functionality" { - It 'Returns Results' { + It "Returns Results" { $result1 = Get-DbaDbSynonym -SqlInstance $TestConfig.instance2 $result1.Count | Should -BeGreaterThan 0 } - It 'Returns all synonyms for all databases' { + It "Returns all synonyms for all databases" { $result2 = Get-DbaDbSynonym -SqlInstance $TestConfig.instance2 $uniqueDatabases = $result2.Database | Select-Object -Unique @@ -44,54 +78,54 @@ Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { $result2.Count | Should -BeGreaterThan 2 } - It 'Accepts a list of databases' { + It "Accepts a list of databases" { $result3 = Get-DbaDbSynonym -SqlInstance $TestConfig.instance2 -Database $dbname, $dbname2 $result3.Database | Select-Object -Unique | Should -Be $dbname, $dbname2 } - It 'Excludes databases' { + It "Excludes databases" { $result4 = Get-DbaDbSynonym -SqlInstance $TestConfig.instance2 -ExcludeDatabase $dbname2 $uniqueDatabases = $result4.Database | Select-Object -Unique $uniqueDatabases | Should -Not -Contain $dbname2 } - It 'Accepts a list of synonyms' { - $result5 = Get-DbaDbSynonym -SqlInstance $TestConfig.instance2 -Synonym 'syn1', 'syn2' + It "Accepts a list of synonyms" { + $result5 = Get-DbaDbSynonym -SqlInstance $TestConfig.instance2 -Synonym "syn1", "syn2" - $result5.Name | Select-Object -Unique | Should -Be 'syn1', 'syn2' + $result5.Name | Select-Object -Unique | Should -Be "syn1", "syn2" } - It 'Excludes synonyms' { - $result6 = Get-DbaDbSynonym -SqlInstance $TestConfig.instance2 -ExcludeSynonym 'syn2' + It "Excludes synonyms" { + $result6 = Get-DbaDbSynonym -SqlInstance $TestConfig.instance2 -ExcludeSynonym "syn2" - $result6.Name | Select-Object -Unique | Should -Not -Contain 'syn2' + $result6.Name | Select-Object -Unique | Should -Not -Contain "syn2" } - It 'Finds synonyms for specified schema only' { - $result7 = Get-DbaDbSynonym -SqlInstance $TestConfig.instance2 -Schema 'sch2' + It "Finds synonyms for specified schema only" { + $result7 = Get-DbaDbSynonym -SqlInstance $TestConfig.instance2 -Schema "sch2" $result7.Count | Should -Be 1 } - It 'Accepts a list of schemas' { - $result8 = Get-DbaDbSynonym -SqlInstance $TestConfig.instance2 -Schema 'dbo','sch2' + It "Accepts a list of schemas" { + $result8 = Get-DbaDbSynonym -SqlInstance $TestConfig.instance2 -Schema "dbo", "sch2" - $result8.Schema | Select-Object -Unique | Should -Be 'dbo','sch2' + $result8.Schema | Select-Object -Unique | Should -Be "dbo", "sch2" } - It 'Excludes schemas' { - $result9 = Get-DbaDbSynonym -SqlInstance $TestConfig.instance2 -ExcludeSchema 'dbo' + It "Excludes schemas" { + $result9 = Get-DbaDbSynonym -SqlInstance $TestConfig.instance2 -ExcludeSchema "dbo" - $result9.Schema | Select-Object -Unique | Should -Not -Contain 'dbo' + $result9.Schema | Select-Object -Unique | Should -Not -Contain "dbo" } - It 'Input is provided' { + It "Input is provided" { $result10 = Get-DbaDbSynonym -WarningAction SilentlyContinue -WarningVariable warn > $null - $warn | Should -Match 'You must pipe in a database or specify a SqlInstance' + $warn | Should -Match "You must pipe in a database or specify a SqlInstance" } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbTable.Tests.ps1 b/tests/Get-DbaDbTable.Tests.ps1 index 95b2cfe2c3d..57e0a1b0d33 100644 --- a/tests/Get-DbaDbTable.Tests.ps1 +++ b/tests/Get-DbaDbTable.Tests.ps1 @@ -1,40 +1,75 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaDbTable", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'ExcludeDatabase', 'IncludeSystemDBs', 'Table', 'EnableException', 'InputObject', 'Schema' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Database", + "ExcludeDatabase", + "IncludeSystemDBs", + "Table", + "Schema", + "InputObject", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + $dbname = "dbatoolsscidb_$(Get-Random)" - $null = New-DbaDatabase -SqlInstance $TestConfig.instance1 -Name $dbname -Owner sa $tablename = "dbatoolssci_$(Get-Random)" + + $null = New-DbaDatabase -SqlInstance $TestConfig.instance1 -Name $dbname -Owner sa $null = Invoke-DbaQuery -SqlInstance $TestConfig.instance1 -Database $dbname -Query "Create table $tablename (col1 int)" + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } + AfterAll { - $null = Invoke-DbaQuery -SqlInstance $TestConfig.instance1 -Database $dbname -Query "drop table $tablename" - $null = Remove-DbaDatabase -SqlInstance $TestConfig.instance1 -Database $dbname -Confirm:$false + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + $null = Invoke-DbaQuery -SqlInstance $TestConfig.instance1 -Database $dbname -Query "drop table $tablename" -ErrorAction SilentlyContinue + $null = Remove-DbaDatabase -SqlInstance $TestConfig.instance1 -Database $dbname -Confirm:$false -ErrorAction SilentlyContinue + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } + Context "Should get the table" { It "Gets the table" { - (Get-DbaDbTable -SqlInstance $TestConfig.instance1).Name | Should Contain $tablename + (Get-DbaDbTable -SqlInstance $TestConfig.instance1).Name | Should -Contain $tablename } + It "Gets the table when you specify the database" { - (Get-DbaDbTable -SqlInstance $TestConfig.instance1 -Database $dbname).Name | Should Contain $tablename + (Get-DbaDbTable -SqlInstance $TestConfig.instance1 -Database $dbname).Name | Should -Contain $tablename } } + Context "Should not get the table if database is excluded" { It "Doesn't find the table" { - (Get-DbaDbTable -SqlInstance $TestConfig.instance1 -ExcludeDatabase $dbname).Name | Should Not Contain $tablename + (Get-DbaDbTable -SqlInstance $TestConfig.instance1 -ExcludeDatabase $dbname).Name | Should -Not -Contain $tablename } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbTrigger.Tests.ps1 b/tests/Get-DbaDbTrigger.Tests.ps1 index 31b9af58e0e..f8396dbe9e3 100644 --- a/tests/Get-DbaDbTrigger.Tests.ps1 +++ b/tests/Get-DbaDbTrigger.Tests.ps1 @@ -1,20 +1,39 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaDbTrigger", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'ExcludeDatabase', 'InputObject', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Database", + "ExcludeDatabase", + "InputObject", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + #trigger adapted from https://docs.microsoft.com/en-us/sql/t-sql/statements/create-trigger-transact-sql?view=sql-server-2017 $trigger = @" CREATE TRIGGER dbatoolsci_safety @@ -28,41 +47,65 @@ CREATE TRIGGER dbatoolsci_safety "@ $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 $server.Query("$trigger") + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } + AfterAll { + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 $trigger = "DROP TRIGGER dbatoolsci_safety ON DATABASE;" $server.Query("$trigger") + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } Context "Gets Database Trigger" { - $results = Get-DbaDbTrigger -SqlInstance $TestConfig.instance2 | Where-Object {$_.name -eq "dbatoolsci_safety"} + BeforeAll { + $results = Get-DbaDbTrigger -SqlInstance $TestConfig.instance2 | Where-Object Name -eq "dbatoolsci_safety" + } + It "Gets results" { - $results | Should Not Be $null + $results | Should -Not -BeNullOrEmpty } + It "Should be enabled" { - $results.isenabled | Should Be $true + $results.IsEnabled | Should -BeTrue } + It "Should have text of Trigger" { - $results.text | Should BeLike '*FOR DROP_SYNONYM*' + $results.Text | Should -BeLike "*FOR DROP_SYNONYM*" } } + Context "Gets Database Trigger when using -Database" { - $results = Get-DbaDbTrigger -SqlInstance $TestConfig.instance2 -Database Master + BeforeAll { + $results = Get-DbaDbTrigger -SqlInstance $TestConfig.instance2 -Database Master + } + It "Gets results" { - $results | Should Not Be $null + $results | Should -Not -BeNullOrEmpty } + It "Should be enabled" { - $results.isenabled | Should Be $true + $results.IsEnabled | Should -BeTrue } + It "Should have text of Trigger" { - $results.text | Should BeLike '*FOR DROP_SYNONYM*' + $results.Text | Should -BeLike "*FOR DROP_SYNONYM*" } } + Context "Gets no Database Trigger when using -ExcludeDatabase" { - $results = Get-DbaDbTrigger -SqlInstance $TestConfig.instance2 -ExcludeDatabase Master + BeforeAll { + $results = Get-DbaDbTrigger -SqlInstance $TestConfig.instance2 -ExcludeDatabase Master + } + It "Gets no results" { - $results | Should Be $null + $results | Should -BeNullOrEmpty } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbUdf.Tests.ps1 b/tests/Get-DbaDbUdf.Tests.ps1 index b5c739dc963..185eebea781 100644 --- a/tests/Get-DbaDbUdf.Tests.ps1 +++ b/tests/Get-DbaDbUdf.Tests.ps1 @@ -1,20 +1,43 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaDbUdf", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'ExcludeDatabase', 'ExcludeSystemUdf', 'Schema', 'ExcludeSchema', 'Name', 'ExcludeName', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Database", + "ExcludeDatabase", + "ExcludeSystemUdf", + "Schema", + "ExcludeSchema", + "Name", + "ExcludeName", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + #Test Function adapted from examples at: #https://docs.microsoft.com/en-us/sql/t-sql/statements/create-function-transact-sql?view=sql-server-2017#examples $CreateTestUDFunction = @" @@ -38,15 +61,26 @@ BEGIN END; "@ Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Query $CreateTestUDFunction -Database master + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } + AfterAll { + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + $DropTestUDFunction = "DROP FUNCTION dbo.dbatoolssci_ISOweek;" - Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Query $DropTestUDFunction -Database master + Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Query $DropTestUDFunction -Database master -ErrorAction SilentlyContinue + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } Context "User Functions are correctly located" { - $results1 = Get-DbaDbUdf -SqlInstance $TestConfig.instance2 -Database master -Name dbatoolssci_ISOweek | Select-Object * - $results2 = Get-DbaDbUdf -SqlInstance $TestConfig.instance2 + BeforeAll { + $results1 = Get-DbaDbUdf -SqlInstance $TestConfig.instance2 -Database master -Name dbatoolssci_ISOweek | Select-Object * + $results2 = Get-DbaDbUdf -SqlInstance $TestConfig.instance2 + } It "Should execute and return results" { $results2 | Should -Not -Be $null @@ -57,12 +91,12 @@ END; } It "Should have matching name dbo.dbatoolssci_ISOweek" { - $results1.name | Should -Be 'dbatoolssci_ISOweek' - $results1.schema | Should -Be 'dbo' + $results1.Name | Should -Be "dbatoolssci_ISOweek" + $results1.Schema | Should -Be "dbo" } - It "Should have a function type of Scalar " { - $results1.FunctionType | Should -Be 'Scalar' + It "Should have a function type of Scalar" { + $results1.FunctionType | Should -Be "Scalar" } It "Should have Parameters of [@Date]" { @@ -70,7 +104,7 @@ END; } It "Should not Throw an Error" { - { Get-DbaDbUdf -SqlInstance $TestConfig.instance2 -ExcludeDatabase master -ExcludeSystemUdf } | Should -not -Throw + { Get-DbaDbUdf -SqlInstance $TestConfig.instance2 -ExcludeDatabase master -ExcludeSystemUdf } | Should -Not -Throw } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbUser.Tests.ps1 b/tests/Get-DbaDbUser.Tests.ps1 index d426a4bc3a8..8d96648b483 100644 --- a/tests/Get-DbaDbUser.Tests.ps1 +++ b/tests/Get-DbaDbUser.Tests.ps1 @@ -1,21 +1,41 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaDbUser", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'ExcludeDatabase', 'ExcludeSystemUser', 'User', 'Login', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Database", + "ExcludeDatabase", + "ExcludeSystemUser", + "User", + "Login", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { - $tempguid = [guid]::newguid(); + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + $tempguid = [guid]::newguid() $DBUserName = "dbatoolssci_$($tempguid.guid)" $DBUserName2 = "dbatoolssci2_$($tempguid.guid)" $CreateTestUser = @" @@ -31,26 +51,33 @@ CREATE USER [$DBUserName2] FOR LOGIN [$DBUserName2] WITH DEFAULT_SCHEMA = dbo; "@ Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Query $CreateTestUser -Database master + + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } + AfterAll { + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + $DropTestUser = @" DROP USER [$DBUserName]; DROP USER [$DBUserName2]; DROP LOGIN [$DBUserName]; DROP LOGIN [$DBUserName2]; "@ - Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Query $DropTestUser -Database master + Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Query $DropTestUser -Database master -ErrorAction SilentlyContinue } Context "Users are correctly located" { - $results1 = Get-DbaDbUser -SqlInstance $TestConfig.instance2 -Database master | Where-Object { $_.name -eq "$DBUserName" } | Select-Object * - $results2 = Get-DbaDbUser -SqlInstance $TestConfig.instance2 + BeforeAll { + $results1 = Get-DbaDbUser -SqlInstance $TestConfig.instance2 -Database master | Where-Object Name -eq $DBUserName | Select-Object * + $results2 = Get-DbaDbUser -SqlInstance $TestConfig.instance2 - $resultsByUser = Get-DbaDbUser -SqlInstance $TestConfig.instance2 -Database master -User $DBUserName2 - $resultsByMultipleUser = Get-DbaDbUser -SqlInstance $TestConfig.instance2 -User $DBUserName, $DBUserName2 + $resultsByUser = Get-DbaDbUser -SqlInstance $TestConfig.instance2 -Database master -User $DBUserName2 + $resultsByMultipleUser = Get-DbaDbUser -SqlInstance $TestConfig.instance2 -User $DBUserName, $DBUserName2 - $resultsByLogin = Get-DbaDbUser -SqlInstance $TestConfig.instance2 -Database master -Login $DBUserName2 - $resultsByMultipleLogin = Get-DbaDbUser -SqlInstance $TestConfig.instance2 -Login $DBUserName, $DBUserName2 + $resultsByLogin = Get-DbaDbUser -SqlInstance $TestConfig.instance2 -Database master -Login $DBUserName2 + $resultsByMultipleLogin = Get-DbaDbUser -SqlInstance $TestConfig.instance2 -Login $DBUserName, $DBUserName2 + } It "Should execute and return results" { $results2 | Should -Not -Be $null @@ -61,12 +88,12 @@ DROP LOGIN [$DBUserName2]; } It "Should have matching login and username of $DBUserName" { - $results1.name | Should -Be "$DBUserName" - $results1.login | Should -Be "$DBUserName" + $results1.name | Should -Be $DBUserName + $results1.login | Should -Be $DBUserName } It "Should have a login type of SqlLogin" { - $results1.LoginType | Should -Be 'SqlLogin' + $results1.LoginType | Should -Be "SqlLogin" } It "Should have DefaultSchema of dbo" { @@ -101,4 +128,4 @@ DROP LOGIN [$DBUserName2]; $resultsByMultipleLogin.Database | Should -Be master, master } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbUserDefinedTableType.Tests.ps1 b/tests/Get-DbaDbUserDefinedTableType.Tests.ps1 index 28acae62001..f07a3608c0d 100644 --- a/tests/Get-DbaDbUserDefinedTableType.Tests.ps1 +++ b/tests/Get-DbaDbUserDefinedTableType.Tests.ps1 @@ -1,55 +1,92 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaDbUserDefinedTableType", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'EnableException', 'Database', 'ExcludeDatabase', 'Type' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "EnableException", + "Database", + "ExcludeDatabase", + "Type" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true + $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 - $tabletypename = ("dbatools_{0}" -f $(Get-Random)) - $tabletypename1 = ("dbatools_{0}" -f $(Get-Random)) - $server.Query("CREATE TYPE $tabletypename AS TABLE([column1] INT NULL)", 'tempdb') - $server.Query("CREATE TYPE $tabletypename1 AS TABLE([column1] INT NULL)", 'tempdb') + $tableTypeName = "dbatools_$(Get-Random)" + $tableTypeName1 = "dbatools_$(Get-Random)" + $server.Query("CREATE TYPE $tableTypeName AS TABLE([column1] INT NULL)", "tempdb") + $server.Query("CREATE TYPE $tableTypeName1 AS TABLE([column1] INT NULL)", "tempdb") + + $PSDefaultParameterValues.Remove("*-Dba*:EnableException") } + AfterAll { - $null = $server.Query("DROP TYPE $tabletypename", 'tempdb') - $null = $server.Query("DROP TYPE $tabletypename1", 'tempdb') + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true + + $null = $server.Query("DROP TYPE $tabletypename", "tempdb") -ErrorAction SilentlyContinue + $null = $server.Query("DROP TYPE $tabletypename1", "tempdb") -ErrorAction SilentlyContinue } Context "Gets a Db User Defined Table Type" { - $results = Get-DbaDbUserDefinedTableType -SqlInstance $TestConfig.instance2 -database tempdb -Type $tabletypename + BeforeAll { + $splatUserDefinedTableType = @{ + SqlInstance = $TestConfig.instance2 + Database = "tempdb" + Type = $tableTypeName + } + $results = Get-DbaDbUserDefinedTableType @splatUserDefinedTableType + } + It "Gets results" { - $results | Should Not Be $Null + $results | Should -Not -BeNullOrEmpty } - It "Should have a name of $tabletypename" { - $results.name | Should Be "$tabletypename" + + It "Should have a name of $tableTypeName" { + $results.Name | Should -BeExactly $tableTypeName } + It "Should have an owner of dbo" { - $results.owner | Should Be "dbo" + $results.Owner | Should -BeExactly "dbo" } + It "Should have a count of 1" { - $results.Count | Should Be 1 + $results.Count | Should -BeExactly 1 } } Context "Gets all the Db User Defined Table Type" { - $results = Get-DbaDbUserDefinedTableType -SqlInstance $TestConfig.instance2 -database tempdb + BeforeAll { + $results = Get-DbaDbUserDefinedTableType -SqlInstance $TestConfig.instance2 -Database tempdb + } + It "Gets results" { - $results | Should Not Be $Null + $results | Should -Not -BeNullOrEmpty } + It "Should have a count of 2" { - $results.Count | Should Be 2 + $results.Count | Should -BeExactly 2 } - } -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbView.Tests.ps1 b/tests/Get-DbaDbView.Tests.ps1 index f28b2b8a889..16e73a99586 100644 --- a/tests/Get-DbaDbView.Tests.ps1 +++ b/tests/Get-DbaDbView.Tests.ps1 @@ -1,30 +1,66 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaDbView", # Static command name for dbatools + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - It "Should only contain our specific parameters" { - [array]$params = ([Management.Automation.CommandMetaData]$ExecutionContext.SessionState.InvokeCommand.GetCommand($CommandName, 'Function')).Parameters.Keys - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'ExcludeDatabase', 'ExcludeSystemView', 'View', 'Schema', 'InputObject', 'EnableException' - Compare-Object -ReferenceObject $knownParameters -DifferenceObject $params | Should -BeNullOrEmpty +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Database", + "ExcludeDatabase", + "ExcludeSystemView", + "View", + "Schema", + "InputObject", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { - $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 - $viewName = ("dbatoolsci_{0}" -f $(Get-Random)) - $viewNameWithSchema = ("dbatoolsci_{0}" -f $(Get-Random)) - $server.Query("CREATE VIEW $viewName AS (SELECT 1 as col1)", 'tempdb') - $server.Query("CREATE SCHEMA [someschema]", 'tempdb') - $server.Query("CREATE VIEW [someschema].$viewNameWithSchema AS (SELECT 1 as col1)", 'tempdb') + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # Set variables. They are available in all the It blocks. + $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 + $viewName = "dbatoolsci_$(Get-Random)" + $viewNameWithSchema = "dbatoolsci_$(Get-Random)" + $schemaName = "someschema" + + # Create the objects. + $server.Query("CREATE VIEW $viewName AS (SELECT 1 as col1)", "tempdb") + $server.Query("CREATE SCHEMA [$schemaName]", "tempdb") + $server.Query("CREATE VIEW [$schemaName].$viewNameWithSchema AS (SELECT 1 as col1)", "tempdb") + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } AfterAll { - $null = $server.Query("DROP VIEW $viewName", 'tempdb') - $null = $server.Query("DROP VIEW [someschema].$viewNameWithSchema", 'tempdb') - $null = $server.Query("DROP SCHEMA [someschema]", 'tempdb') + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # Cleanup all created objects. + $null = $server.Query("DROP VIEW $viewName", "tempdb") + $null = $server.Query("DROP VIEW [$schemaName].$viewNameWithSchema", "tempdb") + $null = $server.Query("DROP SCHEMA [$schemaName]", "tempdb") + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } Context "Command actually works" { @@ -32,25 +68,29 @@ Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { $results = Get-DbaDbView -SqlInstance $TestConfig.instance2 -Database tempdb } It "Should have standard properties" { - $ExpectedProps = 'ComputerName,InstanceName,SqlInstance'.Split(',') - ($results[0].PsObject.Properties.Name | Where-Object { $_ -in $ExpectedProps } | Sort-Object) | Should -Be ($ExpectedProps | Sort-Object) + $ExpectedProps = @( + "ComputerName", + "InstanceName", + "SqlInstance" + ) + ($results[0].PsObject.Properties.Name | Where-Object { $PSItem -in $ExpectedProps } | Sort-Object) | Should -Be ($ExpectedProps | Sort-Object) } It "Should get test view: $viewName" { ($results | Where-Object Name -eq $viewName).Name | Should -Be $viewName } It "Should include system views" { - ($results | Where-Object IsSystemObject -eq $true).Count | Should -BeGreaterThan 0 + @($results | Where-Object IsSystemObject -eq $true).Count | Should -BeGreaterThan 0 } } Context "Exclusions work correctly" { It "Should contain no views from master database" { $results = Get-DbaDbView -SqlInstance $TestConfig.instance2 -ExcludeDatabase master - 'master' | Should -Not -BeIn $results.Database + "master" | Should -Not -BeIn $results.Database } It "Should exclude system views" { $results = Get-DbaDbView -SqlInstance $TestConfig.instance2 -Database master -ExcludeSystemView - ($results | Where-Object IsSystemObject -eq $true).Count | Should -Be 0 + @($results | Where-Object IsSystemObject -eq $true).Count | Should -Be 0 } } @@ -67,9 +107,9 @@ Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { Context "Schema parameter (see #9445)" { It "Should return just one view with schema 'someschema'" { - $results = $TestConfig.instance2 | Get-DbaDbView -Database tempdb -Schema 'someschema' + $results = $TestConfig.instance2 | Get-DbaDbView -Database tempdb -Schema "someschema" ($results | Where-Object Name -eq $viewNameWithSchema).Name | Should -Be $viewNameWithSchema - ($results | Where-Object Schema -ne 'someschema').Count | Should -Be 0 + @($results | Where-Object Schema -ne "someschema").Count | Should -Be 0 } } -} +} \ No newline at end of file