From 5fbde1426256bb9e2a88860dfe108f494012cb32 Mon Sep 17 00:00:00 2001 From: Chrissy LeMaire Date: Sat, 9 Aug 2025 06:46:13 +0200 Subject: [PATCH 01/10] Refactor and enhance Pester tests for dbatools DbMail commands Refactored Pester tests for various Get-DbaDbMail* and related commands to use parameterized test headers, static command names, and improved parameter validation. Updated integration tests to use BeforeAll/AfterAll blocks for setup and cleanup, improved assertions, and standardized test structure for consistency and maintainability. --- tests/Get-DbaDbMail.Tests.ps1 | 70 ++++-- tests/Get-DbaDbMailAccount.Tests.ps1 | 119 ++++++--- tests/Get-DbaDbMailConfig.Tests.ps1 | 110 +++++--- tests/Get-DbaDbMailHistory.Tests.ps1 | 91 +++++-- tests/Get-DbaDbMailLog.Tests.ps1 | 89 +++++-- tests/Get-DbaDbMailProfile.Tests.ps1 | 100 +++++--- tests/Get-DbaDbMailServer.Tests.ps1 | 108 +++++--- tests/Get-DbaDbMasterKey.Tests.ps1 | 82 ++++-- tests/Get-DbaDbMemoryUsage.Tests.ps1 | 53 ++-- tests/Get-DbaDbMirror.Tests.ps1 | 67 +++-- tests/Get-DbaDbMirrorMonitor.Tests.ps1 | 33 ++- tests/Get-DbaDbObjectTrigger.Tests.ps1 | 162 +++++++++--- tests/Get-DbaDbOrphanUser.Tests.ps1 | 106 +++++--- tests/Get-DbaDbPageInfo.Tests.ps1 | 68 +++-- tests/Get-DbaDbPartitionFunction.Tests.ps1 | 57 +++-- tests/Get-DbaDbPartitionScheme.Tests.ps1 | 82 ++++-- tests/Get-DbaDbQueryStoreOption.Tests.ps1 | 31 ++- tests/Get-DbaDbRecoveryModel.Tests.ps1 | 56 +++-- tests/Get-DbaDbRestoreHistory.Tests.ps1 | 172 ++++++++++--- tests/Get-DbaDbRole.Tests.ps1 | 91 ++++--- tests/Get-DbaDbRoleMember.Tests.ps1 | 87 +++++-- tests/Get-DbaDbSchema.Tests.ps1 | 51 +++- tests/Get-DbaDbSequence.Tests.ps1 | 111 +++++++-- tests/Get-DbaDbServiceBrokerQueue.Tests.ps1 | 82 ++++-- tests/Get-DbaDbServiceBrokerService.Tests.ps1 | 81 ++++-- tests/Get-DbaDbSharePoint.Tests.ps1 | 100 ++++++-- tests/Get-DbaDbSnapshot.Tests.ps1 | 80 ++++-- tests/Get-DbaDbSpace.Tests.ps1 | 107 +++++--- tests/Get-DbaDbState.Tests.ps1 | 234 ++++++++++++------ tests/Get-DbaDbStoredProcedure.Tests.ps1 | 76 ++++-- tests/Get-DbaDbSynonym.Tests.ps1 | 98 +++++--- tests/Get-DbaDbTable.Tests.ps1 | 67 +++-- tests/Get-DbaDbTrigger.Tests.ps1 | 81 ++++-- tests/Get-DbaDbUdf.Tests.ps1 | 68 +++-- tests/Get-DbaDbUser.Tests.ps1 | 69 ++++-- tests/Get-DbaDbUserDefinedTableType.Tests.ps1 | 63 +++-- tests/Get-DbaDbView.Tests.ps1 | 90 +++++-- 37 files changed, 2400 insertions(+), 892 deletions(-) diff --git a/tests/Get-DbaDbMail.Tests.ps1 b/tests/Get-DbaDbMail.Tests.ps1 index dfc15fd8c86a..0dcd38813263 100644 --- a/tests/Get-DbaDbMail.Tests.ps1 +++ b/tests/Get-DbaDbMail.Tests.ps1 @@ -1,46 +1,68 @@ -$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 } } } diff --git a/tests/Get-DbaDbMailAccount.Tests.ps1 b/tests/Get-DbaDbMailAccount.Tests.ps1 index dbb6f8a64a5c..542df6ce45e1 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 } } } diff --git a/tests/Get-DbaDbMailConfig.Tests.ps1 b/tests/Get-DbaDbMailConfig.Tests.ps1 index 395dc5aa4b79..44660a34c637 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 1a7b1f3846eb..ee42442d989b 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 574d6617ef81..4122688ab1a1 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 7d076b739f7a..ef0e96bfe9e5 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 7257734cceb5..21219150d6f9 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 } } } diff --git a/tests/Get-DbaDbMasterKey.Tests.ps1 b/tests/Get-DbaDbMasterKey.Tests.ps1 index dd697c12a233..2036872c5d70 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 52f0e48bb99e..4c7b6ebe456a 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" } } } diff --git a/tests/Get-DbaDbMirror.Tests.ps1 b/tests/Get-DbaDbMirror.Tests.ps1 index 4ff5e8e4dc50..363eb4dc7ee8 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 5b0d06de6179..4372193cf751 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 4f51c3e2a033..6952eae5c02e 100644 --- a/tests/Get-DbaDbObjectTrigger.Tests.ps1 +++ b/tests/Get-DbaDbObjectTrigger.Tests.ps1 @@ -1,28 +1,44 @@ -$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 +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 only contain $paramCount parameters" { - $params.Count - $defaultParamCount | Should Be $paramCount + + 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_addtriggertoobject" - $tablename = "dbo.dbatoolsci_trigger" + # 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" - $triggertable = @" + $triggertable = @" CREATE TRIGGER $triggertablename ON $tablename AFTER INSERT @@ -32,9 +48,9 @@ CREATE TRIGGER $triggertablename END "@ - $viewname = "dbo.dbatoolsci_view" + $viewname = "dbo.dbatoolsci_view" $triggerviewname = "dbatoolsci_triggeronview" - $triggerview = @" + $triggerview = @" CREATE TRIGGER $triggerviewname ON $viewname INSTEAD OF INSERT @@ -53,125 +69,191 @@ 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 } + It "Should be enabled" { $results.isenabled | Should -Be $true } + It "Should have text of Trigger" { - $results.TextBody | Should -BeLike '*dbatoolsci_trigger table*' + $results.TextBody | Should -BeLike "*dbatoolsci_trigger table*" } } + 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 } + It "Should be enabled" { $results.isenabled | Should -Be $true } + It "Should have text of Trigger" { - $results.TextBody | Should -BeLike '*dbatoolsci_trigger table*' + $results.TextBody | Should -BeLike "*dbatoolsci_trigger table*" } } + 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 } + It "Should be enabled" { $results.isenabled | Should -Be $true } + It "Should have text of Trigger" { - $results.TextBody | Should -BeLike '*dbatoolsci_trigger table*' + $results.TextBody | Should -BeLike "*dbatoolsci_trigger table*" } } + 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 } + It "Should be enabled" { $results.isenabled | Should -Be $true } + It "Should have text of Trigger" { - $results.TextBody | Should -BeLike '*dbatoolsci_view view*' + $results.TextBody | Should -BeLike "*dbatoolsci_view view*" } } + 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 } + It "Should be enabled" { $results.isenabled | Should -Be $true } + It "Should have text of Trigger" { - $results.TextBody | Should -BeLike '*dbatoolsci_view view*' + $results.TextBody | Should -BeLike "*dbatoolsci_view view*" } } + 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 } + It "Should be enabled" { $results.isenabled | Should -Be $true } + It "Should have text of Trigger" { - $results.TextBody | Should -BeLike '*dbatoolsci_view view*' + $results.TextBody | Should -BeLike "*dbatoolsci_view view*" } } + 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" { - $results.Count | Should -Be 2 + $results.Status.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" { - $results.Count | Should -Be 2 + $results.Status.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 + $results.Status.Count | Should -Be 1 } + It "Should have text of 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 + $results.Status.Count | Should -Be 1 } + It "Should have text of 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 0dfdd511908e..da5e47e0ae5c 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 f612519117ca..49fa77081086 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 } } } diff --git a/tests/Get-DbaDbPartitionFunction.Tests.ps1 b/tests/Get-DbaDbPartitionFunction.Tests.ps1 index 2bd6287299a9..d6d2cdb98773 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 2c769ef401de..c16bf1720d17 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 0e30b0f1fd07..3e7d0947aebc 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 86faedfb9faf..4db903aedbac 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 521d4d26f832..166510319105 100644 --- a/tests/Get-DbaDbRestoreHistory.Tests.ps1 +++ b/tests/Get-DbaDbRestoreHistory.Tests.ps1 @@ -1,61 +1,111 @@ -$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' { - 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 +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", + "Since", + "Force", + "Last", + "RestoreType", + "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 + + # For all the backups that we want to clean up after the test, we create a directory that we can delete at the end. + # Other files can be written there as well, maybe we change the name of that variable later. But for now we focus on backups. + $backupPath = "$($TestConfig.Temp)\$CommandName-$(Get-Random)" + $null = New-Item -Path $backupPath -ItemType Directory + + # Set variables. They are available in all the It blocks. $random = Get-Random $dbname1 = "dbatoolsci_restorehistory1_$random" $dbname2 = "dbatoolsci_restorehistory2_$random" + + # Create the objects. $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 - $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 + $fullBackup = Backup-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname1 -Type Full -Path $backupPath + $diffBackup = Backup-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname1 -Type Diff -Path $backupPath + $logBackup = Backup-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname1 -Type Log -Path $backupPath $null = Restore-DbaDatabase -SqlInstance $TestConfig.instance2 -Path $diffBackup.BackupPath, $logBackup.BackupPath -DatabaseName $dbname1 -WithReplace + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } AfterAll { + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # Cleanup all created object. $null = Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname1, $dbname2 | Remove-DbaDatabase -Confirm:$false - Remove-Item -Path $fullBackup.BackupPath -Force - Remove-Item -Path $logBackup.BackupPath -Force + + # Remove the backup directory. + Remove-Item -Path $backupPath -Recurse -ErrorAction SilentlyContinue + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } + Context "Preparation" { It "Should have prepared" { 1 | Should -Be 1 } } + 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.Status.Count | Should -Be 1 } + It "Should return the full restore with the correct properties" { $results[0].RestoreType | Should -Be "Database" $results[0].From | Should -Be "$($TestConfig.appveyorlabrepo)\singlerestore\singlerestore.bak" $results[0].To | Should -Match "\\rsh_pre_$dbname2" } } + 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.Status.Count | Should -Be 2 } + It "Should return the full restore with the correct properties" { $results[0].RestoreType | Should -Be "Database" $results[1].RestoreType | Should -Be "Log" @@ -65,41 +115,97 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { ($results | Where-Object Database -eq $dbname2).To | Should -Match "\\rsh_pre_$dbname2" } } + 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 + $results.Status.Count | Should -Be 6 } + It "Should return the full restore with the correct properties" { @($results | Where-Object Database -eq $dbname1).Count | Should -Be 4 @($results | Where-Object Database -eq $dbname2).Count | Should -Be 2 } } + Context "return object properties" { It "has the correct properties" { $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) + $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 | Where-Object RestoreType -eq Database).Count | Should -Be 4 + $splatFullRestore = @{ + SqlInstance = $TestConfig.instance2 + Database = $dbname1, $dbname2 + RestoreType = "Database" + } + $results = Get-DbaDbRestoreHistory @splatFullRestore + $results.Status.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 + $splatDiffRestore = @{ + SqlInstance = $TestConfig.instance2 + Database = $dbname1 + RestoreType = "Differential" + } + $results = Get-DbaDbRestoreHistory @splatDiffRestore $results.Database | Should -Be $dbname1 - $results.RestoreType | Should -Be Differential + $results.RestoreType | Should -Be "Differential" } + It "returns the correct history records for log restore" { - $results = Get-DbaDbRestoreHistory -SqlInstance $TestConfig.instance2 -Database $dbname1 -RestoreType Log + $splatLogRestore = @{ + SqlInstance = $TestConfig.instance2 + Database = $dbname1 + RestoreType = "Log" + } + $results = Get-DbaDbRestoreHistory @splatLogRestore $results.Database | Should -Be $dbname1 - $results.RestoreType | Should -Be Log + $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 1eee8780ecc6..99cf4c2e0734 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 8cbd3a8ec816..9a1cc4ab71a6 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" } } } diff --git a/tests/Get-DbaDbSchema.Tests.ps1 b/tests/Get-DbaDbSchema.Tests.ps1 index 3ac00c4526b1..db26e3b872e5 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 7e3dbaf52b17..d59ae9de22cd 100644 --- a/tests/Get-DbaDbSequence.Tests.ps1 +++ b/tests/Get-DbaDbSequence.Tests.ps1 @@ -1,55 +1,122 @@ -$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 + + # Set variables. They are available in all the It blocks. $random = Get-Random $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 $newDbName = "dbatoolsci_newdb_$random" $newDbName2 = "dbatoolsci_newdb2_$random" + + # Create the objects. $newDb, $newDb2 = New-DbaDatabase -SqlInstance $server -Name $newDbName, $newDbName2 - $sequence = New-DbaDbSequence -SqlInstance $server -Database $newDbName -Sequence "Sequence1_$random" -Schema "Schema_$random" - $sequence2 = New-DbaDbSequence -SqlInstance $server -Database $newDbName -Sequence "Sequence2_$random" -Schema "Schema2_$random" - $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" + $splatSequence1 = @{ + SqlInstance = $server + Database = $newDbName + Sequence = "Sequence1_$random" + Schema = "Schema_$random" + } + $sequence = New-DbaDbSequence @splatSequence1 + + $splatSequence2 = @{ + SqlInstance = $server + Database = $newDbName + Sequence = "Sequence2_$random" + Schema = "Schema2_$random" + } + $sequence2 = New-DbaDbSequence @splatSequence2 + + $splatSequence3 = @{ + SqlInstance = $server + Database = $newDbName + Sequence = "Sequence1_$random" + Schema = "Schema2_$random" + } + $sequence3 = New-DbaDbSequence @splatSequence3 + + $splatSequence4 = @{ + SqlInstance = $server + Database = $newDbName + Sequence = "Sequence2_$random" + Schema = "Schema_$random" + } + $sequence4 = New-DbaDbSequence @splatSequence4 + + $splatSequence5 = @{ + SqlInstance = $server + Database = $newDbName2 + Sequence = "Sequence1_$random" + Schema = "Schema_$random" + } + $sequence5 = New-DbaDbSequence @splatSequence5 + + # 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 = $newDb, $newDb2 | Remove-DbaDatabase -Confirm:$false + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # Cleanup all created objects. + $null = $newDb, $newDb2 | Remove-DbaDatabase -Confirm:$false -ErrorAction SilentlyContinue + + # 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 + $sequence.Status.Count | Should -BeGreaterOrEqual 5 } It "finds a sequence in a single database" { $sequence = Get-DbaDbSequence -SqlInstance $server -Database $newDbName $sequence.Parent.Name | Select-Object -Unique | Should -Be $newDbName - $sequence.Count | Should -Be 4 + $sequence.Status.Count | Should -Be 4 } It "finds a sequence in a single database by schema only" { $sequence = Get-DbaDbSequence -SqlInstance $server -Database $newDbName -Schema "Schema2_$random" $sequence.Parent.Name | Select-Object -Unique | Should -Be $newDbName $sequence.Schema | Select-Object -Unique | Should -Be "Schema2_$random" - $sequence.Count | Should -Be 2 + $sequence.Status.Count | Should -Be 2 } It "finds a sequence in a single database by schema and by name" { @@ -57,26 +124,26 @@ Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { $sequence.Parent.Name | Select-Object -Unique | Should -Be $newDbName $sequence.Name | Select-Object -Unique | Should -Be "Sequence1_$random" $sequence.Schema | Select-Object -Unique | Should -Be "Schema_$random" - $sequence.Count | Should -Be 1 + $sequence.Status.Count | Should -Be 1 } It "finds a sequence on an instance by name only" { $sequence = Get-DbaDbSequence -SqlInstance $server -Sequence "Sequence1_$random" $sequence.Name | Select-Object -Unique | Should -Be "Sequence1_$random" - $sequence.Count | Should -Be 3 + $sequence.Status.Count | Should -Be 3 } It "finds a sequence on an instance by schema only" { $sequence = Get-DbaDbSequence -SqlInstance $server -Schema "Schema2_$random" $sequence.Schema | Select-Object -Unique | Should -Be "Schema2_$random" - $sequence.Count | Should -Be 2 + $sequence.Status.Count | Should -Be 2 } It "finds a sequence on an instance by schema and name" { $sequence = Get-DbaDbSequence -SqlInstance $server -Schema "Schema_$random" -Sequence "Sequence1_$random" $sequence.Schema | Select-Object -Unique | Should -Be "Schema_$random" $sequence.Name | Select-Object -Unique | Should -Be "Sequence1_$random" - $sequence.Count | Should -Be 2 + $sequence.Status.Count | Should -Be 2 } It "supports piping databases" { @@ -86,4 +153,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 a3a50cec718e..3419f9969e8d 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 4d31c5e84e10..cc1221e3817b 100644 --- a/tests/Get-DbaDbServiceBrokerService.Tests.ps1 +++ b/tests/Get-DbaDbServiceBrokerService.Tests.ps1 @@ -1,47 +1,80 @@ -$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 406c87922e70..14781ece5e2b 100644 --- a/tests/Get-DbaDbSharePoint.Tests.ps1 +++ b/tests/Get-DbaDbSharePoint.Tests.ps1 @@ -1,32 +1,62 @@ -$commandname = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaDbSharePoint", + $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', '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 } } + # 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" + if (Test-Path -Path $bacpac) { $sqlpackage = (Get-Command sqlpackage -ErrorAction Ignore).Source if (-not $sqlpackage) { @@ -50,16 +80,50 @@ Describe "$commandname Integration Tests" -Tag "IntegrationTests" { Write-Warning -Message "No bacpac found in path [$bacpac], skipping tests." $skip = $true } + + # Store skip value globally for use in It blocks + $global:skipIntegrationTests = $skip + + # 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 - foreach ($db in $spdb) { - It -Skip:$skip "returns $db from in the SharePoint database list" { - $db | Should -BeIn $results.Name - } + BeforeAll { + $results = Get-DbaDbSharePoint -SqlInstance $TestConfig.instance2 + } + + It "Returns SharePoint_Admin_7c0c491d0e6f43858f75afa5399d49ab from in the SharePoint database list" -Skip:$global:skipIntegrationTests { + "SharePoint_Admin_7c0c491d0e6f43858f75afa5399d49ab" | Should -BeIn $results.Name + } + + It "Returns WSS_Logging from in the SharePoint database list" -Skip:$global:skipIntegrationTests { + "WSS_Logging" | Should -BeIn $results.Name + } + + It "Returns SecureStoreService_20e1764876504335a6d8dd0b1937f4bf from in the SharePoint database list" -Skip:$global:skipIntegrationTests { + "SecureStoreService_20e1764876504335a6d8dd0b1937f4bf" | Should -BeIn $results.Name + } + + It "Returns DefaultWebApplicationDB from in the SharePoint database list" -Skip:$global:skipIntegrationTests { + "DefaultWebApplicationDB" | Should -BeIn $results.Name + } + + It "Returns SharePoint_Config_4c524cb90be44c6f906290fe3e34f2e0 from in the SharePoint database list" -Skip:$global:skipIntegrationTests { + "SharePoint_Config_4c524cb90be44c6f906290fe3e34f2e0" | Should -BeIn $results.Name + } + + It "Returns DefaultPowerPivotServiceApplicationDB-5b638361-c6fc-4ad9-b8ba-d05e63e48ac6 from in the SharePoint database list" -Skip:$global:skipIntegrationTests { + "DefaultPowerPivotServiceApplicationDB-5b638361-c6fc-4ad9-b8ba-d05e63e48ac6" | 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 6c13aff1501d..1e70b114738e 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 d87417e44e74..9dd0ecf2fe26 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 77456ed57ac8..5abcfd95148e 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 925ae2a6c921..9f0eb6c6659a 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 ce7493e94d70..fbf9b4415b74 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 95b2cfe2c3d8..4cb439e4e7d0 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 31b9af58e0e4..aaa8346fdb42 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 } } } diff --git a/tests/Get-DbaDbUdf.Tests.ps1 b/tests/Get-DbaDbUdf.Tests.ps1 index b5c739dc963c..4c1c40b61653 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 } } } diff --git a/tests/Get-DbaDbUser.Tests.ps1 b/tests/Get-DbaDbUser.Tests.ps1 index d426a4bc3a87..8d96648b483b 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 28acae620015..f1f322bf6bff 100644 --- a/tests/Get-DbaDbUserDefinedTableType.Tests.ps1 +++ b/tests/Get-DbaDbUserDefinedTableType.Tests.ps1 @@ -1,19 +1,35 @@ -$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", + "Database", + "ExcludeDatabase", + "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 { $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 $tabletypename = ("dbatools_{0}" -f $(Get-Random)) @@ -27,29 +43,38 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { } Context "Gets a Db User Defined Table Type" { - $results = Get-DbaDbUserDefinedTableType -SqlInstance $TestConfig.instance2 -database tempdb -Type $tabletypename + BeforeAll { + $results = Get-DbaDbUserDefinedTableType -SqlInstance $TestConfig.instance2 -Database tempdb -Type $tabletypename + } + It "Gets results" { - $results | Should Not Be $Null + $results | Should -Not -BeNullOrEmpty } + It "Should have a name of $tabletypename" { - $results.name | Should Be "$tabletypename" + $results.Name | Should -Be $tabletypename } + It "Should have an owner of dbo" { - $results.owner | Should Be "dbo" + $results.Owner | Should -Be "dbo" } + It "Should have a count of 1" { - $results.Count | Should Be 1 + $results.Status.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.Status.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 f28b2b8a889b..0a6e2c37aed0 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 From 1f17830b00715d96d6e27afd839e0a4d4445f5aa Mon Sep 17 00:00:00 2001 From: Chrissy LeMaire Date: Sat, 9 Aug 2025 07:42:28 +0200 Subject: [PATCH 02/10] Enhance formatter to preserve alignment and avoid unnecessary writes Updated Invoke-DbatoolsFormatter to use custom PSSA settings that preserve manually aligned hashtables and assignment operators. The script now only writes files if formatting changes are detected, reducing unnecessary file writes. --- public/Invoke-DbatoolsFormatter.ps1 | 62 +++++++++++++++++++++++++++-- 1 file changed, 59 insertions(+), 3 deletions(-) diff --git a/public/Invoke-DbatoolsFormatter.ps1 b/public/Invoke-DbatoolsFormatter.ps1 index 257af695f4e6..07b8e0b9ce4c 100644 --- a/public/Invoke-DbatoolsFormatter.ps1 +++ b/public/Invoke-DbatoolsFormatter.ps1 @@ -5,6 +5,8 @@ function Invoke-DbatoolsFormatter { .DESCRIPTION Uses PSSA's Invoke-Formatter to format the target files and saves it without the BOM. + Preserves manually aligned hashtables and assignment operators. + Only writes files if formatting changes are detected. .PARAMETER Path The path to the ps1 file that needs to be formatted @@ -57,6 +59,48 @@ function Invoke-DbatoolsFormatter { $CBHRex = [regex]'(?smi)\s+\<\#[^#]*\#\>' $CBHStartRex = [regex]'(?[ ]+)\<\#' $CBHEndRex = [regex]'(?[ ]*)\#\>' + + # Create custom formatter settings that preserve alignment + $customSettings = @{ + IncludeRules = @( + 'PSPlaceOpenBrace', + 'PSPlaceCloseBrace', + 'PSUseConsistentIndentation', + 'PSUseConsistentWhitespace' + ) + Rules = @{ + PSPlaceOpenBrace = @{ + Enable = $true + OnSameLine = $true + NewLineAfter = $true + IgnoreOneLineBlock = $true + } + PSPlaceCloseBrace = @{ + Enable = $true + NewLineAfter = $false + IgnoreOneLineBlock = $true + NoEmptyLineBefore = $false + } + PSUseConsistentIndentation = @{ + Enable = $true + Kind = 'space' + PipelineIndentation = 'IncreaseIndentationForFirstPipeline' + IndentationSize = 4 + } + PSUseConsistentWhitespace = @{ + Enable = $true + CheckInnerBrace = $true + CheckOpenBrace = $true + CheckOpenParen = $true + CheckOperator = $false # This is key - don't mess with operator spacing + CheckPipe = $true + CheckPipeForRedundantWhitespace = $false + CheckSeparator = $true + CheckParameter = $false + } + } + } + $OSEOL = "`n" if ($psVersionTable.Platform -ne 'Unix') { $OSEOL = "`r`n" @@ -71,7 +115,9 @@ function Invoke-DbatoolsFormatter { Stop-Function -Message "Cannot find or resolve $p" -Continue } - $content = Get-Content -Path $realPath -Raw -Encoding UTF8 + $originalContent = Get-Content -Path $realPath -Raw -Encoding UTF8 + $content = $originalContent + if ($OSEOL -eq "`r`n") { # See #5830, we are in Windows territory here # Is the file containing at least one `r ? @@ -85,7 +131,8 @@ function Invoke-DbatoolsFormatter { #strip ending empty lines $content = $content -replace "(?s)$OSEOL\s*$" try { - $content = Invoke-Formatter -ScriptDefinition $content -Settings CodeFormattingOTBS -ErrorAction Stop + # Use custom settings instead of CodeFormattingOTBS + $content = Invoke-Formatter -ScriptDefinition $content -Settings $customSettings -ErrorAction Stop } catch { Write-Message -Level Warning "Unable to format $p" } @@ -118,7 +165,16 @@ function Invoke-DbatoolsFormatter { #trim whitespace lines $realContent += $line.Replace("`t", " ").TrimEnd() } - [System.IO.File]::WriteAllText($realPath, ($realContent -Join "$OSEOL"), $Utf8NoBomEncoding) + + $finalContent = $realContent -Join "$OSEOL" + + # Only write the file if there are actual changes + if ($finalContent -ne $originalContent) { + Write-Message -Level Verbose "Formatting changes detected in $realPath" + [System.IO.File]::WriteAllText($realPath, $finalContent, $Utf8NoBomEncoding) + } else { + Write-Message -Level Verbose "No formatting changes needed for $realPath" + } } } } \ No newline at end of file From b07ac96cd1b07e00f4320a15d84570b3adf9df72 Mon Sep 17 00:00:00 2001 From: Chrissy LeMaire Date: Sat, 9 Aug 2025 07:51:17 +0200 Subject: [PATCH 03/10] Improve file handling in Invoke-DbatoolsFormatter Added checks to skip directories and non-PowerShell files, improved error handling for file read/write operations, and ensured only valid content is processed. These changes enhance robustness and prevent errors when processing invalid or unreadable files. --- public/Invoke-DbatoolsFormatter.ps1 | 44 +++++++++++++++++++++++++---- 1 file changed, 39 insertions(+), 5 deletions(-) diff --git a/public/Invoke-DbatoolsFormatter.ps1 b/public/Invoke-DbatoolsFormatter.ps1 index 07b8e0b9ce4c..28e1c26ef694 100644 --- a/public/Invoke-DbatoolsFormatter.ps1 +++ b/public/Invoke-DbatoolsFormatter.ps1 @@ -68,7 +68,7 @@ function Invoke-DbatoolsFormatter { 'PSUseConsistentIndentation', 'PSUseConsistentWhitespace' ) - Rules = @{ + Rules = @{ PSPlaceOpenBrace = @{ Enable = $true OnSameLine = $true @@ -115,7 +115,29 @@ function Invoke-DbatoolsFormatter { Stop-Function -Message "Cannot find or resolve $p" -Continue } - $originalContent = Get-Content -Path $realPath -Raw -Encoding UTF8 + # Skip directories and non-PowerShell files + if (Test-Path -Path $realPath -PathType Container) { + Write-Message -Level Verbose "Skipping directory: $realPath" + continue + } + + if ($realPath -notmatch '\.ps1$|\.psm1$|\.psd1$') { + Write-Message -Level Verbose "Skipping non-PowerShell file: $realPath" + continue + } + + try { + $originalContent = Get-Content -Path $realPath -Raw -Encoding UTF8 + } catch { + Stop-Function -Message "Unable to read file $realPath : $($_.Exception.Message)" -Continue + } + + # If Get-Content failed, originalContent might be null or empty + if (-not $originalContent) { + Write-Message -Level Verbose "Skipping empty or unreadable file: $realPath" + continue + } + $content = $originalContent if ($OSEOL -eq "`r`n") { @@ -134,8 +156,16 @@ function Invoke-DbatoolsFormatter { # Use custom settings instead of CodeFormattingOTBS $content = Invoke-Formatter -ScriptDefinition $content -Settings $customSettings -ErrorAction Stop } catch { - Write-Message -Level Warning "Unable to format $p" + Write-Message -Level Warning "Unable to format $realPath : $($_.Exception.Message)" + continue + } + + # Ensure $content is a string before processing + if (-not $content -or $content -isnot [string]) { + Write-Message -Level Warning "Formatter returned unexpected content type for $realPath" + continue } + #match the ending indentation of CBH with the starting one, see #4373 $CBH = $CBHRex.Match($content).Value if ($CBH) { @@ -170,8 +200,12 @@ function Invoke-DbatoolsFormatter { # Only write the file if there are actual changes if ($finalContent -ne $originalContent) { - Write-Message -Level Verbose "Formatting changes detected in $realPath" - [System.IO.File]::WriteAllText($realPath, $finalContent, $Utf8NoBomEncoding) + try { + Write-Message -Level Verbose "Formatting changes detected in $realPath" + [System.IO.File]::WriteAllText($realPath, $finalContent, $Utf8NoBomEncoding) + } catch { + Stop-Function -Message "Unable to write file $realPath : $($_.Exception.Message)" -Continue + } } else { Write-Message -Level Verbose "No formatting changes needed for $realPath" } From 4b4c3b5d20f6bf9c6930a32a9d3ea5de5b10f57a Mon Sep 17 00:00:00 2001 From: Chrissy LeMaire Date: Sat, 9 Aug 2025 08:04:14 +0200 Subject: [PATCH 04/10] Improve formatting comparison in Invoke-DbatoolsFormatter Enhances the formatter to compare processed, formatted content rather than raw content, ensuring that only meaningful formatting changes trigger file writes. Also applies CBH (Comment-Based Help) fixes and whitespace normalization to both the original and formatted content for accurate comparison. --- public/Invoke-DbatoolsFormatter.ps1 | 51 ++++++++++++++++++++++------- 1 file changed, 40 insertions(+), 11 deletions(-) diff --git a/public/Invoke-DbatoolsFormatter.ps1 b/public/Invoke-DbatoolsFormatter.ps1 index 28e1c26ef694..d2ad580c3766 100644 --- a/public/Invoke-DbatoolsFormatter.ps1 +++ b/public/Invoke-DbatoolsFormatter.ps1 @@ -68,7 +68,7 @@ function Invoke-DbatoolsFormatter { 'PSUseConsistentIndentation', 'PSUseConsistentWhitespace' ) - Rules = @{ + Rules = @{ PSPlaceOpenBrace = @{ Enable = $true OnSameLine = $true @@ -150,36 +150,55 @@ function Invoke-DbatoolsFormatter { } } - #strip ending empty lines + # Strip ending empty lines from both original and working content $content = $content -replace "(?s)$OSEOL\s*$" + $originalStripped = $originalContent -replace "(?s)$OSEOL\s*$" + try { - # Use custom settings instead of CodeFormattingOTBS + # Format the content $content = Invoke-Formatter -ScriptDefinition $content -Settings $customSettings -ErrorAction Stop + # Also format the original to compare + $originalFormatted = Invoke-Formatter -ScriptDefinition $originalStripped -Settings $customSettings -ErrorAction Stop } catch { Write-Message -Level Warning "Unable to format $realPath : $($_.Exception.Message)" continue } - # Ensure $content is a string before processing + # Ensure both contents are strings before processing if (-not $content -or $content -isnot [string]) { Write-Message -Level Warning "Formatter returned unexpected content type for $realPath" continue } - #match the ending indentation of CBH with the starting one, see #4373 + if (-not $originalFormatted -or $originalFormatted -isnot [string]) { + Write-Message -Level Warning "Formatter returned unexpected content type for original in $realPath" + continue + } + + # Apply CBH fix to formatted content $CBH = $CBHRex.Match($content).Value if ($CBH) { - #get starting spaces $startSpaces = $CBHStartRex.Match($CBH).Groups['spaces'] if ($startSpaces) { - #get end $newCBH = $CBHEndRex.Replace($CBH, "$startSpaces#>") if ($newCBH) { - #replace the CBH $content = $content.Replace($CBH, $newCBH) } } } + + # Apply CBH fix to original formatted content + $originalCBH = $CBHRex.Match($originalFormatted).Value + if ($originalCBH) { + $startSpaces = $CBHStartRex.Match($originalCBH).Groups['spaces'] + if ($startSpaces) { + $newOriginalCBH = $CBHEndRex.Replace($originalCBH, "$startSpaces#>") + if ($newOriginalCBH) { + $originalFormatted = $originalFormatted.Replace($originalCBH, $newOriginalCBH) + } + } + } + $Utf8NoBomEncoding = New-Object System.Text.UTF8Encoding $False $correctCase = @( 'DbaInstanceParameter' @@ -187,19 +206,29 @@ function Invoke-DbatoolsFormatter { 'PSCustomObject' 'PSItem' ) + + # Process the formatted content $realContent = @() foreach ($line in $content.Split("`n")) { foreach ($item in $correctCase) { $line = $line -replace $item, $item } - #trim whitespace lines $realContent += $line.Replace("`t", " ").TrimEnd() } - $finalContent = $realContent -Join "$OSEOL" + # Process the original formatted content the same way + $originalProcessed = @() + foreach ($line in $originalFormatted.Split("`n")) { + foreach ($item in $correctCase) { + $line = $line -replace $item, $item + } + $originalProcessed += $line.Replace("`t", " ").TrimEnd() + } + $originalFinalContent = $originalProcessed -Join "$OSEOL" + # Only write the file if there are actual changes - if ($finalContent -ne $originalContent) { + if ($finalContent -ne $originalFinalContent) { try { Write-Message -Level Verbose "Formatting changes detected in $realPath" [System.IO.File]::WriteAllText($realPath, $finalContent, $Utf8NoBomEncoding) From 05eb89782d276dfefc75dcc0e5ae1becc20fe38c Mon Sep 17 00:00:00 2001 From: Chrissy LeMaire Date: Sat, 9 Aug 2025 08:42:53 +0200 Subject: [PATCH 05/10] Refactor Invoke-DbatoolsFormatter for improved formatting Simplifies the formatter by removing custom alignment-preserving settings and redundant code. Now uses a placeholder approach to preserve aligned assignments, streamlines file type checks, and only writes files if actual formatting changes are detected. Improves maintainability and reliability of the formatting process. --- public/Invoke-DbatoolsFormatter.ps1 | 150 +++++++--------------------- 1 file changed, 36 insertions(+), 114 deletions(-) diff --git a/public/Invoke-DbatoolsFormatter.ps1 b/public/Invoke-DbatoolsFormatter.ps1 index d2ad580c3766..2c724b63cb3a 100644 --- a/public/Invoke-DbatoolsFormatter.ps1 +++ b/public/Invoke-DbatoolsFormatter.ps1 @@ -5,8 +5,6 @@ function Invoke-DbatoolsFormatter { .DESCRIPTION Uses PSSA's Invoke-Formatter to format the target files and saves it without the BOM. - Preserves manually aligned hashtables and assignment operators. - Only writes files if formatting changes are detected. .PARAMETER Path The path to the ps1 file that needs to be formatted @@ -59,48 +57,6 @@ function Invoke-DbatoolsFormatter { $CBHRex = [regex]'(?smi)\s+\<\#[^#]*\#\>' $CBHStartRex = [regex]'(?[ ]+)\<\#' $CBHEndRex = [regex]'(?[ ]*)\#\>' - - # Create custom formatter settings that preserve alignment - $customSettings = @{ - IncludeRules = @( - 'PSPlaceOpenBrace', - 'PSPlaceCloseBrace', - 'PSUseConsistentIndentation', - 'PSUseConsistentWhitespace' - ) - Rules = @{ - PSPlaceOpenBrace = @{ - Enable = $true - OnSameLine = $true - NewLineAfter = $true - IgnoreOneLineBlock = $true - } - PSPlaceCloseBrace = @{ - Enable = $true - NewLineAfter = $false - IgnoreOneLineBlock = $true - NoEmptyLineBefore = $false - } - PSUseConsistentIndentation = @{ - Enable = $true - Kind = 'space' - PipelineIndentation = 'IncreaseIndentationForFirstPipeline' - IndentationSize = 4 - } - PSUseConsistentWhitespace = @{ - Enable = $true - CheckInnerBrace = $true - CheckOpenBrace = $true - CheckOpenParen = $true - CheckOperator = $false # This is key - don't mess with operator spacing - CheckPipe = $true - CheckPipeForRedundantWhitespace = $false - CheckSeparator = $true - CheckParameter = $false - } - } - } - $OSEOL = "`n" if ($psVersionTable.Platform -ne 'Unix') { $OSEOL = "`r`n" @@ -115,29 +71,13 @@ function Invoke-DbatoolsFormatter { Stop-Function -Message "Cannot find or resolve $p" -Continue } - # Skip directories and non-PowerShell files + # Skip directories if (Test-Path -Path $realPath -PathType Container) { Write-Message -Level Verbose "Skipping directory: $realPath" continue } - if ($realPath -notmatch '\.ps1$|\.psm1$|\.psd1$') { - Write-Message -Level Verbose "Skipping non-PowerShell file: $realPath" - continue - } - - try { - $originalContent = Get-Content -Path $realPath -Raw -Encoding UTF8 - } catch { - Stop-Function -Message "Unable to read file $realPath : $($_.Exception.Message)" -Continue - } - - # If Get-Content failed, originalContent might be null or empty - if (-not $originalContent) { - Write-Message -Level Verbose "Skipping empty or unreadable file: $realPath" - continue - } - + $originalContent = Get-Content -Path $realPath -Raw -Encoding UTF8 $content = $originalContent if ($OSEOL -eq "`r`n") { @@ -150,55 +90,48 @@ function Invoke-DbatoolsFormatter { } } - # Strip ending empty lines from both original and working content + #strip ending empty lines $content = $content -replace "(?s)$OSEOL\s*$" - $originalStripped = $originalContent -replace "(?s)$OSEOL\s*$" - try { - # Format the content - $content = Invoke-Formatter -ScriptDefinition $content -Settings $customSettings -ErrorAction Stop - # Also format the original to compare - $originalFormatted = Invoke-Formatter -ScriptDefinition $originalStripped -Settings $customSettings -ErrorAction Stop - } catch { - Write-Message -Level Warning "Unable to format $realPath : $($_.Exception.Message)" - continue + # Preserve aligned assignments before formatting + # Look for patterns with multiple spaces before OR after the = sign + $alignedPatterns = [regex]::Matches($content, '(?m)^\s*(\$\w+|\w+)\s{2,}=\s*.+$|^\s*(\$\w+|\w+)\s*=\s{2,}.+$') + $placeholders = @{} + + foreach ($match in $alignedPatterns) { + $placeholder = "___ALIGNMENT_PLACEHOLDER_$($placeholders.Count)___" + $placeholders[$placeholder] = $match.Value + $content = $content.Replace($match.Value, $placeholder) } - # Ensure both contents are strings before processing - if (-not $content -or $content -isnot [string]) { - Write-Message -Level Warning "Formatter returned unexpected content type for $realPath" - continue + try { + $formattedContent = Invoke-Formatter -ScriptDefinition $content -Settings CodeFormattingOTBS -ErrorAction Stop + if ($formattedContent) { + $content = $formattedContent + } + } catch { + # Just silently continue - the formatting might still work partially } - if (-not $originalFormatted -or $originalFormatted -isnot [string]) { - Write-Message -Level Warning "Formatter returned unexpected content type for original in $realPath" - continue + # Restore the aligned patterns + foreach ($key in $placeholders.Keys) { + $content = $content.Replace($key, $placeholders[$key]) } - # Apply CBH fix to formatted content + #match the ending indentation of CBH with the starting one, see #4373 $CBH = $CBHRex.Match($content).Value if ($CBH) { + #get starting spaces $startSpaces = $CBHStartRex.Match($CBH).Groups['spaces'] if ($startSpaces) { + #get end $newCBH = $CBHEndRex.Replace($CBH, "$startSpaces#>") if ($newCBH) { + #replace the CBH $content = $content.Replace($CBH, $newCBH) } } } - - # Apply CBH fix to original formatted content - $originalCBH = $CBHRex.Match($originalFormatted).Value - if ($originalCBH) { - $startSpaces = $CBHStartRex.Match($originalCBH).Groups['spaces'] - if ($startSpaces) { - $newOriginalCBH = $CBHEndRex.Replace($originalCBH, "$startSpaces#>") - if ($newOriginalCBH) { - $originalFormatted = $originalFormatted.Replace($originalCBH, $newOriginalCBH) - } - } - } - $Utf8NoBomEncoding = New-Object System.Text.UTF8Encoding $False $correctCase = @( 'DbaInstanceParameter' @@ -206,37 +139,26 @@ function Invoke-DbatoolsFormatter { 'PSCustomObject' 'PSItem' ) - - # Process the formatted content $realContent = @() foreach ($line in $content.Split("`n")) { foreach ($item in $correctCase) { $line = $line -replace $item, $item } + #trim whitespace lines $realContent += $line.Replace("`t", " ").TrimEnd() } - $finalContent = $realContent -Join "$OSEOL" - # Process the original formatted content the same way - $originalProcessed = @() - foreach ($line in $originalFormatted.Split("`n")) { - foreach ($item in $correctCase) { - $line = $line -replace $item, $item - } - $originalProcessed += $line.Replace("`t", " ").TrimEnd() - } - $originalFinalContent = $originalProcessed -Join "$OSEOL" + $newContent = $realContent -Join "$OSEOL" - # Only write the file if there are actual changes - if ($finalContent -ne $originalFinalContent) { - try { - Write-Message -Level Verbose "Formatting changes detected in $realPath" - [System.IO.File]::WriteAllText($realPath, $finalContent, $Utf8NoBomEncoding) - } catch { - Stop-Function -Message "Unable to write file $realPath : $($_.Exception.Message)" -Continue - } + # Compare without empty lines to detect real changes + $originalNonEmpty = ($originalContent -split "[\r\n]+" | Where-Object { $_.Trim() }) -join "" + $newNonEmpty = ($newContent -split "[\r\n]+" | Where-Object { $_.Trim() }) -join "" + + if ($originalNonEmpty -ne $newNonEmpty) { + [System.IO.File]::WriteAllText($realPath, $newContent, $Utf8NoBomEncoding) + Write-Message -Level Verbose "Updated: $realPath" } else { - Write-Message -Level Verbose "No formatting changes needed for $realPath" + Write-Message -Level Verbose "No changes needed: $realPath" } } } From 21da25c076867558a2a75d35f08af8c500f7c2d2 Mon Sep 17 00:00:00 2001 From: Chrissy LeMaire Date: Sat, 9 Aug 2025 08:44:39 +0200 Subject: [PATCH 06/10] Add progress reporting to Invoke-DbatoolsFormatter Enhanced Invoke-DbatoolsFormatter to display progress when formatting multiple files, including status updates for each file, error handling, and a summary of processed and updated files. This improves user feedback during batch operations. --- public/Invoke-DbatoolsFormatter.ps1 | 40 ++++++++++++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/public/Invoke-DbatoolsFormatter.ps1 b/public/Invoke-DbatoolsFormatter.ps1 index 2c724b63cb3a..4380d83ad538 100644 --- a/public/Invoke-DbatoolsFormatter.ps1 +++ b/public/Invoke-DbatoolsFormatter.ps1 @@ -29,6 +29,11 @@ function Invoke-DbatoolsFormatter { PS C:\> Invoke-DbatoolsFormatter -Path C:\dbatools\public\Get-DbaDatabase.ps1 Reformats C:\dbatools\public\Get-DbaDatabase.ps1 to dbatools' standards + + .EXAMPLE + PS C:\> Get-ChildItem *.ps1 | Invoke-DbatoolsFormatter + + Reformats all .ps1 files in the current directory, showing progress for the batch operation #> [CmdletBinding()] param ( @@ -61,22 +66,44 @@ function Invoke-DbatoolsFormatter { if ($psVersionTable.Platform -ne 'Unix') { $OSEOL = "`r`n" } + + # Collect all paths for progress tracking + $allPaths = @() } process { if (Test-FunctionInterrupt) { return } - foreach ($p in $Path) { + # Collect all paths from pipeline + $allPaths += $Path + } + end { + if (Test-FunctionInterrupt) { return } + + $totalFiles = $allPaths.Count + $currentFile = 0 + $processedFiles = 0 + $updatedFiles = 0 + + foreach ($p in $allPaths) { + $currentFile++ + try { $realPath = (Resolve-Path -Path $p -ErrorAction Stop).Path } catch { + Write-Progress -Activity "Formatting PowerShell files" -Status "Error resolving path: $p" -PercentComplete (($currentFile / $totalFiles) * 100) -CurrentOperation "File $currentFile of $totalFiles" Stop-Function -Message "Cannot find or resolve $p" -Continue + continue } # Skip directories if (Test-Path -Path $realPath -PathType Container) { + Write-Progress -Activity "Formatting PowerShell files" -Status "Skipping directory: $realPath" -PercentComplete (($currentFile / $totalFiles) * 100) -CurrentOperation "File $currentFile of $totalFiles" Write-Message -Level Verbose "Skipping directory: $realPath" continue } + $fileName = Split-Path -Leaf $realPath + Write-Progress -Activity "Formatting PowerShell files" -Status "Processing: $fileName" -PercentComplete (($currentFile / $totalFiles) * 100) -CurrentOperation "File $currentFile of $totalFiles" + $originalContent = Get-Content -Path $realPath -Raw -Encoding UTF8 $content = $originalContent @@ -157,9 +184,20 @@ function Invoke-DbatoolsFormatter { if ($originalNonEmpty -ne $newNonEmpty) { [System.IO.File]::WriteAllText($realPath, $newContent, $Utf8NoBomEncoding) Write-Message -Level Verbose "Updated: $realPath" + $updatedFiles++ } else { Write-Message -Level Verbose "No changes needed: $realPath" } + + $processedFiles++ } + + # Complete the progress bar + Write-Progress -Activity "Formatting PowerShell files" -Status "Complete" -PercentComplete 100 -CurrentOperation "Processed $processedFiles files, updated $updatedFiles" + Start-Sleep -Milliseconds 500 # Brief pause to show completion + Write-Progress -Activity "Formatting PowerShell files" -Completed + + # Summary message + Write-Message -Level Verbose "Formatting complete: Processed $processedFiles files, updated $updatedFiles files" } } \ No newline at end of file From 41a9c68c9335c8c7f4a43943ed140cd522854419 Mon Sep 17 00:00:00 2001 From: Chrissy LeMaire Date: Sat, 9 Aug 2025 08:47:43 +0200 Subject: [PATCH 07/10] Fix whitespace in test scripts Removed trailing spaces and standardized whitespace in Get-DbaDbMailConfig.Tests.ps1 and Get-DbaDbRecoveryModel.Tests.ps1 for improved code consistency. --- tests/Get-DbaDbMailConfig.Tests.ps1 | 4 ++-- tests/Get-DbaDbRecoveryModel.Tests.ps1 | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/Get-DbaDbMailConfig.Tests.ps1 b/tests/Get-DbaDbMailConfig.Tests.ps1 index 44660a34c637..74c21ca1b18d 100644 --- a/tests/Get-DbaDbMailConfig.Tests.ps1 +++ b/tests/Get-DbaDbMailConfig.Tests.ps1 @@ -15,7 +15,7 @@ Describe $CommandName -Tag UnitTests { $expectedParameters = $TestConfig.CommonParameters $expectedParameters += @( "SqlInstance", - "SqlCredential", + "SqlCredential", "Name", "InputObject", "EnableException" @@ -56,7 +56,7 @@ Describe $CommandName -Tag IntegrationTests { $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. } diff --git a/tests/Get-DbaDbRecoveryModel.Tests.ps1 b/tests/Get-DbaDbRecoveryModel.Tests.ps1 index 4db903aedbac..8994117dc546 100644 --- a/tests/Get-DbaDbRecoveryModel.Tests.ps1 +++ b/tests/Get-DbaDbRecoveryModel.Tests.ps1 @@ -15,7 +15,7 @@ Describe $CommandName -Tag UnitTests { $expectedParameters = $TestConfig.CommonParameters $expectedParameters += @( "SqlInstance", - "SqlCredential", + "SqlCredential", "RecoveryModel", "Database", "ExcludeDatabase", From 9ca2b1ef02874ecf5ca63268073615261f3e6ead Mon Sep 17 00:00:00 2001 From: Chrissy LeMaire Date: Sat, 9 Aug 2025 09:53:31 +0200 Subject: [PATCH 08/10] Normalize whitespace and formatting in test scripts This commit standardizes whitespace, indentation, and minor formatting across multiple Pester test scripts for dbatools commands. No functional changes were made; these updates improve code consistency and readability. --- tests/Get-DbaDbMail.Tests.ps1 | 4 ++-- tests/Get-DbaDbMailAccount.Tests.ps1 | 2 +- tests/Get-DbaDbMailServer.Tests.ps1 | 4 ++-- tests/Get-DbaDbMemoryUsage.Tests.ps1 | 2 +- tests/Get-DbaDbMirror.Tests.ps1 | 2 +- tests/Get-DbaDbPageInfo.Tests.ps1 | 16 ++++++++-------- tests/Get-DbaDbRoleMember.Tests.ps1 | 2 +- tests/Get-DbaDbSequence.Tests.ps1 | 12 ++++++------ tests/Get-DbaDbServiceBrokerService.Tests.ps1 | 7 +++---- tests/Get-DbaDbSharePoint.Tests.ps1 | 2 +- tests/Get-DbaDbState.Tests.ps1 | 8 ++++---- tests/Get-DbaDbSynonym.Tests.ps1 | 4 ++-- tests/Get-DbaDbTable.Tests.ps1 | 18 +++++++++--------- tests/Get-DbaDbTrigger.Tests.ps1 | 2 +- tests/Get-DbaDbUdf.Tests.ps1 | 2 +- tests/Get-DbaDbView.Tests.ps1 | 2 +- 16 files changed, 44 insertions(+), 45 deletions(-) diff --git a/tests/Get-DbaDbMail.Tests.ps1 b/tests/Get-DbaDbMail.Tests.ps1 index 0dcd38813263..df64e390c44c 100644 --- a/tests/Get-DbaDbMail.Tests.ps1 +++ b/tests/Get-DbaDbMail.Tests.ps1 @@ -1,7 +1,7 @@ #Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } param( $ModuleName = "dbatools", - $CommandName = "Get-DbaDbMail", # Static command name for dbatools + $CommandName = "Get-DbaDbMail", # Static command name for dbatools $PSDefaultParameterValues = $TestConfig.Defaults ) @@ -66,4 +66,4 @@ Describe $CommandName -Tag IntegrationTests { } } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbMailAccount.Tests.ps1 b/tests/Get-DbaDbMailAccount.Tests.ps1 index 542df6ce45e1..9530310f948c 100644 --- a/tests/Get-DbaDbMailAccount.Tests.ps1 +++ b/tests/Get-DbaDbMailAccount.Tests.ps1 @@ -132,4 +132,4 @@ Describe $CommandName -Tag IntegrationTests { $results | Should -BeNullOrEmpty } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbMailServer.Tests.ps1 b/tests/Get-DbaDbMailServer.Tests.ps1 index 21219150d6f9..ab138433a782 100644 --- a/tests/Get-DbaDbMailServer.Tests.ps1 +++ b/tests/Get-DbaDbMailServer.Tests.ps1 @@ -36,7 +36,7 @@ Describe $CommandName -Tag IntegrationTests { # 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 @@ -114,4 +114,4 @@ Describe $CommandName -Tag IntegrationTests { $accountFilterResults | Should -Not -BeNullOrEmpty } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbMemoryUsage.Tests.ps1 b/tests/Get-DbaDbMemoryUsage.Tests.ps1 index 4c7b6ebe456a..0c29c1dc525c 100644 --- a/tests/Get-DbaDbMemoryUsage.Tests.ps1 +++ b/tests/Get-DbaDbMemoryUsage.Tests.ps1 @@ -55,4 +55,4 @@ Describe $CommandName -Tag IntegrationTests { $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 363eb4dc7ee8..ecd9781bffba 100644 --- a/tests/Get-DbaDbMirror.Tests.ps1 +++ b/tests/Get-DbaDbMirror.Tests.ps1 @@ -39,7 +39,7 @@ Describe $CommandName -Tag IntegrationTests { # 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 diff --git a/tests/Get-DbaDbPageInfo.Tests.ps1 b/tests/Get-DbaDbPageInfo.Tests.ps1 index 49fa77081086..3ba9e9711dc2 100644 --- a/tests/Get-DbaDbPageInfo.Tests.ps1 +++ b/tests/Get-DbaDbPageInfo.Tests.ps1 @@ -34,10 +34,10 @@ 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" - + # Clean up any existing connections $splatStopProcess = @{ SqlInstance = $TestConfig.instance2 @@ -46,7 +46,7 @@ Describe $CommandName -Tag IntegrationTests { 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)") @@ -63,27 +63,27 @@ Describe $CommandName -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 { # 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" { 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 } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbRoleMember.Tests.ps1 b/tests/Get-DbaDbRoleMember.Tests.ps1 index 9a1cc4ab71a6..43d423bae97d 100644 --- a/tests/Get-DbaDbRoleMember.Tests.ps1 +++ b/tests/Get-DbaDbRoleMember.Tests.ps1 @@ -106,4 +106,4 @@ Describe $CommandName -Tag IntegrationTests { $result.Role | Select-Object -Unique | Should -Not -Contain "db_owner" } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbSequence.Tests.ps1 b/tests/Get-DbaDbSequence.Tests.ps1 index d59ae9de22cd..0d9f8e97dfe7 100644 --- a/tests/Get-DbaDbSequence.Tests.ps1 +++ b/tests/Get-DbaDbSequence.Tests.ps1 @@ -1,7 +1,7 @@ #Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } param( $ModuleName = "dbatools", - $CommandName = "Get-DbaDbSequence", # Static command name for dbatools + $CommandName = "Get-DbaDbSequence", # Static command name for dbatools $PSDefaultParameterValues = $TestConfig.Defaults ) @@ -41,7 +41,7 @@ Describe $CommandName -Tag IntegrationTests { $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 $newDbName = "dbatoolsci_newdb_$random" $newDbName2 = "dbatoolsci_newdb2_$random" - + # Create the objects. $newDb, $newDb2 = New-DbaDatabase -SqlInstance $server -Name $newDbName, $newDbName2 @@ -52,7 +52,7 @@ Describe $CommandName -Tag IntegrationTests { Schema = "Schema_$random" } $sequence = New-DbaDbSequence @splatSequence1 - + $splatSequence2 = @{ SqlInstance = $server Database = $newDbName @@ -60,7 +60,7 @@ Describe $CommandName -Tag IntegrationTests { Schema = "Schema2_$random" } $sequence2 = New-DbaDbSequence @splatSequence2 - + $splatSequence3 = @{ SqlInstance = $server Database = $newDbName @@ -68,7 +68,7 @@ Describe $CommandName -Tag IntegrationTests { Schema = "Schema2_$random" } $sequence3 = New-DbaDbSequence @splatSequence3 - + $splatSequence4 = @{ SqlInstance = $server Database = $newDbName @@ -76,7 +76,7 @@ Describe $CommandName -Tag IntegrationTests { Schema = "Schema_$random" } $sequence4 = New-DbaDbSequence @splatSequence4 - + $splatSequence5 = @{ SqlInstance = $server Database = $newDbName2 diff --git a/tests/Get-DbaDbServiceBrokerService.Tests.ps1 b/tests/Get-DbaDbServiceBrokerService.Tests.ps1 index cc1221e3817b..1f8f25865d6d 100644 --- a/tests/Get-DbaDbServiceBrokerService.Tests.ps1 +++ b/tests/Get-DbaDbServiceBrokerService.Tests.ps1 @@ -45,8 +45,7 @@ Describe $CommandName -Tag IntegrationTests { $null = $server.Query("DROP SERVICE $servicename", "tempdb") $null = $server.Query("DROP QUEUE $queuename", "tempdb") $null = $server.Query("DROP PROCEDURE $procname", "tempdb") - } - catch { + } catch { # Suppress errors during cleanup } } @@ -55,8 +54,8 @@ Describe $CommandName -Tag IntegrationTests { BeforeAll { $splatServiceBroker = @{ SqlInstance = $TestConfig.instance2 - Database = "tempdb" - ExcludeSystemService = $true + Database = "tempdb" + ExcludeSystemService = $true } $results = Get-DbaDbServiceBrokerService @splatServiceBroker } diff --git a/tests/Get-DbaDbSharePoint.Tests.ps1 b/tests/Get-DbaDbSharePoint.Tests.ps1 index 14781ece5e2b..2803cb0831d0 100644 --- a/tests/Get-DbaDbSharePoint.Tests.ps1 +++ b/tests/Get-DbaDbSharePoint.Tests.ps1 @@ -56,7 +56,7 @@ Describe $CommandName -Tag IntegrationTests { # 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" - + if (Test-Path -Path $bacpac) { $sqlpackage = (Get-Command sqlpackage -ErrorAction Ignore).Source if (-not $sqlpackage) { diff --git a/tests/Get-DbaDbState.Tests.ps1 b/tests/Get-DbaDbState.Tests.ps1 index 5abcfd95148e..6e57dfab9c1a 100644 --- a/tests/Get-DbaDbState.Tests.ps1 +++ b/tests/Get-DbaDbState.Tests.ps1 @@ -43,14 +43,14 @@ Describe $CommandName -Tag IntegrationTests { $db6 = "dbatoolsci_dbstate_multi" $db7 = "dbatoolsci_dbstate_rw" $db8 = "dbatoolsci_dbstate_ro" - + $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") @@ -59,7 +59,7 @@ Describe $CommandName -Tag 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 @@ -84,7 +84,7 @@ Describe $CommandName -Tag IntegrationTests { Force = $true } $null = Set-DbaDbState @splatSetState - + $splatRemoveDbCleanup = @{ SqlInstance = $TestConfig.instance2 Database = $db1, $db2, $db3, $db4, $db5, $db6, $db7, $db8 diff --git a/tests/Get-DbaDbSynonym.Tests.ps1 b/tests/Get-DbaDbSynonym.Tests.ps1 index fbf9b4415b74..9b6a99b48027 100644 --- a/tests/Get-DbaDbSynonym.Tests.ps1 +++ b/tests/Get-DbaDbSynonym.Tests.ps1 @@ -1,7 +1,7 @@ #Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } param( $ModuleName = "dbatools", - $CommandName = "Get-DbaDbSynonym", # Static command name for dbatools + $CommandName = "Get-DbaDbSynonym", # Static command name for dbatools $PSDefaultParameterValues = $TestConfig.Defaults ) @@ -41,7 +41,7 @@ Describe $CommandName -Tag IntegrationTests { # 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 diff --git a/tests/Get-DbaDbTable.Tests.ps1 b/tests/Get-DbaDbTable.Tests.ps1 index 4cb439e4e7d0..57e0a1b0d333 100644 --- a/tests/Get-DbaDbTable.Tests.ps1 +++ b/tests/Get-DbaDbTable.Tests.ps1 @@ -36,37 +36,37 @@ 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)" $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 { # 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 } - + It "Gets the table when you specify the database" { (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 diff --git a/tests/Get-DbaDbTrigger.Tests.ps1 b/tests/Get-DbaDbTrigger.Tests.ps1 index aaa8346fdb42..f8396dbe9e3e 100644 --- a/tests/Get-DbaDbTrigger.Tests.ps1 +++ b/tests/Get-DbaDbTrigger.Tests.ps1 @@ -108,4 +108,4 @@ CREATE TRIGGER dbatoolsci_safety $results | Should -BeNullOrEmpty } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbUdf.Tests.ps1 b/tests/Get-DbaDbUdf.Tests.ps1 index 4c1c40b61653..185eebea7812 100644 --- a/tests/Get-DbaDbUdf.Tests.ps1 +++ b/tests/Get-DbaDbUdf.Tests.ps1 @@ -107,4 +107,4 @@ END; { Get-DbaDbUdf -SqlInstance $TestConfig.instance2 -ExcludeDatabase master -ExcludeSystemUdf } | Should -Not -Throw } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbView.Tests.ps1 b/tests/Get-DbaDbView.Tests.ps1 index 0a6e2c37aed0..16e73a995868 100644 --- a/tests/Get-DbaDbView.Tests.ps1 +++ b/tests/Get-DbaDbView.Tests.ps1 @@ -1,7 +1,7 @@ #Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } param( $ModuleName = "dbatools", - $CommandName = "Get-DbaDbView", # Static command name for dbatools + $CommandName = "Get-DbaDbView", # Static command name for dbatools $PSDefaultParameterValues = $TestConfig.Defaults ) From 7aa43431edc870b2c4a7ceb959c09bc77ef32d5c Mon Sep 17 00:00:00 2001 From: Chrissy LeMaire Date: Mon, 11 Aug 2025 06:37:11 +0200 Subject: [PATCH 09/10] Refactor and streamline integration tests for several commands Refactored integration tests for Get-DbaDbObjectTrigger, Get-DbaDbRestoreHistory, Get-DbaDbSequence, Get-DbaDbSharePoint, and Get-DbaDbUserDefinedTableType. Changes include improved variable naming, use of splatting for command parameters, removal of redundant comments, consolidation of repeated code, and more consistent assertions. These updates enhance readability, maintainability, and reliability of the test suites. --- tests/Get-DbaDbObjectTrigger.Tests.ps1 | 80 ++++--------- tests/Get-DbaDbRestoreHistory.Tests.ps1 | 113 +++++++++--------- tests/Get-DbaDbSequence.Tests.ps1 | 65 ++-------- tests/Get-DbaDbSharePoint.Tests.ps1 | 39 ++---- tests/Get-DbaDbUserDefinedTableType.Tests.ps1 | 46 ++++--- 5 files changed, 132 insertions(+), 211 deletions(-) diff --git a/tests/Get-DbaDbObjectTrigger.Tests.ps1 b/tests/Get-DbaDbObjectTrigger.Tests.ps1 index 6952eae5c02e..71c1d86901cd 100644 --- a/tests/Get-DbaDbObjectTrigger.Tests.ps1 +++ b/tests/Get-DbaDbObjectTrigger.Tests.ps1 @@ -35,10 +35,10 @@ Describe $CommandName -Tag IntegrationTests { # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. $PSDefaultParameterValues['*-Dba*:EnableException'] = $true - $dbname = "dbatoolsci_addtriggertoobject" - $tablename = "dbo.dbatoolsci_trigger" + $dbname = "dbatoolsci_addtriggertoobject" + $tablename = "dbo.dbatoolsci_trigger" $triggertablename = "dbatoolsci_triggerontable" - $triggertable = @" + $triggertable = @" CREATE TRIGGER $triggertablename ON $tablename AFTER INSERT @@ -48,9 +48,9 @@ CREATE TRIGGER $triggertablename END "@ - $viewname = "dbo.dbatoolsci_view" + $viewname = "dbo.dbatoolsci_view" $triggerviewname = "dbatoolsci_triggeronview" - $triggerview = @" + $triggerview = @" CREATE TRIGGER $triggerviewname ON $viewname INSTEAD OF INSERT @@ -73,7 +73,6 @@ CREATE TRIGGER $triggerviewname # 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 @@ -87,172 +86,135 @@ CREATE TRIGGER $triggerviewname BeforeAll { $results = Get-DbaDbObjectTrigger -SqlInstance $TestConfig.instance2 -ExcludeDatabase $systemDbs.Name | Where-Object Name -eq "dbatoolsci_triggerontable" } - It "Gets results" { $results | Should -Not -Be $null } - It "Should be enabled" { $results.isenabled | Should -Be $true } - It "Should have text of Trigger" { - $results.TextBody | Should -BeLike "*dbatoolsci_trigger table*" + $results.TextBody | Should -BeLike '*dbatoolsci_trigger table*' } } - Context "Gets Table Trigger when using -Database" { BeforeAll { $results = Get-DbaDbObjectTrigger -SqlInstance $TestConfig.instance2 -Database $dbname | Where-Object Name -eq "dbatoolsci_triggerontable" } - It "Gets results" { $results | Should -Not -Be $null } - It "Should be enabled" { $results.isenabled | Should -Be $true } - It "Should have text of Trigger" { - $results.TextBody | Should -BeLike "*dbatoolsci_trigger table*" + $results.TextBody | Should -BeLike '*dbatoolsci_trigger table*' } } - Context "Gets Table Trigger passing table object using pipeline" { BeforeAll { $results = Get-DbaDbTable -SqlInstance $TestConfig.instance2 -Database $dbname -Table "dbatoolsci_trigger" | Get-DbaDbObjectTrigger } - It "Gets results" { $results | Should -Not -Be $null } - It "Should be enabled" { $results.isenabled | Should -Be $true } - It "Should have text of Trigger" { - $results.TextBody | Should -BeLike "*dbatoolsci_trigger table*" + $results.TextBody | Should -BeLike '*dbatoolsci_trigger table*' } } - Context "Gets View Trigger" { BeforeAll { $results = Get-DbaDbObjectTrigger -SqlInstance $TestConfig.instance2 -ExcludeDatabase $systemDbs.Name | Where-Object Name -eq "dbatoolsci_triggeronview" } - It "Gets results" { $results | Should -Not -Be $null } - It "Should be enabled" { $results.isenabled | Should -Be $true } - It "Should have text of Trigger" { - $results.TextBody | Should -BeLike "*dbatoolsci_view view*" + $results.TextBody | Should -BeLike '*dbatoolsci_view view*' } } - Context "Gets View Trigger when using -Database" { BeforeAll { $results = Get-DbaDbObjectTrigger -SqlInstance $TestConfig.instance2 -Database $dbname | Where-Object Name -eq "dbatoolsci_triggeronview" } - It "Gets results" { $results | Should -Not -Be $null } - It "Should be enabled" { $results.isenabled | Should -Be $true } - It "Should have text of Trigger" { - $results.TextBody | Should -BeLike "*dbatoolsci_view view*" + $results.TextBody | Should -BeLike '*dbatoolsci_view view*' } } - Context "Gets View Trigger passing table object using pipeline" { BeforeAll { $results = Get-DbaDbView -SqlInstance $TestConfig.instance2 -Database $dbname -ExcludeSystemView | Get-DbaDbObjectTrigger } - It "Gets results" { $results | Should -Not -Be $null } - It "Should be enabled" { $results.isenabled | Should -Be $true } - It "Should have text of Trigger" { - $results.TextBody | Should -BeLike "*dbatoolsci_view view*" + $results.TextBody | Should -BeLike '*dbatoolsci_view view*' } } - Context "Gets Table and View Trigger passing both objects using pipeline" { 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 + $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" { - $results.Status.Count | Should -Be 2 + It "Should return two triggers" { + $results.Count | Should -Be 2 } } - Context "Gets All types Trigger when using -Type" { BeforeAll { $results = Get-DbaDbObjectTrigger -SqlInstance $TestConfig.instance2 -Database $dbname -Type All } - It "Gets results" { $results | Should -Not -Be $null } - - It "Should be only one" { - $results.Status.Count | Should -Be 2 + It "Should return two triggers" { + $results.Count | Should -Be 2 } } - Context "Gets only Table Trigger when using -Type" { 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.Status.Count | Should -Be 1 + $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" { 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.Status.Count | Should -Be 1 + $results.Count | Should -Be 1 } - - It "Should have text of Trigger" { + It "Should be a View trigger" { $results.Parent.GetType().Name | Should -Be "View" } } diff --git a/tests/Get-DbaDbRestoreHistory.Tests.ps1 b/tests/Get-DbaDbRestoreHistory.Tests.ps1 index 166510319105..34e9197301f9 100644 --- a/tests/Get-DbaDbRestoreHistory.Tests.ps1 +++ b/tests/Get-DbaDbRestoreHistory.Tests.ps1 @@ -9,7 +9,7 @@ Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig Describe $CommandName -Tag UnitTests { - Context "Parameter validation" { + Context "Validate parameters" { BeforeAll { $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } $expectedParameters = $TestConfig.CommonParameters @@ -19,9 +19,9 @@ Describe $CommandName -Tag UnitTests { "Database", "ExcludeDatabase", "Since", + "RestoreType", "Force", "Last", - "RestoreType", "EnableException" ) } @@ -30,33 +30,57 @@ Describe $CommandName -Tag UnitTests { Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } + } Describe $CommandName -Tag IntegrationTests { + BeforeAll { # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. $PSDefaultParameterValues['*-Dba*:EnableException'] = $true - # For all the backups that we want to clean up after the test, we create a directory that we can delete at the end. - # Other files can be written there as well, maybe we change the name of that variable later. But for now we focus on backups. - $backupPath = "$($TestConfig.Temp)\$CommandName-$(Get-Random)" - $null = New-Item -Path $backupPath -ItemType Directory - - # Set variables. They are available in all the It blocks. $random = Get-Random $dbname1 = "dbatoolsci_restorehistory1_$random" $dbname2 = "dbatoolsci_restorehistory2_$random" - # Create the objects. $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 - $fullBackup = Backup-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname1 -Type Full -Path $backupPath - $diffBackup = Backup-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname1 -Type Diff -Path $backupPath - $logBackup = Backup-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname1 -Type Log -Path $backupPath - $null = Restore-DbaDatabase -SqlInstance $TestConfig.instance2 -Path $diffBackup.BackupPath, $logBackup.BackupPath -DatabaseName $dbname1 -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 + + $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') @@ -66,46 +90,40 @@ Describe $CommandName -Tag IntegrationTests { # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. $PSDefaultParameterValues['*-Dba*:EnableException'] = $true - # Cleanup all created object. $null = Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname1, $dbname2 | Remove-DbaDatabase -Confirm:$false - - # Remove the backup directory. - Remove-Item -Path $backupPath -Recurse -ErrorAction SilentlyContinue + 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" { 1 | Should -Be 1 } } - Context "Get last restore history for single database" { BeforeAll { $results = @(Get-DbaDbRestoreHistory -SqlInstance $TestConfig.instance2 -Database $dbname2 -Last) } It "Results holds 1 object" { - $results.Status.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" $results[0].From | Should -Be "$($TestConfig.appveyorlabrepo)\singlerestore\singlerestore.bak" $results[0].To | Should -Match "\\rsh_pre_$dbname2" } } - Context "Get last restore history for multiple database" { BeforeAll { $results = @(Get-DbaDbRestoreHistory -SqlInstance $TestConfig.instance2 -Database $dbname1, $dbname2 -Last) } It "Results holds 2 objects" { - $results.Status.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" $results[1].RestoreType | Should -Be "Log" @@ -115,26 +133,26 @@ Describe $CommandName -Tag IntegrationTests { ($results | Where-Object Database -eq $dbname2).To | Should -Match "\\rsh_pre_$dbname2" } } - Context "Get complete restore history for multiple database" { BeforeAll { $results = @(Get-DbaDbRestoreHistory -SqlInstance $TestConfig.instance2 -Database $dbname1, $dbname2) } It "Results holds correct number of objects" { - $results.Status.Count | Should -Be 6 + $results.Count | Should -Be 6 } - It "Should return the full restore with the correct properties" { @($results | Where-Object Database -eq $dbname1).Count | Should -Be 4 @($results | Where-Object Database -eq $dbname2).Count | Should -Be 2 } } - Context "return object properties" { - It "has the correct properties" { + BeforeAll { $results = Get-DbaDbRestoreHistory -SqlInstance $TestConfig.instance2 -Database $dbname1, $dbname2 $result = $results[0] + } + + It "has the correct properties" { $ExpectedProps = @( "ComputerName", "InstanceName", @@ -158,6 +176,7 @@ Describe $CommandName -Tag IntegrationTests { "HasErrors" ) ($result.PsObject.Properties.Name | Sort-Object) | Should -Be ($ExpectedProps | Sort-Object) + $ExpectedPropsDefault = @( "ComputerName", "InstanceName", @@ -173,39 +192,23 @@ Describe $CommandName -Tag IntegrationTests { ($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" { - $splatFullRestore = @{ - SqlInstance = $TestConfig.instance2 - Database = $dbname1, $dbname2 - RestoreType = "Database" - } - $results = Get-DbaDbRestoreHistory @splatFullRestore - $results.Status.Count | Should -Be 4 - @($results | Where-Object RestoreType -eq "Database").Count | Should -Be 4 + $results = Get-DbaDbRestoreHistory -SqlInstance $TestConfig.instance2 -Database $dbname1, $dbname2 -RestoreType Database + $results.Count | Should -Be 4 + @($results | Where-Object RestoreType -eq Database).Count | Should -Be 4 } It "returns the correct history records for diffential restore" { - $splatDiffRestore = @{ - SqlInstance = $TestConfig.instance2 - Database = $dbname1 - RestoreType = "Differential" - } - $results = Get-DbaDbRestoreHistory @splatDiffRestore + $results = Get-DbaDbRestoreHistory -SqlInstance $TestConfig.instance2 -Database $dbname1 -RestoreType Differential $results.Database | Should -Be $dbname1 - $results.RestoreType | Should -Be "Differential" + $results.RestoreType | Should -Be Differential } It "returns the correct history records for log restore" { - $splatLogRestore = @{ - SqlInstance = $TestConfig.instance2 - Database = $dbname1 - RestoreType = "Log" - } - $results = Get-DbaDbRestoreHistory @splatLogRestore + $results = Get-DbaDbRestoreHistory -SqlInstance $TestConfig.instance2 -Database $dbname1 -RestoreType Log $results.Database | Should -Be $dbname1 - $results.RestoreType | Should -Be "Log" + $results.RestoreType | Should -Be Log } } } \ No newline at end of file diff --git a/tests/Get-DbaDbSequence.Tests.ps1 b/tests/Get-DbaDbSequence.Tests.ps1 index 0d9f8e97dfe7..1f7c277e23fa 100644 --- a/tests/Get-DbaDbSequence.Tests.ps1 +++ b/tests/Get-DbaDbSequence.Tests.ps1 @@ -36,54 +36,17 @@ Describe $CommandName -Tag IntegrationTests { # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. $PSDefaultParameterValues['*-Dba*:EnableException'] = $true - # Set variables. They are available in all the It blocks. $random = Get-Random $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 $newDbName = "dbatoolsci_newdb_$random" $newDbName2 = "dbatoolsci_newdb2_$random" - - # Create the objects. $newDb, $newDb2 = New-DbaDatabase -SqlInstance $server -Name $newDbName, $newDbName2 - $splatSequence1 = @{ - SqlInstance = $server - Database = $newDbName - Sequence = "Sequence1_$random" - Schema = "Schema_$random" - } - $sequence = New-DbaDbSequence @splatSequence1 - - $splatSequence2 = @{ - SqlInstance = $server - Database = $newDbName - Sequence = "Sequence2_$random" - Schema = "Schema2_$random" - } - $sequence2 = New-DbaDbSequence @splatSequence2 - - $splatSequence3 = @{ - SqlInstance = $server - Database = $newDbName - Sequence = "Sequence1_$random" - Schema = "Schema2_$random" - } - $sequence3 = New-DbaDbSequence @splatSequence3 - - $splatSequence4 = @{ - SqlInstance = $server - Database = $newDbName - Sequence = "Sequence2_$random" - Schema = "Schema_$random" - } - $sequence4 = New-DbaDbSequence @splatSequence4 - - $splatSequence5 = @{ - SqlInstance = $server - Database = $newDbName2 - Sequence = "Sequence1_$random" - Schema = "Schema_$random" - } - $sequence5 = New-DbaDbSequence @splatSequence5 + $sequence = New-DbaDbSequence -SqlInstance $server -Database $newDbName -Sequence "Sequence1_$random" -Schema "Schema_$random" + $sequence2 = New-DbaDbSequence -SqlInstance $server -Database $newDbName -Sequence "Sequence2_$random" -Schema "Schema2_$random" + $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') @@ -93,30 +56,28 @@ Describe $CommandName -Tag IntegrationTests { # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. $PSDefaultParameterValues['*-Dba*:EnableException'] = $true - # Cleanup all created objects. - $null = $newDb, $newDb2 | Remove-DbaDatabase -Confirm:$false -ErrorAction SilentlyContinue + $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.Status.Count | Should -BeGreaterOrEqual 5 + $sequence.Count | Should -BeGreaterOrEqual 5 } It "finds a sequence in a single database" { $sequence = Get-DbaDbSequence -SqlInstance $server -Database $newDbName $sequence.Parent.Name | Select-Object -Unique | Should -Be $newDbName - $sequence.Status.Count | Should -Be 4 + $sequence.Count | Should -Be 4 } It "finds a sequence in a single database by schema only" { $sequence = Get-DbaDbSequence -SqlInstance $server -Database $newDbName -Schema "Schema2_$random" $sequence.Parent.Name | Select-Object -Unique | Should -Be $newDbName $sequence.Schema | Select-Object -Unique | Should -Be "Schema2_$random" - $sequence.Status.Count | Should -Be 2 + $sequence.Count | Should -Be 2 } It "finds a sequence in a single database by schema and by name" { @@ -124,26 +85,26 @@ Describe $CommandName -Tag IntegrationTests { $sequence.Parent.Name | Select-Object -Unique | Should -Be $newDbName $sequence.Name | Select-Object -Unique | Should -Be "Sequence1_$random" $sequence.Schema | Select-Object -Unique | Should -Be "Schema_$random" - $sequence.Status.Count | Should -Be 1 + $sequence.Count | Should -Be 1 } It "finds a sequence on an instance by name only" { $sequence = Get-DbaDbSequence -SqlInstance $server -Sequence "Sequence1_$random" $sequence.Name | Select-Object -Unique | Should -Be "Sequence1_$random" - $sequence.Status.Count | Should -Be 3 + $sequence.Count | Should -Be 3 } It "finds a sequence on an instance by schema only" { $sequence = Get-DbaDbSequence -SqlInstance $server -Schema "Schema2_$random" $sequence.Schema | Select-Object -Unique | Should -Be "Schema2_$random" - $sequence.Status.Count | Should -Be 2 + $sequence.Count | Should -Be 2 } It "finds a sequence on an instance by schema and name" { $sequence = Get-DbaDbSequence -SqlInstance $server -Schema "Schema_$random" -Sequence "Sequence1_$random" $sequence.Schema | Select-Object -Unique | Should -Be "Schema_$random" $sequence.Name | Select-Object -Unique | Should -Be "Sequence1_$random" - $sequence.Status.Count | Should -Be 2 + $sequence.Count | Should -Be 2 } It "supports piping databases" { diff --git a/tests/Get-DbaDbSharePoint.Tests.ps1 b/tests/Get-DbaDbSharePoint.Tests.ps1 index 2803cb0831d0..ad9db93648ce 100644 --- a/tests/Get-DbaDbSharePoint.Tests.ps1 +++ b/tests/Get-DbaDbSharePoint.Tests.ps1 @@ -5,9 +5,6 @@ param( $PSDefaultParameterValues = $TestConfig.Defaults ) -Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig - Describe $CommandName -Tag UnitTests { Context "Parameter validation" { BeforeAll { @@ -50,18 +47,19 @@ Describe $CommandName -Tag IntegrationTests { 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" - if (Test-Path -Path $bacpac) { $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 @@ -81,9 +79,6 @@ Describe $CommandName -Tag IntegrationTests { $skip = $true } - # Store skip value globally for use in It blocks - $global:skipIntegrationTests = $skip - # 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') } @@ -102,28 +97,10 @@ Describe $CommandName -Tag IntegrationTests { $results = Get-DbaDbSharePoint -SqlInstance $TestConfig.instance2 } - It "Returns SharePoint_Admin_7c0c491d0e6f43858f75afa5399d49ab from in the SharePoint database list" -Skip:$global:skipIntegrationTests { - "SharePoint_Admin_7c0c491d0e6f43858f75afa5399d49ab" | Should -BeIn $results.Name - } - - It "Returns WSS_Logging from in the SharePoint database list" -Skip:$global:skipIntegrationTests { - "WSS_Logging" | Should -BeIn $results.Name - } - - It "Returns SecureStoreService_20e1764876504335a6d8dd0b1937f4bf from in the SharePoint database list" -Skip:$global:skipIntegrationTests { - "SecureStoreService_20e1764876504335a6d8dd0b1937f4bf" | Should -BeIn $results.Name - } - - It "Returns DefaultWebApplicationDB from in the SharePoint database list" -Skip:$global:skipIntegrationTests { - "DefaultWebApplicationDB" | Should -BeIn $results.Name - } - - It "Returns SharePoint_Config_4c524cb90be44c6f906290fe3e34f2e0 from in the SharePoint database list" -Skip:$global:skipIntegrationTests { - "SharePoint_Config_4c524cb90be44c6f906290fe3e34f2e0" | Should -BeIn $results.Name - } - - It "Returns DefaultPowerPivotServiceApplicationDB-5b638361-c6fc-4ad9-b8ba-d05e63e48ac6 from in the SharePoint database list" -Skip:$global:skipIntegrationTests { - "DefaultPowerPivotServiceApplicationDB-5b638361-c6fc-4ad9-b8ba-d05e63e48ac6" | Should -BeIn $results.Name + foreach ($db in $spdb) { + 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-DbaDbUserDefinedTableType.Tests.ps1 b/tests/Get-DbaDbUserDefinedTableType.Tests.ps1 index f1f322bf6bff..ea7bc7017b5f 100644 --- a/tests/Get-DbaDbUserDefinedTableType.Tests.ps1 +++ b/tests/Get-DbaDbUserDefinedTableType.Tests.ps1 @@ -16,10 +16,10 @@ Describe $CommandName -Tag UnitTests { $expectedParameters += @( "SqlInstance", "SqlCredential", + "EnableException", "Database", "ExcludeDatabase", - "Type", - "EnableException" + "Type" ) } @@ -31,32 +31,50 @@ Describe $CommandName -Tag UnitTests { Describe $CommandName -Tag IntegrationTests { BeforeAll { + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + $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") + + # 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 TYPE $tabletypename", 'tempdb') - $null = $server.Query("DROP TYPE $tabletypename1", '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 + + $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 + $null = $server.Query("DROP TYPE $tableTypeName", "tempdb") + $null = $server.Query("DROP TYPE $tableTypeName1", "tempdb") + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } Context "Gets a Db User Defined Table Type" { BeforeAll { - $results = Get-DbaDbUserDefinedTableType -SqlInstance $TestConfig.instance2 -Database tempdb -Type $tabletypename + $splatUserDefinedTableType = @{ + SqlInstance = $TestConfig.instance2 + Database = "tempdb" + Type = $tableTypeName + } + $results = Get-DbaDbUserDefinedTableType @splatUserDefinedTableType } It "Gets results" { $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" { @@ -64,9 +82,9 @@ Describe $CommandName -Tag IntegrationTests { } } - Context "Gets all the Db User Defined Table Type" { + Context "Gets all the Db User Defined Table Types" { BeforeAll { - $results = Get-DbaDbUserDefinedTableType -SqlInstance $TestConfig.instance2 -Database tempdb + $results = Get-DbaDbUserDefinedTableType -SqlInstance $TestConfig.instance2 -Database "tempdb" } It "Gets results" { From 1ffd92db41070372de6b1c5c5ac9c1289f8eb503 Mon Sep 17 00:00:00 2001 From: Chrissy LeMaire Date: Mon, 11 Aug 2025 07:16:36 +0200 Subject: [PATCH 10/10] Let's try with Sonnet Standardized usage of double quotes for PSDefaultParameterValues keys and removed unnecessary comments. Improved cleanup in AfterAll by adding -ErrorAction SilentlyContinue to DROP TYPE queries. Fixed assertions to check the correct property for result counts. --- tests/Get-DbaDbUserDefinedTableType.Tests.ps1 | 24 +++++++------------ 1 file changed, 9 insertions(+), 15 deletions(-) diff --git a/tests/Get-DbaDbUserDefinedTableType.Tests.ps1 b/tests/Get-DbaDbUserDefinedTableType.Tests.ps1 index ea7bc7017b5f..f07a3608c0d1 100644 --- a/tests/Get-DbaDbUserDefinedTableType.Tests.ps1 +++ b/tests/Get-DbaDbUserDefinedTableType.Tests.ps1 @@ -31,8 +31,7 @@ Describe $CommandName -Tag UnitTests { Describe $CommandName -Tag IntegrationTests { BeforeAll { - # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. - $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 $tableTypeName = "dbatools_$(Get-Random)" @@ -40,19 +39,14 @@ Describe $CommandName -Tag IntegrationTests { $server.Query("CREATE TYPE $tableTypeName AS TABLE([column1] INT NULL)", "tempdb") $server.Query("CREATE TYPE $tableTypeName1 AS TABLE([column1] INT NULL)", "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') + $PSDefaultParameterValues.Remove("*-Dba*:EnableException") } AfterAll { - # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. - $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true - $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 - $null = $server.Query("DROP TYPE $tableTypeName", "tempdb") - $null = $server.Query("DROP TYPE $tableTypeName1", "tempdb") - - # As this is the last block we do not need to reset the $PSDefaultParameterValues. + $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" { @@ -78,13 +72,13 @@ Describe $CommandName -Tag IntegrationTests { } It "Should have a count of 1" { - $results.Status.Count | Should -BeExactly 1 + $results.Count | Should -BeExactly 1 } } - Context "Gets all the Db User Defined Table Types" { + Context "Gets all the Db User Defined Table Type" { BeforeAll { - $results = Get-DbaDbUserDefinedTableType -SqlInstance $TestConfig.instance2 -Database "tempdb" + $results = Get-DbaDbUserDefinedTableType -SqlInstance $TestConfig.instance2 -Database tempdb } It "Gets results" { @@ -92,7 +86,7 @@ Describe $CommandName -Tag IntegrationTests { } It "Should have a count of 2" { - $results.Status.Count | Should -BeExactly 2 + $results.Count | Should -BeExactly 2 } } } \ No newline at end of file