From ee627651ab4ff32bc17c0490143dc4609f1edd84 Mon Sep 17 00:00:00 2001 From: Chrissy LeMaire Date: Tue, 5 Nov 2024 21:05:22 +0100 Subject: [PATCH] revert --- tests/Backup-DbaDatabase.Tests.ps1 | 605 +++++---------------- tests/Export-DbaRegServer.Tests.ps1 | 263 ++++----- tests/Export-DbaScript.Tests.ps1 | 117 ++-- tests/Find-DbaAgentJob.Tests.ps1 | 178 ++---- tests/Find-DbaBackup.Tests.ps1 | 222 +++----- tests/Find-DbaDbUnusedIndex.Tests.ps1 | 164 +++--- tests/Find-DbaStoredProcedure.Tests.ps1 | 91 ++-- tests/Find-DbaTrigger.Tests.ps1 | 93 +--- tests/Find-DbaView.Tests.ps1 | 85 +-- tests/Get-DbaAgentJob.Tests.ps1 | 114 ++-- tests/Get-DbaComputerCertificate.Tests.ps1 | 70 +-- tests/Get-DbaDbCompression.Tests.ps1 | 81 ++- 12 files changed, 716 insertions(+), 1367 deletions(-) diff --git a/tests/Backup-DbaDatabase.Tests.ps1 b/tests/Backup-DbaDatabase.Tests.ps1 index 112bda6e84..1ffcfdf525 100644 --- a/tests/Backup-DbaDatabase.Tests.ps1 +++ b/tests/Backup-DbaDatabase.Tests.ps1 @@ -1,80 +1,32 @@ -#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} -param( - $ModuleName = "dbatools", - $PSDefaultParameterValues = ($global:TestConfig = Get-TestConfig).Defaults -) - -Describe "Backup-DbaDatabase" -Tag "UnitTests" { - Context "Parameter validation" { - BeforeAll { - $command = Get-Command Backup-DbaDatabase - $expected = $TestConfig.CommonParameters - $expected += @( - "SqlInstance", - "SqlCredential", - "Database", - "ExcludeDatabase", - "Path", - "FilePath", - "IncrementPrefix", - "ReplaceInName", - "NoAppendDbNameInPath", - "CopyOnly", - "Type", - "InputObject", - "CreateFolder", - "FileCount", - "CompressBackup", - "Checksum", - "Verify", - "MaxTransferSize", - "BlockSize", - "BufferCount", - "AzureBaseUrl", - "AzureCredential", - "NoRecovery", - "BuildPath", - "WithFormat", - "Initialize", - "SkipTapeHeader", - "TimeStampFormat", - "IgnoreFileChecks", - "OutputScriptOnly", - "EncryptionAlgorithm", - "EncryptionCertificate", - "Description", - "EnableException", - "Verbose", - "Debug", - "ErrorAction", - "WarningAction", - "InformationAction", - "ProgressAction", - "ErrorVariable", - "WarningVariable", - "InformationVariable", - "OutVariable", - "OutBuffer", - "PipelineVariable", - "WhatIf", - "Confirm" - ) - } - - It "Has parameter: <_>" -ForEach $expected { - $command | Should -HaveParameter $PSItem - } - - It "Should have exactly the number of parameters" { - $params = $command.Parameters.Values.Name - Compare-Object -ReferenceObject $expected -DifferenceObject $params | Should -BeNullOrEmpty +$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan +$global:TestConfig = Get-TestConfig + +Describe "$CommandName Unit Tests" -Tag 'UnitTests' { + Context "Validate parameters" { + [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } + [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'ExcludeDatabase', 'Path', 'FilePath', 'ReplaceInName', 'NoAppendDbNameInPath', 'CopyOnly', 'Type', 'InputObject', 'CreateFolder', 'FileCount', 'CompressBackup', 'Checksum', 'Verify', 'MaxTransferSize', 'BlockSize', 'BufferCount', 'AzureBaseUrl', 'AzureCredential', 'NoRecovery', 'BuildPath', 'WithFormat', 'Initialize', 'SkipTapeHeader', 'TimeStampFormat', 'IgnoreFileChecks', 'OutputScriptOnly', 'EnableException', 'EncryptionAlgorithm', 'EncryptionCertificate', 'IncrementPrefix', 'Description' + $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 "Backup-DbaDatabase" -Tag "IntegrationTests" { +Describe "$commandname Integration Tests" -Tags "IntegrationTests" { + + Context "Properly restores a database on the local drive using Path" { + $results = Backup-DbaDatabase -SqlInstance $TestConfig.instance1 -BackupDirectory C:\temp\backups + It "Should return a database name, specifically master" { + ($results.DatabaseName -contains 'master') | Should -Be $true + } + It "Should return successful restore" { + $results.ForEach{ $_.BackupComplete | Should -Be $true } + } + } + BeforeAll { - $DestBackupDir = "C:\Temp\backups" + $DestBackupDir = 'C:\Temp\backups' $random = Get-Random $DestDbRandom = "dbatools_ci_backupdbadatabase$random" if (-Not(Test-Path $DestBackupDir)) { @@ -90,48 +42,15 @@ Describe "Backup-DbaDatabase" -Tag "IntegrationTests" { Remove-Item "$DestBackupDir\*" -Force -Recurse } } - - Context "When restoring a database on the local drive using Path" { - BeforeEach { - $splatBackup = @{ - SqlInstance = $TestConfig.instance1 - BackupDirectory = "C:\temp\backups" - } - $results = Backup-DbaDatabase @splatBackup - } - It "Should return a database name, specifically master" { - ($results.DatabaseName -contains "master") | Should -Be $true - } - It "Should return successful restore" { - $results.ForEach{ $PSItem.BackupComplete | Should -Be $true } - } - } - - Context "When database and exclude match" { - BeforeEach { - $splatBackup = @{ - SqlInstance = $TestConfig.instance1 - BackupDirectory = $DestBackupDir - Database = "master" - Exclude = "master" - } - $results = Backup-DbaDatabase @splatBackup - } + Context "Should not backup if database and exclude match" { + $results = Backup-DbaDatabase -SqlInstance $TestConfig.instance1 -BackupDirectory $DestBackupDir -Database master -Exclude master It "Should not return object" { $results | Should -Be $null } } - Context "When no database found to backup" { - BeforeEach { - $splatBackup = @{ - SqlInstance = $TestConfig.instance1 - BackupDirectory = $DestBackupDir - Database = "AliceDoesntDBHereAnyMore" - WarningVariable = warnvar - } - $results = Backup-DbaDatabase @splatBackup 3> $null - } + Context "No database found to backup should raise warning and null output" { + $results = Backup-DbaDatabase -SqlInstance $TestConfig.instance1 -BackupDirectory $DestBackupDir -Database AliceDoesntDBHereAnyMore -WarningVariable warnvar 3> $null It "Should not return object" { $results | Should -Be $null } @@ -140,15 +59,8 @@ Describe "Backup-DbaDatabase" -Tag "IntegrationTests" { } } - Context "When backing up a single database" { - BeforeEach { - $splatBackup = @{ - SqlInstance = $TestConfig.instance1 - BackupDirectory = $DestBackupDir - Database = "master" - } - $results = Backup-DbaDatabase @splatBackup - } + Context "Database should backup 1 database" { + $results = Backup-DbaDatabase -SqlInstance $TestConfig.instance1 -BackupDirectory $DestBackupDir -Database master It "Database backup object count Should Be 1" { $results.DatabaseName.Count | Should -Be 1 $results.BackupComplete | Should -Be $true @@ -158,31 +70,16 @@ Describe "Backup-DbaDatabase" -Tag "IntegrationTests" { } } - Context "When backing up multiple databases" { - BeforeEach { - $splatBackup = @{ - SqlInstance = $TestConfig.instance1 - BackupDirectory = $DestBackupDir - Database = "master", "msdb" - } - $results = Backup-DbaDatabase @splatBackup - } + Context "Database should backup 2 databases" { + $results = Backup-DbaDatabase -SqlInstance $TestConfig.instance1 -BackupDirectory $DestBackupDir -Database master, msdb It "Database backup object count Should Be 2" { $results.DatabaseName.Count | Should -Be 2 $results.BackupComplete | Should -Be @($true, $true) } } - Context "When specifying path and filename" { - BeforeEach { - $splatBackup = @{ - SqlInstance = $TestConfig.instance1 - BackupDirectory = $DestBackupDir - Database = "master" - BackupFileName = "PesterTest.bak" - } - $results = Backup-DbaDatabase @splatBackup - } + Context "Should take path and filename" { + $results = Backup-DbaDatabase -SqlInstance $TestConfig.instance1 -BackupDirectory $DestBackupDir -Database master -BackupFileName 'PesterTest.bak' It "Should report it has backed up to the path with the correct name" { $results.Fullname | Should -BeLike "$DestBackupDir*PesterTest.bak" } @@ -191,16 +88,8 @@ Describe "Backup-DbaDatabase" -Tag "IntegrationTests" { } } - Context "When using pipes for database parameter" { - BeforeEach { - $splatBackup = @{ - SqlInstance = $TestConfig.instance1 - Database = "master" - BackupFileName = "PesterTest.bak" - BackupDirectory = $DestBackupDir - } - $results = Get-DbaDatabase -SqlInstance $TestConfig.instance1 | Backup-DbaDatabase @splatBackup - } + Context "Database parameter works when using pipes (fixes #5044)" { + $results = Get-DbaDatabase -SqlInstance $TestConfig.instance1 | Backup-DbaDatabase -Database master -BackupFileName PesterTest.bak -BackupDirectory $DestBackupDir It "Should report it has backed up to the path with the correct name" { $results.Fullname | Should -BeLike "$DestBackupDir*PesterTest.bak" } @@ -209,161 +98,94 @@ Describe "Backup-DbaDatabase" -Tag "IntegrationTests" { } } - Context "When excluding databases using pipes" { - BeforeEach { - $splatBackup = @{ - SqlInstance = $TestConfig.instance1 - ExcludeDatabase = "master", "tempdb", "msdb", "model" - } - $results = Get-DbaDatabase -SqlInstance $TestConfig.instance1 | Backup-DbaDatabase @splatBackup - } + Context "ExcludeDatabase parameter works when using pipes (fixes #5044)" { + $results = Get-DbaDatabase -SqlInstance $TestConfig.instance1 | Backup-DbaDatabase -ExcludeDatabase master, tempdb, msdb, model It "Should report it has backed up to the path with the correct name" { - $results.DatabaseName | Should -Not -Contain "master" - $results.DatabaseName | Should -Not -Contain "tempdb" - $results.DatabaseName | Should -Not -Contain "msdb" - $results.DatabaseName | Should -Not -Contain "model" + $results.DatabaseName | Should -Not -Contain master + $results.DatabaseName | Should -Not -Contain tempdb + $results.DatabaseName | Should -Not -Contain msdb + $results.DatabaseName | Should -Not -Contain model } } - Context "When handling non-existent backup paths" { - BeforeEach { - $MissingPathTrailing = "$DestBackupDir\Missing1\Awol2\" - $MissingPath = "$DestBackupDir\Missing1\Awol2" - $null = Backup-DbaDatabase -SqlInstance $TestConfig.instance1 -Database "master" -BackupDirectory $MissingPath -WarningVariable warnvar *>$null - } + Context "Handling backup paths that don't exist" { + $MissingPathTrailing = "$DestBackupDir\Missing1\Awol2\" + $MissingPath = "$DestBackupDir\Missing1\Awol2" + $null = Backup-DbaDatabase -SqlInstance $TestConfig.instance1 -Database master -BackupDirectory $MissingPath -WarningVariable warnvar *>$null It "Should warn and fail if path doesn't exist and BuildPath not set" { $warnvar | Should -BeLike "*$MissingPath*" } - BeforeEach { - $splatBackup = @{ - SqlInstance = $TestConfig.instance1 - Database = "master" - BackupDirectory = $MissingPathTrailing - BuildPath = $true - } - $results = Backup-DbaDatabase @splatBackup - } + # $MissingPathTrailing has a trailing slash but we normalize the path before doing the actual backup + $results = Backup-DbaDatabase -SqlInstance $TestConfig.instance1 -Database master -BackupDirectory $MissingPathTrailing -BuildPath It "Should have backed up to $MissingPath" { $results.BackupFolder | Should -Be "$MissingPath" - $results.Path | Should -Not -BeLike "*\\*" + $results.Path | Should -Not -BeLike '*\\*' } } - Context "When using CreateFolder switch" { - BeforeEach { - $splatBackup = @{ - SqlInstance = $TestConfig.instance1 - Database = "master" - BackupDirectory = $DestBackupDir - CreateFolder = $true - } - $results = Backup-DbaDatabase @splatBackup - } + Context "CreateFolder switch should append the databasename to the backup path" { + $results = Backup-DbaDatabase -SqlInstance $TestConfig.instance1 -Database master -BackupDirectory $DestBackupDir -CreateFolder It "Should have appended master to the backup path" { $results.BackupFolder | Should -Be "$DestBackupDir\master" } } - Context "When using CreateFolder switch with striping" { - BeforeEach { - $backupPaths = "$DestBackupDir\stripewithdb1", "$DestBackupDir\stripewithdb2" - $splatBackup = @{ - SqlInstance = $TestConfig.instance1 - Database = "master" - BackupDirectory = $backupPaths - CreateFolder = $true - } - $results = Backup-DbaDatabase @splatBackup - } + Context "CreateFolder switch should append the databasename to the backup path even when striping" { + $backupPaths = "$DestBackupDir\stripewithdb1", "$DestBackupDir\stripewithdb2" + $results = Backup-DbaDatabase -SqlInstance $TestConfig.instance1 -Database master -BackupDirectory $backupPaths -CreateFolder It "Should have appended master to all backup paths" { foreach ($path in $results.BackupFolder) { - ($results.BackupFolder | Sort-Object) | Should -Be ($backupPaths | Sort-Object | ForEach-Object { [IO.Path]::Combine($PSItem, "master") }) + ($results.BackupFolder | Sort-Object) | Should -Be ($backupPaths | Sort-Object | ForEach-Object { [IO.Path]::Combine($_, 'master') }) } } } - Context "When using a fully qualified path" { - BeforeEach { - $splatBackup = @{ - SqlInstance = $TestConfig.instance1 - Database = "master" - BackupDirectory = "c:\temp" - BackupFileName = "$DestBackupDir\PesterTest2.bak" - } - $results = Backup-DbaDatabase @splatBackup - } + + Context "A fully qualified path should override a backupfolder" { + $results = Backup-DbaDatabase -SqlInstance $TestConfig.instance1 -Database master -BackupDirectory c:\temp -BackupFileName "$DestBackupDir\PesterTest2.bak" It "Should report backed up to $DestBackupDir" { $results.FullName | Should -BeLike "$DestBackupDir\PesterTest2.bak" - $results.BackupFolder | Should Not Be "c:\temp" + $results.BackupFolder | Should Not Be 'c:\temp' } - It "Should have backed up to $DestBackupDir\PesterTest2.bak" { + It "Should have backuped up to $DestBackupDir\PesterTest2.bak" { Test-Path "$DestBackupDir\PesterTest2.bak" | Should -Be $true } } - Context "When multiple backup folders specified" { - BeforeEach { - $backupPaths = "$DestBackupDir\stripe1", "$DestBackupDir\stripe2", "$DestBackupDir\stripe3" - $null = New-Item -Path $backupPaths -ItemType Directory - $splatBackup = @{ - SqlInstance = $TestConfig.instance1 - Database = "master" - BackupDirectory = $backupPaths - } - $results = Backup-DbaDatabase @splatBackup - } + Context "Should stripe if multiple backupfolders specified" { + $backupPaths = "$DestBackupDir\stripe1", "$DestBackupDir\stripe2", "$DestBackupDir\stripe3" + $null = New-Item -Path $backupPaths -ItemType Directory + + + $results = Backup-DbaDatabase -SqlInstance $TestConfig.instance1 -Database master -BackupDirectory $backupPaths It "Should have created 3 backups" { $results.BackupFilesCount | Should -Be 3 } It "Should have written to all 3 folders" { $backupPaths | ForEach-Object { - $PSItem | Should -BeIn ($results.BackupFolder) + $_ | Should -BeIn ($results.BackupFolder) } } It "Should have written files with extensions" { foreach ($path in $results.BackupFile) { - [IO.Path]::GetExtension($PSItem) | Should -Be ".bak" - } - } - BeforeEach { - $splatBackup = @{ - SqlInstance = $TestConfig.instance1 - Database = "master" - BackupDirectory = $backupPaths - FileCount = 2 + [IO.Path]::GetExtension($path) | Should -Be '.bak' } - $results = Backup-DbaDatabase @splatBackup } + # Assure that striping logic favours -BackupDirectory and not -Filecount + $results = Backup-DbaDatabase -SqlInstance $TestConfig.instance1 -Database master -BackupDirectory $backupPaths -FileCount 2 It "Should have created 3 backups, even when FileCount is different" { $results.BackupFilesCount | Should -Be 3 } } - Context "When file count is greater than 1" { - BeforeEach { - $splatBackup = @{ - SqlInstance = $TestConfig.instance1 - Database = "master" - BackupDirectory = $DestBackupDir - FileCount = 3 - } - $results = Backup-DbaDatabase @splatBackup - } + Context "Should stripe on filecount > 1" { + $results = Backup-DbaDatabase -SqlInstance $TestConfig.instance1 -Database master -BackupDirectory $DestBackupDir -FileCount 3 It "Should have created 3 backups" { $results.BackupFilesCount | Should -Be 3 } } - Context "When building filenames" { - BeforeEach { - $splatBackup = @{ - SqlInstance = $TestConfig.instance1 - Database = "master" - BackupDirectory = $DestBackupDir - FileCount = 3 - } - $results = Backup-DbaDatabase @splatBackup - } + Context "Should build filenames properly" { It "Should have 1 period in file extension" { foreach ($path in $results.BackupFile) { [IO.Path]::GetExtension($path) | Should -Not -BeLike '*..*' @@ -371,18 +193,9 @@ Describe "Backup-DbaDatabase" -Tag "IntegrationTests" { } } - Context "When IncrementPrefix is set" { - BeforeEach { - $fileCount = 3 - $splatBackup = @{ - SqlInstance = $TestConfig.instance1 - Database = "master" - BackupDirectory = $DestBackupDir - FileCount = $fileCount - IncrementPrefix = $true - } - $results = Backup-DbaDatabase @splatBackup - } + Context "Should prefix the filenames when IncrementPrefix set" { + $fileCount = 3 + $results = Backup-DbaDatabase -SqlInstance $TestConfig.instance1 -Database master -BackupDirectory $DestBackupDir -FileCount $fileCount -IncrementPrefix It "Should have created 3 backups" { $results.BackupFilesCount | Should -Be 3 } @@ -393,135 +206,78 @@ Describe "Backup-DbaDatabase" -Tag "IntegrationTests" { } } - Context "When no backup path is specified" { - BeforeEach { - $splatBackup = @{ - SqlInstance = $TestConfig.instance1 - Database = "master" - BackupFileName = "PesterTest.bak" - } - $results = Backup-DbaDatabase @splatBackup - $DefaultPath = (Get-DbaDefaultPath -SqlInstance $TestConfig.instance1).Backup - } - It "Should report it has backed up to the path with the correct name" { + Context "Should Backup to default path if none specified" { + $results = Backup-DbaDatabase -SqlInstance $TestConfig.instance1 -Database master -BackupFileName 'PesterTest.bak' + $DefaultPath = (Get-DbaDefaultPath -SqlInstance $TestConfig.instance1).Backup + It "Should report it has backed up to the path with the corrrect name" { $results.Fullname | Should -BeLike "$DefaultPath*PesterTest.bak" } - It "Should have backed up to the path with the correct name" { + It "Should have backed up to the path with the corrrect name" { Test-Path "$DefaultPath\PesterTest.bak" | Should -Be $true } } - Context "When verifying backup" { - BeforeEach { - $splatBackup = @{ - SqlInstance = $TestConfig.instance1 - Database = "master" - Type = "full" - Verify = $true - } - $b = Backup-DbaDatabase @splatBackup - } + Context "Test backup verification" { It "Should perform a full backup and verify it" { - $b.BackupComplete | Should -Be $true - $b.Verified | Should -Be $true + $b = Backup-DbaDatabase -SqlInstance $TestConfig.instance1 -Database master -Type full -Verify + $b.BackupComplete | Should -Be $True + $b.Verified | Should -Be $True $b.count | Should -Be 1 } - It -Skip $true "Should perform a diff backup and verify it" { - $splatBackup = @{ - SqlInstance = $TestConfig.instance1 - Database = "backuptest" - Type = "diff" - Verify = $true - } - $b = Backup-DbaDatabase @splatBackup - $b.BackupComplete | Should -Be $true - $b.Verified | Should -Be $true - } - It -Skip $true "Should perform a log backup and verify it" { - $splatBackup = @{ - SqlInstance = $TestConfig.instance1 - Database = "backuptest" - Type = "log" - Verify = $true - } - $b = Backup-DbaDatabase @splatBackup - $b.BackupComplete | Should -Be $true - $b.Verified | Should -Be $true + It -Skip "Should perform a diff backup and verify it" { + $b = Backup-DbaDatabase -SqlInstance $TestConfig.instance1 -Database backuptest -Type diff -Verify + $b.BackupComplete | Should -Be $True + $b.Verified | Should -Be $True + } + It -Skip "Should perform a log backup and verify it" { + $b = Backup-DbaDatabase -SqlInstance $TestConfig.instance1 -Database backuptest -Type log -Verify + $b.BackupComplete | Should -Be $True + $b.Verified | Should -Be $True } } - Context "When piping backup to restore" { - BeforeEach { - $null = Restore-DbaDatabase -SqlInstance $TestConfig.instance1 -Path "$($TestConfig.appveyorlabrepo)\singlerestore\singlerestore.bak" -DatabaseName "dbatoolsci_singlerestore" - $splatBackup = @{ - SqlInstance = $TestConfig.instance1 - BackupDirectory = $DestBackupDir - Database = "dbatoolsci_singlerestore" - } - $results = Backup-DbaDatabase @splatBackup | Restore-DbaDatabase -SqlInstance $TestConfig.instance2 -DatabaseName $DestDbRandom -TrustDbBackupHistory -ReplaceDbNameInFile - } + Context "Backup can pipe to restore" { + $null = Restore-DbaDatabase -SqlInstance $TestConfig.instance1 -Path "$($TestConfig.appveyorlabrepo)\singlerestore\singlerestore.bak" -DatabaseName "dbatoolsci_singlerestore" + $results = Backup-DbaDatabase -SqlInstance $TestConfig.instance1 -BackupDirectory $DestBackupDir -Database "dbatoolsci_singlerestore" | Restore-DbaDatabase -SqlInstance $TestConfig.instance2 -DatabaseName $DestDbRandom -TrustDbBackupHistory -ReplaceDbNameInFile It "Should return successful restore" { $results.RestoreComplete | Should -Be $true } } - Context "When Backup-DbaDatabase can take pipe input" { - BeforeEach { - $splatBackup = @{ - SqlInstance = $TestConfig.instance1 - Database = "master" - Confirm = $false - WarningVariable = warnvar - } - $results = Get-DbaDatabase -SqlInstance $TestConfig.instance1 -Database "master" | Backup-DbaDatabase @splatBackup 3> $null - } + Context "Test Backup-DbaDatabase can take pipe input" { + $results = Get-DbaDatabase -SqlInstance $TestConfig.instance1 -Database master | Backup-DbaDatabase -confirm:$false -WarningVariable warnvar 3> $null It "Should not warn" { $warnvar | Should -BeNullOrEmpty } It "Should Complete Successfully" { $results.BackupComplete | Should -Be $true } + } - Context "When handling NUL as an input path" { - BeforeEach { - $splatBackup = @{ - SqlInstance = $TestConfig.instance1 - Database = "master" - BackupFileName = "NUL" - } - $results = Backup-DbaDatabase @splatBackup - } - It "Should return successful backup" { + Context "Should handle NUL as an input path" { + $results = Backup-DbaDatabase -SqlInstance $TestConfig.instance1 -Database master -BackupFileName NUL + It "Should return succesful backup" { $results.BackupComplete | Should -Be $true } It "Should have backed up to NUL:" { - $results.FullName[0] | Should -Be "NUL:" + $results.FullName[0] | Should -Be 'NUL:' } } - Context "When OutputScriptOnly is specified" { - BeforeEach { - $splatBackup = @{ - SqlInstance = $TestConfig.instance1 - Database = "master" - BackupFileName = "c:\notexists\file.bak" - OutputScriptOnly = $true - } - $results = Backup-DbaDatabase @splatBackup - } + Context "Should only output a T-SQL String if OutputScriptOnly specified" { + $results = Backup-DbaDatabase -SqlInstance $TestConfig.instance1 -Database master -BackupFileName c:\notexists\file.bak -OutputScriptOnly It "Should return a string" { - $results.GetType().ToString() | Should -Be "System.String" + $results.GetType().ToString() | Should -Be 'System.String' } It "Should return BACKUP DATABASE [master] TO DISK = N'c:\notexists\file.bak' WITH NOFORMAT, NOINIT, NOSKIP, REWIND, NOUNLOAD, STATS = 1" { $results | Should -Be "BACKUP DATABASE [master] TO DISK = N'c:\notexists\file.bak' WITH NOFORMAT, NOINIT, NOSKIP, REWIND, NOUNLOAD, STATS = 1" } } - Context "When handling an encrypted database with compression" { - BeforeEach { - $sqlencrypt = - @" + Context "Should handle an encrypted database when compression is specified" { + $sqlencrypt = + @" CREATE MASTER KEY ENCRYPTION BY PASSWORD = ''; go CREATE CERTIFICATE MyServerCert WITH SUBJECT = 'My DEK Certificate'; @@ -529,9 +285,9 @@ go CREATE DATABASE encrypted go "@ - $null = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Query $sqlencrypt -Database "Master" - $createdb = - @" + $null = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Query $sqlencrypt -Database Master + $createdb = + @" CREATE DATABASE ENCRYPTION KEY WITH ALGORITHM = AES_128 ENCRYPTION BY SERVER CERTIFICATE MyServerCert; @@ -540,128 +296,84 @@ ALTER DATABASE encrypted SET ENCRYPTION ON; GO "@ - $null = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Query $createdb -Database "encrypted" - } + $null = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Query $createdb -Database encrypted It "Should compress an encrypted db" { - $splatBackup = @{ - SqlInstance = $TestConfig.instance2 - Database = "encrypted" - Compress = $true - } - $results = Backup-DbaDatabase @splatBackup + $results = Backup-DbaDatabase -SqlInstance $TestConfig.instance2 -Database encrypted -Compress Invoke-Command2 -ComputerName $TestConfig.instance2 -ScriptBlock { Remove-Item -Path $args[0] } -ArgumentList $results.FullName - $results.script | Should -BeLike "*D, COMPRESSION,*" + $results.script | Should -BeLike '*D, COMPRESSION,*' } - AfterAll { - Remove-DbaDatabase -SqlInstance $TestConfig.instance2 -Database "encrypted" -confirm:$false - $sqldrop = - @" + Remove-DbaDatabase -SqlInstance $TestConfig.instance2 -Database encrypted -confirm:$false + $sqldrop = + @" drop certificate MyServerCert go drop master key go "@ - $null = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Query $sqldrop -Database "Master" - } + $null = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Query $sqldrop -Database Master } - Context "When applying custom TimeStamp" { - BeforeEach { - $splatBackup = @{ - SqlInstance = $TestConfig.instance1 - Database = "master" - BackupDirectory = $DestBackupDir - TimeStampFormat = "bobob" - } - $results = Backup-DbaDatabase @splatBackup - } - It "Should apply the correct custom Timestamp" { - ($results | Where-Object { $PSItem.BackupPath -like "*bobob*" }).count | Should -Be $results.Status.Count + Context "Custom TimeStamp" { + # Test relies on DateFormat bobob returning bobob as the values aren't interpreted, check here in case .Net rules change + $results = Backup-DbaDatabase -SqlInstance $TestConfig.instance1 -Database master -BackupDirectory $DestBackupDir -TimeStampFormat bobob + It "Should apply the corect custom Timestamp" { + ($results | Where-Object { $_.BackupPath -like '*bobob*' }).count | Should -Be $results.count } } - Context "When testing backup templating" { - BeforeEach { - $splatBackup = @{ - SqlInstance = $TestConfig.instance1 - Database = "master", "msdb" - BackupDirectory = "$DestBackupDir\dbname\instancename\backuptype\" - BackupFileName = "dbname-backuptype.bak" - ReplaceInName = $true - BuildPath = $true - } - $results = Backup-DbaDatabase @splatBackup - } + Context "Test Backup templating" { + $results = Backup-DbaDatabase -SqlInstance $TestConfig.instance1 -Database master, msdb -BackupDirectory $DestBackupDir\dbname\instancename\backuptype\ -BackupFileName dbname-backuptype.bak -ReplaceInName -BuildPath It "Should have replaced the markers" { $results[0].BackupPath | Should -BeLike "$DestBackupDir\master\$(($TestConfig.instance1).split('\')[1])\Full\master-Full.bak" $results[1].BackupPath | Should -BeLike "$DestBackupDir\msdb\$(($TestConfig.instance1).split('\')[1])\Full\msdb-Full.bak" } } - Context "When testing backup templating with piped db object" { - BeforeEach { - $splatBackup = @{ - BackupDirectory = "$DestBackupDir\db2\dbname\instancename\backuptype\" - BackupFileName = "dbname-backuptype.bak" - ReplaceInName = $true - BuildPath = $true - } - $results = Get-DbaDatabase -SqlInstance $TestConfig.instance1 -Database "master", "msdb" | Backup-DbaDatabase @splatBackup - } + Context "Test Backup templating when db object piped in issue 8100" { + $results = Get-DbaDatabase -SqlInstance $TestConfig.instance1 -Database master,msdb | Backup-DbaDatabase -BackupDirectory $DestBackupDir\db2\dbname\instancename\backuptype\ -BackupFileName dbname-backuptype.bak -ReplaceInName -BuildPath It "Should have replaced the markers" { $results[0].BackupPath | Should -BeLike "$DestBackupDir\db2\master\$(($TestConfig.instance1).split('\')[1])\Full\master-Full.bak" $results[1].BackupPath | Should -BeLike "$DestBackupDir\db2\msdb\$(($TestConfig.instance1).split('\')[1])\Full\msdb-Full.bak" } } - Context "When testing backup encryption with certificate" { - BeforeEach { - $securePass = ConvertTo-SecureString "estBackupDir\master\script:instance1).split('\')[1])\Full\master-Full.bak" -AsPlainText -Force - New-DbaDbMasterKey -SqlInstance $TestConfig.instance2 -Database "Master" -SecurePassword $securePass -confirm:$false -ErrorAction SilentlyContinue - $cert = New-DbaDbCertificate -SqlInstance $TestConfig.instance2 -Database "master" -Name "BackupCertt" -Subject "BackupCertt" - $splatBackup = @{ - SqlInstance = $TestConfig.instance2 - Database = "master" - EncryptionAlgorithm = "AES128" - EncryptionCertificate = "BackupCertt" - BackupFileName = "encryptiontest.bak" - Description = "Encrypted backup" - } - $encBackupResults = Backup-DbaDatabase @splatBackup - } + Context "Test Backup Encryption with Certificate" { + $securePass = ConvertTo-SecureString "estBackupDir\master\script:instance1).split('\')[1])\Full\master-Full.bak" -AsPlainText -Force + New-DbaDbMasterKey -SqlInstance $TestConfig.instance2 -Database Master -SecurePassword $securePass -confirm:$false -ErrorAction SilentlyContinue + $cert = New-DbaDbCertificate -SqlInstance $TestConfig.instance2 -Database master -Name BackupCertt -Subject BackupCertt + $encBackupResults = Backup-DbaDatabase -SqlInstance $TestConfig.instance2 -Database master -EncryptionAlgorithm AES128 -EncryptionCertificate BackupCertt -BackupFileName 'encryptiontest.bak' -Description "Encrypted backup" + Invoke-Command2 -ComputerName $TestConfig.instance2 -ScriptBlock { Remove-Item -Path $args[0] } -ArgumentList $encBackupResults.FullName It "Should encrypt the backup" { $encBackupResults.EncryptorType | Should Be "CERTIFICATE" $encBackupResults.KeyAlgorithm | Should Be "aes_128" } - AfterAll { - Remove-DbaDbCertificate -SqlInstance $TestConfig.instance2 -Database "master" -Certificate "BackupCertt" -Confirm:$false - Remove-DbaDbMasterKey -SqlInstance $TestConfig.instance2 -Database "Master" -confirm:$false - } + Remove-DbaDbCertificate -SqlInstance $TestConfig.instance2 -Database master -Certificate BackupCertt -Confirm:$false + Remove-DbaDbMasterKey -SqlInstance $TestConfig.instance2 -Database Master -confirm:$false } # Context "Test Backup Encryption with Asymmetric Key" { - # $key = New-DbaDbAsymmetricKey -SqlInstance $TestConfig.instance2 -Database "master" -Name "BackupKey" - # $encBackupResults = Backup-DbaDatabase -SqlInstance $TestConfig.instance2 -Database "master" -EncryptionAlgorithm "AES128" -EncryptionKey "BackupKey" + # $key = New-DbaDbAsymmetricKey -SqlInstance $TestConfig.instance2 -Database master -Name BackupKey + # $encBackupResults = Backup-DbaDatabase -SqlInstance $TestConfig.instance2 -Database master -EncryptionAlgorithm AES128 -EncryptionKey BackupKey # It "Should encrypt the backup" { # $encBackupResults.EncryptorType | Should Be "CERTIFICATE" # $encBackupResults.KeyAlgorithm | Should Be "aes_128" # } - # remove-DbaDbCertificate -SqlInstance $TestConfig.instance2 -Database "master" -Certificate "BackupCertt" -Confirm:$false + # remove-DbaDbCertificate -SqlInstance $TestConfig.instance2 -Database master -Certificate BackupCertt -Confirm:$false # } if ($env:azurepasswd) { - Context "When backing up to Azure" { + Context "Azure works" { BeforeAll { Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database "dbatoolsci_azure" | Remove-DbaDatabase -Confirm:$false $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 - if (Get-DbaCredential -SqlInstance $TestConfig.instance2 -Name "[$TestConfig.azureblob]") { + if (Get-DbaCredential -SqlInstance $TestConfig.instance2 -Name "[$TestConfig.azureblob]" ) { $sql = "DROP CREDENTIAL [$TestConfig.azureblob]" $server.Query($sql) } $sql = "CREATE CREDENTIAL [$TestConfig.azureblob] WITH IDENTITY = N'SHARED ACCESS SIGNATURE', SECRET = N'$env:azurepasswd'" $server.Query($sql) $server.Query("CREATE DATABASE dbatoolsci_azure") - if (Get-DbaCredential -SqlInstance $TestConfig.instance2 -name "dbatools_ci") { + if (Get-DbaCredential -SqlInstance $TestConfig.instance2 -name dbatools_ci) { $sql = "DROP CREDENTIAL dbatools_ci" $server.Query($sql) } @@ -673,31 +385,16 @@ go $server.Query("DROP CREDENTIAL [$TestConfig.azureblob]") } It "backs up to Azure properly using SHARED ACCESS SIGNATURE" { - $splatBackup = @{ - SqlInstance = $TestConfig.instance2 - AzureBaseUrl = $TestConfig.azureblob - Database = "dbatoolsci_azure" - BackupFileName = "dbatoolsci_azure.bak" - WithFormat = $true - } - $results = Backup-DbaDatabase @splatBackup - $results.Database | Should -Be "dbatoolsci_azure" - $results.DeviceType | Should -Be "URL" - $results.BackupFile | Should -Be "dbatoolsci_azure.bak" + $results = Backup-DbaDatabase -SqlInstance $TestConfig.instance2 -AzureBaseUrl $TestConfig.azureblob -Database dbatoolsci_azure -BackupFileName dbatoolsci_azure.bak -WithFormat + $results.Database | Should -Be 'dbatoolsci_azure' + $results.DeviceType | Should -Be 'URL' + $results.BackupFile | Should -Be 'dbatoolsci_azure.bak' } It "backs up to Azure properly using legacy credential" { - $splatBackup = @{ - SqlInstance = $TestConfig.instance2 - AzureBaseUrl = $TestConfig.azureblob - Database = "dbatoolsci_azure" - BackupFileName = "dbatoolsci_azure2.bak" - WithFormat = $true - AzureCredential = "dbatools_ci" - } - $results = Backup-DbaDatabase @splatBackup - $results.Database | Should -Be "dbatoolsci_azure" - $results.DeviceType | Should -Be "URL" - $results.BackupFile | Should -Be "dbatoolsci_azure2.bak" + $results = Backup-DbaDatabase -SqlInstance $TestConfig.instance2 -AzureBaseUrl $TestConfig.azureblob -Database dbatoolsci_azure -BackupFileName dbatoolsci_azure2.bak -WithFormat -AzureCredential dbatools_ci + $results.Database | Should -Be 'dbatoolsci_azure' + $results.DeviceType | Should -Be 'URL' + $results.BackupFile | Should -Be 'dbatoolsci_azure2.bak' } } } diff --git a/tests/Export-DbaRegServer.Tests.ps1 b/tests/Export-DbaRegServer.Tests.ps1 index e2c1475d36..82062be11b 100644 --- a/tests/Export-DbaRegServer.Tests.ps1 +++ b/tests/Export-DbaRegServer.Tests.ps1 @@ -1,176 +1,153 @@ -#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } -param( - $ModuleName = "dbatools", - $PSDefaultParameterValues = ($global:TestConfig = Get-TestConfig).Defaults -) - -Describe "Export-DbaRegServer" -Tag "UnitTests" { - Context "Parameter validation" { - BeforeAll { - $command = Get-Command Export-DbaRegServer - $expected = $TestConfig.CommonParameters - $expected += @( - "SqlInstance", - "SqlCredential", - "InputObject", - "Path", - "FilePath", - "CredentialPersistenceType", - "Group", - "ExcludeGroup", - "Overwrite", - "EnableException" - ) - } - - It "Has parameter: <_>" -ForEach $expected { - $command | Should -HaveParameter $PSItem - } - - It "Should have exactly the number of expected parameters ($($expected.Count))" { - $hasParams = $command.Parameters.Values.Name - Compare-Object -ReferenceObject $expected -DifferenceObject $hasParams | Should -BeNullOrEmpty +$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan +$global:TestConfig = Get-TestConfig + +Describe "$CommandName Unit Tests" -Tags "UnitTests" { + Context "Validate parameters" { + It "Should only contain our specific parameters" { + [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } + [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'InputObject', 'Path', 'FilePath', 'CredentialPersistenceType', 'EnableException', 'Group', 'ExcludeGroup', 'Overwrite' + $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters + (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should -Be 0 } } } -Describe "Export-DbaRegServer" -Tag "IntegrationTests" { - BeforeAll { - $random = Get-Random - $newDirectory = "C:\temp-$random" +Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { + BeforeEach { + $srvName = "dbatoolsci-server1" + $group = "dbatoolsci-group1" + $regSrvName = "dbatoolsci-server12" + $regSrvDesc = "dbatoolsci-server123" - $splatServer1 = @{ - SqlInstance = $TestConfig.instance2 - ServerName = "dbatoolsci-server1" - Name = "dbatoolsci-server12" - Description = "dbatoolsci-server123" - } + $newGroup = Add-DbaRegServerGroup -SqlInstance $TestConfig.instance2 -Name $group + $newServer = Add-DbaRegServer -SqlInstance $TestConfig.instance2 -ServerName $srvName -Name $regSrvName -Description $regSrvDesc - $splatServer2 = @{ - SqlInstance = $TestConfig.instance2 - ServerName = "dbatoolsci-server2" - Name = "dbatoolsci-server21" - Description = "dbatoolsci-server321" - } + $srvName2 = "dbatoolsci-server2" + $group2 = "dbatoolsci-group2" + $regSrvName2 = "dbatoolsci-server21" + $regSrvDesc2 = "dbatoolsci-server321" - $splatServer3 = @{ - SqlInstance = $TestConfig.instance2 - ServerName = "dbatoolsci-server3" - Name = "dbatoolsci-server3" - Description = "dbatoolsci-server3desc" - } + $newGroup2 = Add-DbaRegServerGroup -SqlInstance $TestConfig.instance2 -Name $group2 + $newServer2 = Add-DbaRegServer -SqlInstance $TestConfig.instance2 -ServerName $srvName2 -Name $regSrvName2 -Description $regSrvDesc2 + + $regSrvName3 = "dbatoolsci-server3" + $srvName3 = "dbatoolsci-server3" + $regSrvDesc3 = "dbatoolsci-server3desc" - $group1 = Add-DbaRegServerGroup -SqlInstance $TestConfig.instance2 -Name "dbatoolsci-group1" - $group2 = Add-DbaRegServerGroup -SqlInstance $TestConfig.instance2 -Name "dbatoolsci-group2" + $newServer3 = Add-DbaRegServer -SqlInstance $TestConfig.instance2 -ServerName $srvName3 -Name $regSrvName3 -Description $regSrvDesc3 + + $random = Get-Random + $newDirectory = "C:\temp-$random" + } + AfterEach { + Get-DbaRegServer -SqlInstance $TestConfig.instance2 | Where-Object Name -Match dbatoolsci | Remove-DbaRegServer -Confirm:$false + Get-DbaRegServerGroup -SqlInstance $TestConfig.instance2 | Where-Object Name -Match dbatoolsci | Remove-DbaRegServerGroup -Confirm:$false + $results, $results2, $results3 | Remove-Item -ErrorAction Ignore + + Remove-Item $newDirectory -ErrorAction Ignore -Recurse -Force + } + + It "should create an xml file" { + $results = $newServer | Export-DbaRegServer + $results -is [System.IO.FileInfo] | Should -Be $true + $results.Extension -eq '.xml' | Should -Be $true + } - $server1 = Add-DbaRegServer @splatServer1 - $server2 = Add-DbaRegServer @splatServer2 - $server3 = Add-DbaRegServer @splatServer3 + It "should create a specific xml file when using Path" { + $results2 = $newGroup2 | Export-DbaRegServer -Path C:\temp + $results2 -is [System.IO.FileInfo] | Should -Be $true + $results2.FullName | Should -match 'C\:\\temp' + Get-Content -Path $results2 -Raw | Should -Match $group2 } - AfterAll { + It "creates an importable xml file" { + $results3 = $newServer3 | Export-DbaRegServer -Path C:\temp Get-DbaRegServer -SqlInstance $TestConfig.instance2 | Where-Object Name -Match dbatoolsci | Remove-DbaRegServer -Confirm:$false Get-DbaRegServerGroup -SqlInstance $TestConfig.instance2 | Where-Object Name -Match dbatoolsci | Remove-DbaRegServerGroup -Confirm:$false + $results4 = Import-DbaRegServer -SqlInstance $TestConfig.instance2 -Path $results3 + $newServer3.ServerName | Should -BeIn $results4.ServerName + $newServer3.Description | Should -BeIn $results4.Description + } - if (Test-Path $newDirectory) { - Remove-Item $newDirectory -Recurse -Force - } + It "Create an xml file using FilePath" { + $outputFileName = "C:\temp\dbatoolsci-regsrvr-export-$random.xml" + $results = Export-DbaRegServer -SqlInstance $TestConfig.instance2 -FilePath $outputFileName + $results -is [System.IO.FileInfo] | Should -Be $true + $results.FullName | Should -Be $outputFileName } - Context "When exporting registered servers" { - It "Creates an xml file" { - $results = $server1 | Export-DbaRegServer - $results | Should -BeOfType [System.IO.FileInfo] - $results.Extension | Should -Be '.xml' - } + It "Create a regsrvr file using the FilePath alias OutFile" { + $outputFileName = "C:\temp\dbatoolsci-regsrvr-export-$random.regsrvr" + $results = Export-DbaRegServer -SqlInstance $TestConfig.instance2 -OutFile $outputFileName + $results -is [System.IO.FileInfo] | Should -Be $true + $results.FullName | Should -Be $outputFileName + } - It "Creates a specific xml file when using Path" { - $results = $group2 | Export-DbaRegServer -Path C:\temp - $results | Should -BeOfType [System.IO.FileInfo] - $results.FullName | Should -Match 'C\:\\temp' - Get-Content -Path $results -Raw | Should -Match 'dbatoolsci-group2' - } + It "Try to create an invalid file using FilePath" { + $outputFileName = "C:\temp\dbatoolsci-regsrvr-export-$random.txt" + $results = Export-DbaRegServer -SqlInstance $TestConfig.instance2 -FilePath $outputFileName + $results.length | Should -Be 0 + } - It "Creates an importable xml file" { - $exportPath = $server3 | Export-DbaRegServer -Path C:\temp - Get-DbaRegServer -SqlInstance $TestConfig.instance2 | Where-Object Name -Match dbatoolsci | Remove-DbaRegServer -Confirm:$false - Get-DbaRegServerGroup -SqlInstance $TestConfig.instance2 | Where-Object Name -Match dbatoolsci | Remove-DbaRegServerGroup -Confirm:$false + It "Create an xml file using the FilePath alias FileName in a directory that does not yet exist" { + $outputFileName = "$newDirectory\dbatoolsci-regsrvr-export-$random.xml" + $results = Export-DbaRegServer -SqlInstance $TestConfig.instance2 -FileName $outputFileName + $results -is [System.IO.FileInfo] | Should -Be $true + $results.FullName | Should -Be $outputFileName + } - $importedServer = Import-DbaRegServer -SqlInstance $TestConfig.instance2 -Path $exportPath - $importedServer.ServerName | Should -Be $splatServer3.ServerName - $importedServer.Description | Should -Be $splatServer3.Description - } + It "Ensure the Overwrite param is working" { + $outputFileName = "C:\temp\dbatoolsci-regsrvr-export-$random.xml" + $results = Export-DbaRegServer -SqlInstance $TestConfig.instance2 -FilePath $outputFileName + $results -is [System.IO.FileInfo] | Should -Be $true + $results.FullName | Should -Be $outputFileName - It "Creates an xml file using FilePath" { - $outputFile = "C:\temp\dbatoolsci-regsrvr-export-$random.xml" - $results = Export-DbaRegServer -SqlInstance $TestConfig.instance2 -FilePath $outputFile - $results | Should -BeOfType [System.IO.FileInfo] - $results.FullName | Should -Be $outputFile - } + # test without -Overwrite + $invalidResults = Export-DbaRegServer -SqlInstance $TestConfig.instance2 -FilePath $outputFileName + $invalidResults.length | Should -Be 0 - It "Creates a regsrvr file using the FilePath alias OutFile" { - $outputFile = "C:\temp\dbatoolsci-regsrvr-export-$random.regsrvr" - $results = Export-DbaRegServer -SqlInstance $TestConfig.instance2 -OutFile $outputFile - $results | Should -BeOfType [System.IO.FileInfo] - $results.FullName | Should -Be $outputFile - } + # test with -Overwrite + $resultsOverwrite = Export-DbaRegServer -SqlInstance $TestConfig.instance2 -FilePath $outputFileName -Overwrite + $resultsOverwrite -is [System.IO.FileInfo] | Should -Be $true + $resultsOverwrite.FullName | Should -Be $outputFileName + } - It "Fails to create an invalid file using FilePath" { - $outputFile = "C:\temp\dbatoolsci-regsrvr-export-$random.txt" - $results = Export-DbaRegServer -SqlInstance $TestConfig.instance2 -FilePath $outputFile - $results.Length | Should -Be 0 - } + It "Test with the Group param" { + $outputFileName = "C:\temp\dbatoolsci-regsrvr-export-$random.xml" + $results = Export-DbaRegServer -SqlInstance $TestConfig.instance2 -FilePath $outputFileName -Group $group + $results -is [System.IO.FileInfo] | Should -Be $true + $results.FullName | Should -Be $outputFileName - It "Creates an xml file in a new directory using FileName" { - $outputFile = "$newDirectory\dbatoolsci-regsrvr-export-$random.xml" - $results = Export-DbaRegServer -SqlInstance $TestConfig.instance2 -FileName $outputFile - $results | Should -BeOfType [System.IO.FileInfo] - $results.FullName | Should -Be $outputFile - } + $fileText = Get-Content -Path $results -Raw - It "Respects the Overwrite parameter" { - $outputFile = "C:\temp\dbatoolsci-regsrvr-export-$random.xml" - $results = Export-DbaRegServer -SqlInstance $TestConfig.instance2 -FilePath $outputFile - $results | Should -BeOfType [System.IO.FileInfo] - $results.FullName | Should -Be $outputFile + $fileText | Should -Match $group + $fileText | Should -Not -Match $group2 + } - $invalidResults = Export-DbaRegServer -SqlInstance $TestConfig.instance2 -FilePath $outputFile - $invalidResults.Length | Should -Be 0 + It "Test with the Group param and multiple group names" { + $outputFileName = "C:\temp\dbatoolsci-regsrvr-export-$random.xml" + $results = Export-DbaRegServer -SqlInstance $TestConfig.instance2 -FilePath $outputFileName -Group @($group, $group2) + $results.length | Should -Be 2 - $resultsOverwrite = Export-DbaRegServer -SqlInstance $TestConfig.instance2 -FilePath $outputFile -Overwrite - $resultsOverwrite | Should -BeOfType [System.IO.FileInfo] - $resultsOverwrite.FullName | Should -Be $outputFile - } + $fileText = Get-Content -Path $results[0] -Raw - It "Filters by Group parameter" { - $outputFile = "C:\temp\dbatoolsci-regsrvr-export-$random.xml" - $results = Export-DbaRegServer -SqlInstance $TestConfig.instance2 -FilePath $outputFile -Group "dbatoolsci-group1" - $results | Should -BeOfType [System.IO.FileInfo] - $fileContent = Get-Content -Path $results -Raw - $fileContent | Should -Match "dbatoolsci-group1" - $fileContent | Should -Not -Match "dbatoolsci-group2" - } + $fileText | Should -Match $group + $fileText | Should -Not -Match $group2 - It "Handles multiple groups" { - $outputFile = "C:\temp\dbatoolsci-regsrvr-export-$random.xml" - $results = Export-DbaRegServer -SqlInstance $TestConfig.instance2 -FilePath $outputFile -Group @("dbatoolsci-group1", "dbatoolsci-group2") - $results.Length | Should -Be 2 + $fileText = Get-Content -Path $results[1] -Raw - $content1 = Get-Content -Path $results[0] -Raw - $content1 | Should -Match "dbatoolsci-group1" - $content1 | Should -Not -Match "dbatoolsci-group2" + $fileText | Should -Not -Match $group + $fileText | Should -Match $group2 + } - $content2 = Get-Content -Path $results[1] -Raw - $content2 | Should -Not -Match "dbatoolsci-group1" - $content2 | Should -Match "dbatoolsci-group2" - } + It "Test with the ExcludeGroup param" { + $results = Export-DbaRegServer -SqlInstance $TestConfig.instance2 -ExcludeGroup $group2 + $results -is [System.IO.FileInfo] | Should -Be $true - It "Respects ExcludeGroup parameter" { - $results = Export-DbaRegServer -SqlInstance $TestConfig.instance2 -ExcludeGroup "dbatoolsci-group2" - $results | Should -BeOfType [System.IO.FileInfo] - $fileContent = Get-Content -Path $results -Raw - $fileContent | Should -Match "dbatoolsci-group1" - $fileContent | Should -Not -Match "dbatoolsci-group2" - } + $fileText = Get-Content -Path $results -Raw + + $fileText | Should -Match $group + $fileText | Should -Not -Match $group2 } } diff --git a/tests/Export-DbaScript.Tests.ps1 b/tests/Export-DbaScript.Tests.ps1 index bd2af9d43b..100a1e0ba1 100644 --- a/tests/Export-DbaScript.Tests.ps1 +++ b/tests/Export-DbaScript.Tests.ps1 @@ -1,95 +1,56 @@ -#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} -param( - $ModuleName = "dbatools", - $PSDefaultParameterValues = ($global:TestConfig = Get-TestConfig).Defaults -) - -Describe "Export-DbaScript" -Tag "UnitTests" { - BeforeAll { - $command = Get-Command Export-DbaScript - $expected = $TestConfig.CommonParameters - $expected += @( - "InputObject", - "ScriptingOptionsObject", - "Path", - "FilePath", - "Encoding", - "BatchSeparator", - "NoPrefix", - "Passthru", - "NoClobber", - "Append", - "EnableException", - "Confirm", - "WhatIf" - ) - } - - Context "Parameter validation" { - It "Has parameter: <_>" -ForEach $expected { - $command | Should -HaveParameter $PSItem - } - - It "Should have exactly the number of expected parameters ($($expected.Count))" { - $hasparms = $command.Parameters.Values.Name - Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty +$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan +$global:TestConfig = Get-TestConfig + +Describe "$CommandName Unit Tests" -Tag 'UnitTests' { + Context "Validate parameters" { + It "Should only contain our specific parameters" { + [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } + [object[]]$knownParameters = 'InputObject', 'ScriptingOptionsObject', 'Path', 'FilePath', 'Encoding', 'BatchSeparator', 'NoPrefix', 'Passthru', 'NoClobber', 'Append', 'EnableException' + $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters + (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should -Be 0 } } } -Describe "Export-DbaScript" -Tag "IntegrationTests" { - Context "When exporting database objects" { - BeforeAll { - $table = Get-DbaDbTable -SqlInstance $TestConfig.instance2 -Database msdb | Select-Object -First 1 - $results = $table | Export-DbaScript -Passthru - } +Describe "$commandname Integration Tests" -Tags "IntegrationTests" { + Context "works as expected" { - It "Should export text matching CREATE TABLE" { - $results | Should -Match "CREATE TABLE" + It "should export some text matching create table" { + $results = Get-DbaDbTable -SqlInstance $TestConfig.instance2 -Database msdb | Select-Object -First 1 | Export-DbaScript -Passthru + $results -match "CREATE TABLE" } - - It "Should include BatchSeparator based on the Formatting.BatchSeparator configuration" { - $results | Should -Match "(Get-DbatoolsConfigValue -FullName 'Formatting.BatchSeparator')" + It "should include BatchSeparator based on the Formatting.BatchSeparator configuration" { + $results = Get-DbaDbTable -SqlInstance $TestConfig.instance2 -Database msdb | Select-Object -First 1 | Export-DbaScript -Passthru + $results -match "(Get-DbatoolsConfigValue -FullName 'Formatting.BatchSeparator')" } - It "Should include the defined BatchSeparator when specified" { - $customResults = $table | Export-DbaScript -Passthru -BatchSeparator "MakeItSo" - $customResults | Should -Match "MakeItSo" + It "should include the defined BatchSeparator" { + $results = Get-DbaDbTable -SqlInstance $TestConfig.instance2 -Database msdb | Select-Object -First 1 | Export-DbaScript -Passthru -BatchSeparator "MakeItSo" + $results -match "MakeItSo" } - } - Context "When handling invalid input" { - It "Should not accept non-SMO objects" { - $invalidObject = [pscustomobject]@{ Invalid = $true } - $invalidObject | Export-DbaScript -WarningVariable invalid -WarningAction Continue - $invalid | Should -Match "not a SQL Management Object" + It "should not accept non-SMO objects" { + $null = Get-DbaDbTable -SqlInstance $TestConfig.instance2 -Database msdb | Select-Object -First 1 | Export-DbaScript -Passthru -BatchSeparator "MakeItSo" + $null = [pscustomobject]@{ Invalid = $true } | Export-DbaScript -WarningVariable invalid -WarningAction Continue + $invalid -match "not a SQL Management Object" } - } - Context "When using NoPrefix parameter" { - BeforeAll { - $testPath = "C:\temp" - if (-not (Test-Path $testPath)) { - $null = New-Item -ItemType Directory -Path $testPath - } - $outputFile = Join-Path $testPath "msdb.txt" - $table = Get-DbaDbTable -SqlInstance $TestConfig.instance2 -Database msdb | Select-Object -First 1 + It "should not accept non-SMO objects" { + $null = Get-DbaDbTable -SqlInstance $TestConfig.instance2 -Database msdb | Select-Object -First 1 | Export-DbaScript -Passthru -BatchSeparator "MakeItSo" + $null = [pscustomobject]@{ Invalid = $true } | Export-DbaScript -WarningVariable invalid -WarningAction Continue + $invalid -match "not a SQL Management Object" } - - It "Should not append content by default with NoPrefix" { - $null = $table | Export-DbaScript -NoPrefix -FilePath $outputFile - $linecount1 = (Get-Content $outputFile).Count - $null = $table | Export-DbaScript -NoPrefix -FilePath $outputFile - $linecount2 = (Get-Content $outputFile).Count + It "should not append when using NoPrefix (#7455)" { + if (-not (Test-Path C:\temp)) { $null = mkdir C:\temp } + $null = Get-DbaDbTable -SqlInstance $TestConfig.instance2 -Database msdb | Select-Object -First 1 | Export-DbaScript -NoPrefix -FilePath C:\temp\msdb.txt + $linecount1 = (Get-Content C:\temp\msdb.txt).Count + $null = Get-DbaDbTable -SqlInstance $TestConfig.instance2 -Database msdb | Select-Object -First 1 | Export-DbaScript -NoPrefix -FilePath C:\temp\msdb.txt + $linecount2 = (Get-Content C:\temp\msdb.txt).Count $linecount1 | Should -Be $linecount2 - } - - It "Should append content when Append parameter is used with NoPrefix" { - $null = $table | Export-DbaScript -NoPrefix -FilePath $outputFile - $linecount1 = (Get-Content $outputFile).Count - $null = $table | Export-DbaScript -NoPrefix -FilePath $outputFile -Append - $linecount2 = (Get-Content $outputFile).Count - $linecount2 | Should -BeGreaterThan $linecount1 + $null = Get-DbaDbTable -SqlInstance $TestConfig.instance2 -Database msdb | Select-Object -First 1 | Export-DbaScript -NoPrefix -FilePath C:\temp\msdb.txt -Append + $linecount3 = (Get-Content C:\temp\msdb.txt).Count + $linecount1 | Should -Not -Be $linecount3 } } } diff --git a/tests/Find-DbaAgentJob.Tests.ps1 b/tests/Find-DbaAgentJob.Tests.ps1 index e6d0ee30e5..730f2b3507 100644 --- a/tests/Find-DbaAgentJob.Tests.ps1 +++ b/tests/Find-DbaAgentJob.Tests.ps1 @@ -1,169 +1,89 @@ -#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} -param( - $ModuleName = "dbatools", - $PSDefaultParameterValues = ($global:TestConfig = Get-TestConfig).Defaults -) - -Describe "Find-DbaAgentJob" -Tag "UnitTests" { - BeforeAll { - $command = Get-Command Find-DbaAgentJob - $expected = $TestConfig.CommonParameters - $expected += @( - 'SqlInstance', - 'SqlCredential', - 'JobName', - 'ExcludeJobName', - 'StepName', - 'LastUsed', - 'IsDisabled', - 'IsFailed', - 'IsNotScheduled', - 'IsNoEmailNotification', - 'Category', - 'Owner', - 'Since', - 'EnableException' - ) - } - - Context "Parameter validation" { - It "Has parameter: <_>" -ForEach $expected { - $command | Should -HaveParameter $PSItem - } - - It "Should have exactly the number of expected parameters ($($expected.Count))" { - $hasparms = $command.Parameters.Values.Name - Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty +$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan +$global:TestConfig = Get-TestConfig + +Describe "$CommandName Unit Tests" -Tag 'UnitTests' { + Context "Validate parameters" { + [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} + [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'JobName', 'ExcludeJobName', 'StepName', 'LastUsed', 'IsDisabled', 'IsFailed', 'IsNotScheduled', 'IsNoEmailNotification', 'Category', 'Owner', 'Since', '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 "Find-DbaAgentJob" -Tags "IntegrationTests" { +Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { + Context "Command finds jobs using all parameters" { BeforeAll { + #subsystemServer needs the real underlying name, and it doesn't work if targeting something like localhost\namedinstance + # the typical error would be WARNING: [17:19:26][New-DbaAgentJobStep] Something went wrong creating the job step | The specified '@server' is + #invalid (valid values are returned by sp_helpserver). $srvName = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Query "select @@servername as sn" -as PSObject - - # Create test job - $splatJob = @{ - SqlInstance = $TestConfig.instance2 - Job = 'dbatoolsci_testjob' - OwnerLogin = 'sa' - } - $null = New-DbaAgentJob @splatJob - - # Create test job step - $splatStep = @{ - SqlInstance = $TestConfig.instance2 - Job = 'dbatoolsci_testjob' - StepId = 1 - StepName = 'dbatoolsci Failed' - Subsystem = 'TransactSql' - SubsystemServer = $srvName.sn - Command = "RAISERROR (15600,-1,-1, 'dbatools_error');" - CmdExecSuccessCode = 0 - OnSuccessAction = 'QuitWithSuccess' - OnFailAction = 'QuitWithFailure' - Database = 'master' - RetryAttempts = 1 - RetryInterval = 2 - } - $null = New-DbaAgentJobStep @splatStep + $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job 'dbatoolsci_testjob' -OwnerLogin 'sa' + $null = New-DbaAgentJobStep -SqlInstance $TestConfig.instance2 -Job 'dbatoolsci_testjob' -StepId 1 -StepName 'dbatoolsci Failed' -Subsystem TransactSql -SubsystemServer $srvName.sn -Command "RAISERROR (15600,-1,-1, 'dbatools_error');" -CmdExecSuccessCode 0 -OnSuccessAction QuitWithSuccess -OnFailAction QuitWithFailure -Database master -RetryAttempts 1 -RetryInterval 2 $null = Start-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job 'dbatoolsci_testjob' - - # Create another test job - $null = New-DbaAgentJob @splatJob - $null = New-DbaAgentJobStep @splatStep - - # Create job category + $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job 'dbatoolsci_testjob' -OwnerLogin 'sa' + $null = New-DbaAgentJobStep -SqlInstance $TestConfig.instance2 -Job 'dbatoolsci_testjob' -StepId 1 -StepName 'dbatoolsci Failed' -Subsystem TransactSql -SubsystemServer $srvName.sn -Command "RAISERROR (15600,-1,-1, 'dbatools_error');" -CmdExecSuccessCode 0 -OnSuccessAction QuitWithSuccess -OnFailAction QuitWithFailure -Database master -RetryAttempts 1 -RetryInterval 2 $null = New-DbaAgentJobCategory -SqlInstance $TestConfig.instance2 -Category 'dbatoolsci_job_category' -CategoryType LocalJob - - # Create disabled test job - $splatDisabledJob = @{ - SqlInstance = $TestConfig.instance2 - Job = 'dbatoolsci_testjob_disabled' - Category = 'dbatoolsci_job_category' - Disabled = $true - } - $null = New-DbaAgentJob @splatDisabledJob - - # Create disabled job step - $splatDisabledStep = @{ - SqlInstance = $TestConfig.instance2 - Job = 'dbatoolsci_testjob_disabled' - StepId = 1 - StepName = 'dbatoolsci Test Step' - Subsystem = 'TransactSql' - SubsystemServer = $srvName.sn - Command = 'SELECT * FROM master.sys.all_columns' - CmdExecSuccessCode = 0 - OnSuccessAction = 'QuitWithSuccess' - OnFailAction = 'QuitWithFailure' - Database = 'master' - RetryAttempts = 1 - RetryInterval = 2 - } - $null = New-DbaAgentJobStep @splatDisabledStep + $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job 'dbatoolsci_testjob_disabled' -Category 'dbatoolsci_job_category' -Disabled + $null = New-DbaAgentJobStep -SqlInstance $TestConfig.instance2 -Job 'dbatoolsci_testjob_disabled' -StepId 1 -StepName 'dbatoolsci Test Step' -Subsystem TransactSql -SubsystemServer $srvName.sn -Command 'SELECT * FROM master.sys.all_columns' -CmdExecSuccessCode 0 -OnSuccessAction QuitWithSuccess -OnFailAction QuitWithFailure -Database master -RetryAttempts 1 -RetryInterval 2 } - AfterAll { $null = Remove-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob, dbatoolsci_testjob_disabled -Confirm:$false $null = Remove-DbaAgentJobCategory -SqlInstance $TestConfig.instance2 -Category 'dbatoolsci_job_category' -Confirm:$false } + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob It "Should find a specific job" { - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob - $results.name | Should -Be "dbatoolsci_testjob" + $results.name | Should Be "dbatoolsci_testjob" } - + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job *dbatoolsci* -Exclude dbatoolsci_testjob_disabled It "Should find a specific job but not an excluded job" { - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job *dbatoolsci* -Exclude dbatoolsci_testjob_disabled - $results.name | Should -Not -Be "dbatoolsci_testjob_disabled" + $results.name | Should Not Be "dbatoolsci_testjob_disabled" } - + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -StepName 'dbatoolsci Test Step' It "Should find a specific job with a specific step" { - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -StepName 'dbatoolsci Test Step' - $results.name | Should -Be "dbatoolsci_testjob_disabled" + $results.name | Should Be "dbatoolsci_testjob_disabled" } - + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -LastUsed 10 It "Should find jobs not used in the last 10 days" { - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -LastUsed 10 - $results | Should -Not -BeNullOrEmpty + $results | Should not be null } - + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsDisabled It "Should find jobs disabled from running" { - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsDisabled - $results.name | Should -Be "dbatoolsci_testjob_disabled" - $results.Count | Should -Be 1 + $results.name | Should be "dbatoolsci_testjob_disabled" } - + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsDisabled + It "Should find 1 job disabled from running" { + $results.count | Should be 1 + } + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsNotScheduled It "Should find jobs that have not been scheduled" { - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsNotScheduled - $results | Should -Not -BeNullOrEmpty + $results | Should not be null } - + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsNotScheduled -Job *dbatoolsci* It "Should find 2 jobs that have no schedule" { - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsNotScheduled -Job *dbatoolsci* - $results.Count | Should -Be 2 + $results.count | Should be 2 } - + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsNoEmailNotification It "Should find jobs that have no email notification" { - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsNoEmailNotification - $results | Should -Not -BeNullOrEmpty + $results | Should not be null } - + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Category 'dbatoolsci_job_category' It "Should find jobs that have a category of dbatoolsci_job_category" { - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Category 'dbatoolsci_job_category' - $results.name | Should -Be "dbatoolsci_testjob_disabled" + $results.name | Should be "dbatoolsci_testjob_disabled" } - + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Owner 'sa' It "Should find jobs that are owned by sa" { - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Owner 'sa' - $results | Should -Not -BeNullOrEmpty + $results | Should not be null } + + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsFailed -Since '2016-07-01 10:47:00' It "Should find jobs that have been failed since July of 2016" { - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsFailed -Since '2016-07-01 10:47:00' - $results | Should -Not -BeNullOrEmpty + $results | Should not be null } } } diff --git a/tests/Find-DbaBackup.Tests.ps1 b/tests/Find-DbaBackup.Tests.ps1 index 87ffb38fa3..2521874a9f 100644 --- a/tests/Find-DbaBackup.Tests.ps1 +++ b/tests/Find-DbaBackup.Tests.ps1 @@ -1,185 +1,131 @@ -#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} -param( - $ModuleName = "dbatools", - $PSDefaultParameterValues = ($global:TestConfig = Get-TestConfig).Defaults -) - -Describe "Find-DbaBackup" -Tag "UnitTests" { - BeforeAll { - $command = Get-Command Find-DbaBackup - $knownParameters = @( - 'Path' - 'BackupFileExtension' - 'RetentionPeriod' - 'CheckArchiveBit' - 'EnableException' - ) - $expected = $TestConfig.CommonParameters + $knownParameters - } - - Context "Parameter validation" { - It "Has parameter: <_>" -ForEach $expected { - $command | Should -HaveParameter $PSItem - } - - It "Should have exactly the number of expected parameters ($($expected.Count))" { - $params = $command.Parameters.Values.Name - Compare-Object -ReferenceObject $expected -DifferenceObject $params | Should -BeNullOrEmpty +$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan +$global:TestConfig = Get-TestConfig + +Describe "$CommandName Unit Tests" -Tag 'UnitTests' { + Context "Validate parameters" { + [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} + [object[]]$knownParameters = 'Path', 'BackupFileExtension', 'RetentionPeriod', 'CheckArchiveBit', '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 "Find-DbaBackup" -Tag "IntegrationTests" { - BeforeAll { - $testPath = "TestDrive:\sqlbackups" - if (!(Test-Path $testPath)) { - New-Item -Path $testPath -ItemType Container - } +Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { + $testPath = "TestDrive:\sqlbackups" + if (!(Test-Path $testPath)) { + New-Item -Path $testPath -ItemType Container } - Context "Path validation" { - It "Throws when path is invalid" { - { Find-DbaBackup -Path 'funnypath' -BackupFileExtension 'bak' -RetentionPeriod '0d' -EnableException } | - Should -Throw "not found" - } + { Find-DbaBackup -Path 'funnypath' -BackupFileExtension 'bak' -RetentionPeriod '0d' -EnableException } | Should Throw "not found" } - Context "RetentionPeriod validation" { - It "Throws when retention period format is invalid" { - { Find-DbaBackup -Path $testPath -BackupFileExtension 'bak' -RetentionPeriod 'ad' -EnableException } | - Should -Throw "format invalid" - } - - It "Throws when retention period units are invalid" { - { Find-DbaBackup -Path $testPath -BackupFileExtension 'bak' -RetentionPeriod '11y' -EnableException } | - Should -Throw "units invalid" - } + { Find-DbaBackup -Path $testPath -BackupFileExtension 'bak' -RetentionPeriod 'ad' -EnableException } | Should Throw "format invalid" + { Find-DbaBackup -Path $testPath -BackupFileExtension 'bak' -RetentionPeriod '11y' -EnableException } | Should Throw "units invalid" } - Context "BackupFileExtension validation" { - It "Does not throw with valid extension" { - { Find-DbaBackup -Path $testPath -BackupFileExtension '.bak' -RetentionPeriod '0d' -EnableException -WarningAction SilentlyContinue } | - Should -Not -Throw - } - - It "Outputs correct warning message" { - $warnMessage = Find-DbaBackup -WarningAction Continue -Path $testPath -BackupFileExtension '.bak' -RetentionPeriod '0d' 3>&1 - $warnMessage | Should -BeLike '*period*' - } + { Find-DbaBackup -Path $testPath -BackupFileExtension '.bak' -RetentionPeriod '0d' -EnableException -WarningAction SilentlyContinue } | Should Not Throw + } + Context "BackupFileExtension message validation" { + $warnmessage = Find-DbaBackup -WarningAction Continue -Path $testPath -BackupFileExtension '.bak' -RetentionPeriod '0d' 3>&1 + $warnmessage | Should BeLike '*period*' } - Context "Files found match the proper retention" { - BeforeAll { - # Create test files with different ages - foreach ($i in 1..5) { - $filepath = Join-Path $testPath "dbatoolsci_$($i)_backup_hours.bak" - Set-Content $filepath -value "." - (Get-ChildItem $filepath).LastWriteTime = (Get-Date).AddHours(-10) - } - foreach ($i in 1..5) { - $filepath = Join-Path $testPath "dbatoolsci_$($i)_backup_days.bak" - Set-Content $filepath -value "." - (Get-ChildItem $filepath).LastWriteTime = (Get-Date).AddDays(-5) - } - foreach ($i in 1..5) { - $filepath = Join-Path $testPath "dbatoolsci_$($i)_backup_weeks.bak" - Set-Content $filepath -value "." - (Get-ChildItem $filepath).LastWriteTime = (Get-Date).AddDays(-5 * 7) - } - foreach ($i in 1..5) { - $filepath = Join-Path $testPath "dbatoolsci_$($i)_backup_months.bak" - Set-Content $filepath -value "." - (Get-ChildItem $filepath).LastWriteTime = (Get-Date).AddDays(-5 * 30) - } + for ($i = 1; $i -le 5; $i++) { + $filepath = Join-Path $testPath "dbatoolsci_$($i)_backup_hours.bak" + Set-Content $filepath -value "." + (Get-ChildItem $filepath).LastWriteTime = (Get-Date).AddHours(-10) + } + for ($i = 1; $i -le 5; $i++) { + $filepath = Join-Path $testPath "dbatoolsci_$($i)_backup_days.bak" + Set-Content $filepath -value "." + (Get-ChildItem $filepath).LastWriteTime = (Get-Date).AddDays(-5) + } + for ($i = 1; $i -le 5; $i++) { + $filepath = Join-Path $testPath "dbatoolsci_$($i)_backup_weeks.bak" + Set-Content $filepath -value "." + (Get-ChildItem $filepath).LastWriteTime = (Get-Date).AddDays(-5 * 7) + } + for ($i = 1; $i -le 5; $i++) { + $filepath = Join-Path $testPath "dbatoolsci_$($i)_backup_months.bak" + Set-Content $filepath -value "." + (Get-ChildItem $filepath).LastWriteTime = (Get-Date).AddDays(-5 * 30) } - It "Should find all files with retention 0d" { $results = Find-DbaBackup -Path $testPath -BackupFileExtension 'bak' -RetentionPeriod '0d' - $results.Length | Should -Be 20 + $results.Length | Should Be 20 } - It "Should find no files '*hours*' with retention 11h" { $results = Find-DbaBackup -Path $testPath -BackupFileExtension 'bak' -RetentionPeriod '11h' - $results.Length | Should -Be 15 - ($results | Where-Object FullName -Like '*hours*').Count | Should -Be 0 + $results.Length | Should Be 15 + ($results | Where-Object FullName -Like '*hours*').Count | Should Be 0 } - It "Should find no files '*days*' with retention 6d" { $results = Find-DbaBackup -Path $testPath -BackupFileExtension 'bak' -RetentionPeriod '6d' - $results.Length | Should -Be 10 - ($results | Where-Object FullName -Like '*hours*').Count | Should -Be 0 - ($results | Where-Object FullName -Like '*days*').Count | Should -Be 0 + $results.Length | Should Be 10 + ($results | Where-Object FullName -Like '*hours*').Count | Should Be 0 + ($results | Where-Object FullName -Like '*days*').Count | Should Be 0 } - It "Should find no files '*weeks*' with retention 6w" { $results = Find-DbaBackup -Path $testPath -BackupFileExtension 'bak' -RetentionPeriod '6w' - $results.Length | Should -Be 5 - ($results | Where-Object FullName -Like '*hours*').Count | Should -Be 0 - ($results | Where-Object FullName -Like '*days*').Count | Should -Be 0 - ($results | Where-Object FullName -Like '*weeks*').Count | Should -Be 0 + $results.Length | Should Be 5 + ($results | Where-Object FullName -Like '*hours*').Count | Should Be 0 + ($results | Where-Object FullName -Like '*days*').Count | Should Be 0 + ($results | Where-Object FullName -Like '*weeks*').Count | Should Be 0 } - It "Should find no files '*months*' with retention 6m" { $results = Find-DbaBackup -Path $testPath -BackupFileExtension 'bak' -RetentionPeriod '6m' - $results.Length | Should -Be 0 - ($results | Where-Object FullName -Like '*hours*').Count | Should -Be 0 - ($results | Where-Object FullName -Like '*days*').Count | Should -Be 0 - ($results | Where-Object FullName -Like '*weeks*').Count | Should -Be 0 - ($results | Where-Object FullName -Like '*weeks*').Count | Should -Be 0 + $results.Length | Should Be 0 + ($results | Where-Object FullName -Like '*hours*').Count | Should Be 0 + ($results | Where-Object FullName -Like '*days*').Count | Should Be 0 + ($results | Where-Object FullName -Like '*weeks*').Count | Should Be 0 + ($results | Where-Object FullName -Like '*weeks*').Count | Should Be 0 } } - Context "Files found match the proper archive bit" { - BeforeAll { - foreach ($i in 1..5) { - $filepath = Join-Path $testPath "dbatoolsci_$($i)_backup_notarchive.bak" - Set-Content $filepath -value "." - (Get-ChildItem $filepath).LastWriteTime = (Get-Date).AddDays(-5) - (Get-ChildItem $filepath).Attributes = "Normal" - } - foreach ($i in 1..5) { - $filepath = Join-Path $testPath "dbatoolsci_$($i)_backup_archive.bak" - Set-Content $filepath -value "." - (Get-ChildItem $filepath).LastWriteTime = (Get-Date).AddDays(-5) - (Get-ChildItem $filepath).Attributes = "Archive" - } + for ($i = 1; $i -le 5; $i++) { + $filepath = Join-Path $testPath "dbatoolsci_$($i)_backup_notarchive.bak" + Set-Content $filepath -value "." + (Get-ChildItem $filepath).LastWriteTime = (Get-Date).AddDays(-5) + (Get-ChildItem $filepath).Attributes = "Normal" + } + for ($i = 1; $i -le 5; $i++) { + $filepath = Join-Path $testPath "dbatoolsci_$($i)_backup_archive.bak" + Set-Content $filepath -value "." + (Get-ChildItem $filepath).LastWriteTime = (Get-Date).AddDays(-5) + (Get-ChildItem $filepath).Attributes = "Archive" } - It "Should find all files with retention 0d" { $results = Find-DbaBackup -Path $testPath -BackupFileExtension 'bak' -RetentionPeriod '0d' - $results.Length | Should -Be 10 + $results.Length | Should Be 10 } - It "Should find only files with the archive bit not set" { $results = Find-DbaBackup -Path $testPath -BackupFileExtension 'bak' -RetentionPeriod '0d' -CheckArchiveBit - $results.Length | Should -Be 5 - ($results | Where-Object FullName -Like '*_notarchive*').Count | Should -Be 5 - ($results | Where-Object FullName -Like '*_archive*').Count | Should -Be 0 + $results.Length | Should Be 5 + ($results | Where-Object FullName -Like '*_notarchive*').Count | Should Be 5 + ($results | Where-Object FullName -Like '*_archive*').Count | Should Be 0 } } - Context "Files found match the proper extension" { - BeforeAll { - foreach ($i in 1..5) { - $filepath = Join-Path $testPath "dbatoolsci_$($i)_backup.trn" - Set-Content $filepath -value "." - (Get-ChildItem $filepath).LastWriteTime = (Get-Date).AddDays(-5) - } - foreach ($i in 1..5) { - $filepath = Join-Path $testPath "dbatoolsci_$($i)_backup.bak" - Set-Content $filepath -value "." - (Get-ChildItem $filepath).LastWriteTime = (Get-Date).AddDays(-5) - } + for ($i = 1; $i -le 5; $i++) { + $filepath = Join-Path $testPath "dbatoolsci_$($i)_backup.trn" + Set-Content $filepath -value "." + (Get-ChildItem $filepath).LastWriteTime = (Get-Date).AddDays(-5) + } + for ($i = 1; $i -le 5; $i++) { + $filepath = Join-Path $testPath "dbatoolsci_$($i)_backup.bak" + Set-Content $filepath -value "." + (Get-ChildItem $filepath).LastWriteTime = (Get-Date).AddDays(-5) } - It "Should find 5 files with extension trn" { $results = Find-DbaBackup -Path $testPath -BackupFileExtension 'trn' -RetentionPeriod '0d' - $results.Length | Should -Be 5 + $results.Length | Should Be 5 } - It "Should find 5 files with extension bak" { $results = Find-DbaBackup -Path $testPath -BackupFileExtension 'bak' -RetentionPeriod '0d' - $results.Length | Should -Be 5 + $results.Length | Should Be 5 } } -} +} \ No newline at end of file diff --git a/tests/Find-DbaDbUnusedIndex.Tests.ps1 b/tests/Find-DbaDbUnusedIndex.Tests.ps1 index 8d2831fd77..00585ff7d5 100644 --- a/tests/Find-DbaDbUnusedIndex.Tests.ps1 +++ b/tests/Find-DbaDbUnusedIndex.Tests.ps1 @@ -1,99 +1,109 @@ -#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} -param( - $ModuleName = "dbatools", - $PSDefaultParameterValues = ($global:TestConfig = Get-TestConfig).Defaults -) - -Describe "Find-DbaDbUnusedIndex" -Tag "UnitTests" { - BeforeAll { - $command = Get-Command Find-DbaDbUnusedIndex - $expected = $TestConfig.CommonParameters - $expected += @( - "SqlInstance", - "SqlCredential", - "Database", - "ExcludeDatabase", - "IgnoreUptime", - "Seeks", - "Scans", - "Lookups", - "InputObject", - "EnableException" - ) - } +$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan +$global:TestConfig = Get-TestConfig - Context "Parameter validation" { - It "Has parameter: <_>" -ForEach $expected { - $command | Should -HaveParameter $PSItem - } +Describe "$CommandName Unit Tests" -Tag 'UnitTests' { + Context "Validate parameters" { + It "Should only contain our specific parameters" { + [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } + [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'ExcludeDatabase', 'IgnoreUptime', 'InputObject', 'EnableException', 'Seeks', 'Scans', 'Lookups' + $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should have exactly the number of expected parameters ($($expected.Count))" { - $hasparms = $command.Parameters.Values.Name - Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty + (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should -Be 0 } } } +<# + Integration test should appear below and are custom to the command you are writing. + Read https://github.com/dataplat/dbatools/blob/development/contributing.md#tests + for more guidence. +#> -Describe "Find-DbaDbUnusedIndex" -Tag "IntegrationTests" { - BeforeAll { - Write-Message -Level Warning -Message "Find-DbaDbUnusedIndex testing connection to $($TestConfig.instance2)" - Test-DbaConnection -SqlInstance $TestConfig.instance2 - $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 +Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { + Context "Verify basics of the Find-DbaDbUnusedIndex command" { + BeforeAll { + Write-Message -Level Warning -Message "Find-DbaDbUnusedIndex testing connection to $($TestConfig.instance2)" + Test-DbaConnection -SqlInstance $TestConfig.instance2 - $random = Get-Random - $dbName = "dbatoolsci_$random" + $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 - Write-Message -Level Warning -Message "Find-DbaDbUnusedIndex setting up the new database $dbName" - Remove-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbName -Confirm:$false - $newDB = New-DbaDatabase -SqlInstance $TestConfig.instance2 -Name $dbName + $random = Get-Random + $dbName = "dbatoolsci_$random" - $indexName = "dbatoolsci_index_$random" - $tableName = "dbatoolsci_table_$random" - $sql = "USE $dbName; - CREATE TABLE $tableName (ID INTEGER); - CREATE INDEX $indexName ON $tableName (ID); - INSERT INTO $tableName (ID) VALUES (1); - SELECT ID FROM $tableName; - WAITFOR DELAY '00:00:05'; -- for slower systems allow the query optimizer engine to catch up and update sys.dm_db_index_usage_stats" + Write-Message -Level Warning -Message "Find-DbaDbUnusedIndex setting up the new database $dbName" + Remove-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbName -Confirm:$false + $newDB = New-DbaDatabase -SqlInstance $TestConfig.instance2 -Name $dbName - $null = $server.Query($sql) - } + $indexName = "dbatoolsci_index_$random" + $tableName = "dbatoolsci_table_$random" + $sql = "USE $dbName; + CREATE TABLE $tableName (ID INTEGER); + CREATE INDEX $indexName ON $tableName (ID); + INSERT INTO $tableName (ID) VALUES (1); + SELECT ID FROM $tableName; + WAITFOR DELAY '00:00:05'; -- for slower systems allow the query optimizer engine to catch up and update sys.dm_db_index_usage_stats" - AfterAll { - Write-Message -Level Warning -Message "Find-DbaDbUnusedIndex removing the database $dbName" - Remove-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbName -Confirm:$false - } + $null = $server.Query($sql) + } - Context "When finding unused indexes" { - BeforeAll { - $results = Find-DbaDbUnusedIndex -SqlInstance $TestConfig.instance2 -Database $dbName -IgnoreUptime -Seeks 10 -Scans 10 -Lookups 10 + AfterAll { + Write-Message -Level Warning -Message "Find-DbaDbUnusedIndex removing the database $dbName" + Remove-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbName -Confirm:$false } - It "Returns results for the test database" { + It "Should find the 'unused' index on each test sql instance" { + $results = Find-DbaDbUnusedIndex -SqlInstance $TestConfig.instance2 -Database $dbName -IgnoreUptime -Seeks 10 -Scans 10 -Lookups 10 $results.Database | Should -Be $dbName $results.DatabaseId | Should -Be $newDB.Id - } - It "Finds the test index" { - $foundIndex = $results | Where-Object IndexName -eq $indexName - $foundIndex | Should -Not -BeNullOrEmpty + $testSQLinstance = $false + + foreach ($row in $results) { + if ($row["IndexName"] -eq $indexName) { + Write-Message -Level Debug -Message "$($indexName) was found on $($TestConfig.instance2) in database $($dbName)" + $testSQLinstance = $true + } else { + Write-Message -Level Warning -Message "$($indexName) was not found on $($TestConfig.instance2) in database $($dbName)" + } + } + + $testSQLinstance | Should -Be $true } - It "Returns all expected properties" { - $expectedColumns = @( - 'CompressionDescription', 'ComputerName', 'Database', 'DatabaseId', - 'IndexId', 'IndexName', 'IndexSizeMB', 'InstanceName', - 'LastSystemLookup', 'LastSystemScan', 'LastSystemSeek', 'LastSystemUpdate', - 'LastUserLookup', 'LastUserScan', 'LastUserSeek', 'LastUserUpdate', - 'ObjectId', 'RowCount', 'Schema', 'SqlInstance', 'SystemLookup', - 'SystemScans', 'SystemSeeks', 'SystemUpdates', 'Table', 'TypeDesc', - 'UserLookups', 'UserScans', 'UserSeeks', 'UserUpdates' - ) - - $resultColumns = $results[0].PSObject.Properties.Name - $comparison = Compare-Object -ReferenceObject $expectedColumns -DifferenceObject $resultColumns - $comparison | Should -BeNullOrEmpty + + It "Should return the expected columns on each test sql instance" { + [object[]]$expectedColumnArray = 'CompressionDescription', 'ComputerName', 'Database', 'DatabaseId', 'IndexId', 'IndexName', 'IndexSizeMB', 'InstanceName', 'LastSystemLookup', 'LastSystemScan', 'LastSystemSeek', 'LastSystemUpdate', 'LastUserLookup', 'LastUserScan', 'LastUserSeek', 'LastUserUpdate', 'ObjectId', 'RowCount', 'Schema', 'SqlInstance', 'SystemLookup', 'SystemScans', 'SystemSeeks', 'SystemUpdates', 'Table', 'TypeDesc', 'UserLookups', 'UserScans', 'UserSeeks', 'UserUpdates' + + $testSQLinstance = $false + + $results = Find-DbaDbUnusedIndex -SqlInstance $TestConfig.instance2 -Database $dbName -IgnoreUptime -Seeks 10 -Scans 10 -Lookups 10 + + if ( ($null -ne $results) ) { + $row = $null + # if one row is returned $results will be a System.Data.DataRow, otherwise it will be an object[] of System.Data.DataRow + if ($results -is [System.Data.DataRow]) { + $row = $results + } elseif ($results -is [Object[]] -and $results.Count -gt 0) { + $row = $results[0] + } else { + Write-Message -Level Warning -Message "Unexpected results returned from $($SqlInstance): $($results)" + $testSQLinstance = $false + } + + if ($null -ne $row) { + [object[]]$columnNamesReturned = @($row | Get-Member -MemberType Property | Select-Object -Property Name | ForEach-Object { $_.Name }) + + if ( @(Compare-Object -ReferenceObject $expectedColumnArray -DifferenceObject $columnNamesReturned).Count -eq 0 ) { + Write-Message -Level Debug -Message "Columns matched on $($TestConfig.instance2)" + $testSQLinstance = $true + } else { + Write-Message -Level Warning -Message "The columns specified in the expectedColumnList variable do not match these returned columns from $($TestConfig.instance2): $($columnNamesReturned)" + } + } + } + + $testSQLinstance | Should -Be $true } } -} \ No newline at end of file +} diff --git a/tests/Find-DbaStoredProcedure.Tests.ps1 b/tests/Find-DbaStoredProcedure.Tests.ps1 index b51eb3bf3a..b6cf365576 100644 --- a/tests/Find-DbaStoredProcedure.Tests.ps1 +++ b/tests/Find-DbaStoredProcedure.Tests.ps1 @@ -1,94 +1,65 @@ -#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} -param( - $ModuleName = "dbatools", - $PSDefaultParameterValues = ($global:TestConfig = Get-TestConfig).Defaults -) +$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan +$global:TestConfig = Get-TestConfig -Describe "Find-DbaStoredProcedure" -Tag "UnitTests" { - BeforeAll { - $command = Get-Command Find-DbaStoredProcedure - $expected = $TestConfig.CommonParameters - $expected += @( - "SqlInstance", - "SqlCredential", - "Database", - "ExcludeDatabase", - "Pattern", - "IncludeSystemObjects", - "IncludeSystemDatabases", - "EnableException" - ) - } - - Context "Parameter validation" { - It "Has parameter: <_>" -ForEach $expected { - $command | Should -HaveParameter $PSItem - } - - It "Should have exactly the number of expected parameters ($($expected.Count))" { - $hasparms = $command.Parameters.Values.Name - Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty +Describe "$CommandName 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', 'Pattern', 'IncludeSystemObjects', 'IncludeSystemDatabases', '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 "Find-DbaStoredProcedure" -Tag "IntegrationTests" { - Context "When finding procedures in system databases" { +Describe "$commandname Integration Tests" -Tags "IntegrationTests" { + Context "Command finds Procedures in a System Database" { BeforeAll { - $systemProcedureQuery = @" + $ServerProcedure = @" CREATE PROCEDURE dbo.cp_dbatoolsci_sysadmin AS SET NOCOUNT ON; SELECT [sid],[loginname],[sysadmin] FROM [master].[sys].[syslogins]; "@ - $null = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Database 'Master' -Query $systemProcedureQuery + $null = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Database 'Master' -Query $ServerProcedure } - AfterAll { - $dropProcedureQuery = "DROP PROCEDURE dbo.cp_dbatoolsci_sysadmin;" - $null = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Database 'Master' -Query $dropProcedureQuery - } - - BeforeAll { - $systemResults = Find-DbaStoredProcedure -SqlInstance $TestConfig.instance2 -Pattern dbatools* -IncludeSystemDatabases + $DropProcedure = "DROP PROCEDURE dbo.cp_dbatoolsci_sysadmin;" + $null = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Database 'Master' -Query $DropProcedure } - - It "Should find procedure named cp_dbatoolsci_sysadmin" { - $systemResults.Name | Should -Contain "cp_dbatoolsci_sysadmin" - $systemResults.DatabaseId | Should -BeExactly (Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database master).ID + $results = Find-DbaStoredProcedure -SqlInstance $TestConfig.instance2 -Pattern dbatools* -IncludeSystemDatabases + It "Should find a specific StoredProcedure named cp_dbatoolsci_sysadmin" { + $results.Name | Should Contain "cp_dbatoolsci_sysadmin" + $results.DatabaseId | Should -Be (Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database master).ID } } - - Context "When finding procedures in user databases" { + Context "Command finds Procedures in a User Database" { BeforeAll { $null = New-DbaDatabase -SqlInstance $TestConfig.instance2 -Name 'dbatoolsci_storedproceduredb' - $userProcedureQuery = @" + $StoredProcedure = @" CREATE PROCEDURE dbo.sp_dbatoolsci_custom AS SET NOCOUNT ON; PRINT 'Dbatools Rocks'; "@ - $null = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Database 'dbatoolsci_storedproceduredb' -Query $userProcedureQuery - $userResults = Find-DbaStoredProcedure -SqlInstance $TestConfig.instance2 -Pattern dbatools* -Database 'dbatoolsci_storedproceduredb' - $excludeResults = Find-DbaStoredProcedure -SqlInstance $TestConfig.instance2 -Pattern dbatools* -ExcludeDatabase 'dbatoolsci_storedproceduredb' + $null = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Database 'dbatoolsci_storedproceduredb' -Query $StoredProcedure } - AfterAll { $null = Remove-DbaDatabase -SqlInstance $TestConfig.instance2 -Database 'dbatoolsci_storedproceduredb' -Confirm:$false } - - It "Should find procedure named sp_dbatoolsci_custom" { - $userResults.Name | Should -Contain "sp_dbatoolsci_custom" - $userResults.DatabaseId | Should -BeExactly (Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database dbatoolsci_storedproceduredb).ID + $results = Find-DbaStoredProcedure -SqlInstance $TestConfig.instance2 -Pattern dbatools* -Database 'dbatoolsci_storedproceduredb' + It "Should find a specific StoredProcedure named sp_dbatoolsci_custom" { + $results.Name | Should Contain "sp_dbatoolsci_custom" + $results.DatabaseId | Should -Be (Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database dbatoolsci_storedproceduredb).ID } - It "Should find sp_dbatoolsci_custom in dbatoolsci_storedproceduredb" { - $userResults.Database | Should -Contain "dbatoolsci_storedproceduredb" + $results.Database | Should Contain "dbatoolsci_storedproceduredb" } - - It "Should find no results when excluding dbatoolsci_storedproceduredb" { - $excludeResults | Should -BeNullOrEmpty + $results = Find-DbaStoredProcedure -SqlInstance $TestConfig.instance2 -Pattern dbatools* -ExcludeDatabase 'dbatoolsci_storedproceduredb' + It "Should find no results when Excluding dbatoolsci_storedproceduredb" { + $results | Should Be $null } } } diff --git a/tests/Find-DbaTrigger.Tests.ps1 b/tests/Find-DbaTrigger.Tests.ps1 index a5f0b357d7..724046f1e2 100644 --- a/tests/Find-DbaTrigger.Tests.ps1 +++ b/tests/Find-DbaTrigger.Tests.ps1 @@ -1,39 +1,19 @@ -#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} -param( - $ModuleName = "dbatools", - $PSDefaultParameterValues = ($global:TestConfig = Get-TestConfig).Defaults -) - -Describe "Find-DbaTrigger" -Tag "UnitTests" { - BeforeAll { - $command = Get-Command Find-DbaTrigger - $expected = $TestConfig.CommonParameters - $expected += @( - 'SqlInstance', - 'SqlCredential', - 'Database', - 'ExcludeDatabase', - 'Pattern', - 'TriggerLevel', - 'IncludeSystemObjects', - 'IncludeSystemDatabases', - 'EnableException' - ) - } - - Context "Parameter validation" { - It "Has parameter: <_>" -ForEach $expected { - $command | Should -HaveParameter $PSItem - } - - It "Should have exactly the number of expected parameters ($($expected.Count))" { - $hasparms = $command.Parameters.Values.Name - Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty +$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan +$global:TestConfig = Get-TestConfig + +Describe "$CommandName Unit Tests" -Tag 'UnitTests' { + Context "Validate parameters" { + [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } + [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'ExcludeDatabase', 'Pattern', 'TriggerLevel', 'IncludeSystemObjects', 'IncludeSystemDatabases', '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 "Find-DbaTrigger" -Tag "IntegrationTests" { +Describe "$commandname Integration Tests" -Tags "IntegrationTests" { Context "Command finds Triggers at the Server Level" { BeforeAll { ## All Triggers adapted from examples on: @@ -49,7 +29,6 @@ AS "@ $null = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Query $ServerTrigger } - AfterAll { $DropTrigger = @" DROP TRIGGER dbatoolsci_ddl_trig_database @@ -58,25 +37,19 @@ ON ALL SERVER; $null = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Database 'Master' -Query $DropTrigger } - BeforeAll { - $results = Find-DbaTrigger -SqlInstance $TestConfig.instance2 -Pattern dbatoolsci* -IncludeSystemDatabases -IncludeSystemObjects -TriggerLevel Server - } - + $results = Find-DbaTrigger -SqlInstance $TestConfig.instance2 -Pattern dbatoolsci* -IncludeSystemDatabases -IncludeSystemObjects -TriggerLevel Server It "Should find a specific Trigger at the Server Level" { - $results.TriggerLevel | Should -Be "Server" + $results.TriggerLevel | Should Be "Server" $results.DatabaseId | Should -BeNullOrEmpty } - It "Should find a specific Trigger named dbatoolsci_ddl_trig_database" { - $results.Name | Should -Be "dbatoolsci_ddl_trig_database" + $results.Name | Should Be "dbatoolsci_ddl_trig_database" } - + $results = Find-DbaTrigger -SqlInstance $TestConfig.instance2 -Pattern dbatoolsci* -TriggerLevel All It "Should find a specific Trigger when TriggerLevel is All" { - $allResults = Find-DbaTrigger -SqlInstance $TestConfig.instance2 -Pattern dbatoolsci* -TriggerLevel All - $allResults.Name | Should -Be "dbatoolsci_ddl_trig_database" + $results.Name | Should Be "dbatoolsci_ddl_trig_database" } } - Context "Command finds Triggers at the Database and Object Level" { BeforeAll { ## All Triggers adapted from examples on: @@ -105,42 +78,34 @@ GO "@ $null = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Database 'dbatoolsci_triggerdb' -Query $TableTrigger } - AfterAll { $null = Remove-DbaDatabase -SqlInstance $TestConfig.instance2 -Database 'dbatoolsci_triggerdb' -Confirm:$false } - BeforeAll { - $databaseResults = Find-DbaTrigger -SqlInstance $TestConfig.instance2 -Pattern dbatoolsci* -Database 'dbatoolsci_triggerdb' -TriggerLevel Database - $objectResults = Find-DbaTrigger -SqlInstance $TestConfig.instance2 -Pattern dbatoolsci* -Database 'dbatoolsci_triggerdb' -ExcludeDatabase Master -TriggerLevel Object - $allResults = Find-DbaTrigger -SqlInstance $TestConfig.instance2 -Pattern dbatoolsci* -TriggerLevel All - } - + $results = Find-DbaTrigger -SqlInstance $TestConfig.instance2 -Pattern dbatoolsci* -Database 'dbatoolsci_triggerdb' -TriggerLevel Database It "Should find a specific Trigger at the Database Level" { - $databaseResults.TriggerLevel | Should -Be "Database" - $databaseResults.DatabaseId | Should -Be $dbatoolsci_triggerdb.ID + $results.TriggerLevel | Should Be "Database" + $results.DatabaseId | Should -Be $dbatoolsci_triggerdb.ID } - It "Should find a specific Trigger named dbatoolsci_safety" { - $databaseResults.Name | Should -Be "dbatoolsci_safety" + $results.Name | Should Be "dbatoolsci_safety" } + $results = Find-DbaTrigger -SqlInstance $TestConfig.instance2 -Pattern dbatoolsci* -Database 'dbatoolsci_triggerdb' -ExcludeDatabase Master -TriggerLevel Object It "Should find a specific Trigger at the Object Level" { - $objectResults.TriggerLevel | Should -Be "Object" - $objectResults.DatabaseId | Should -Be $dbatoolsci_triggerdb.ID + $results.TriggerLevel | Should Be "Object" + $results.DatabaseId | Should -Be $dbatoolsci_triggerdb.ID } - It "Should find a specific Trigger named dbatoolsci_reminder1" { - $objectResults.Name | Should -Be "dbatoolsci_reminder1" + $results.Name | Should Be "dbatoolsci_reminder1" } - It "Should find a specific Trigger on the Table [dbo].[Customer]" { - $objectResults.Object | Should -Be "[dbo].[Customer]" + $results.Object | Should Be "[dbo].[Customer]" } - + $results = Find-DbaTrigger -SqlInstance $TestConfig.instance2 -Pattern dbatoolsci* -TriggerLevel All It "Should find 2 Triggers when TriggerLevel is All" { - $allResults.Name | Should -Be @('dbatoolsci_safety', 'dbatoolsci_reminder1') - $allResults.DatabaseId | Should -Be @($dbatoolsci_triggerdb.ID, $dbatoolsci_triggerdb.ID) + $results.name | Should Be @('dbatoolsci_safety', 'dbatoolsci_reminder1') + $results.DatabaseId | Should -Be $dbatoolsci_triggerdb.ID, $dbatoolsci_triggerdb.ID } } } diff --git a/tests/Find-DbaView.Tests.ps1 b/tests/Find-DbaView.Tests.ps1 index a26cfddf92..e9cb17fe49 100644 --- a/tests/Find-DbaView.Tests.ps1 +++ b/tests/Find-DbaView.Tests.ps1 @@ -1,99 +1,70 @@ -#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} -param( - $ModuleName = "dbatools", - $PSDefaultParameterValues = ($global:TestConfig = Get-TestConfig).Defaults -) - +$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan +$global:TestConfig = Get-TestConfig -Describe "Find-DbaView" -Tag "UnitTests" { - BeforeAll { - $command = Get-Command Find-DbaView - $expected = $TestConfig.CommonParameters - $expected += @( - "SqlInstance", - "SqlCredential", - "Database", - "ExcludeDatabase", - "Pattern", - "IncludeSystemObjects", - "IncludeSystemDatabases", - "EnableException" - ) - } - - Context "Parameter validation" { - It "Has parameter: <_>" -ForEach $expected { - $command | Should -HaveParameter $PSItem - } - - It "Should have exactly the number of expected parameters ($($expected.Count))" { - $hasparms = $command.Parameters.Values.Name - Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty +Describe "$CommandName 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', 'Pattern', 'IncludeSystemObjects', 'IncludeSystemDatabases', '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 "Find-DbaView" -Tags "IntegrationTests" { - Context "When finding views in a system database" { + +Describe "$commandname Integration Tests" -Tags "IntegrationTests" { + Context "Command finds Views in a System Database" { BeforeAll { - $serverView = @" + $ServerView = @" CREATE VIEW dbo.v_dbatoolsci_sysadmin AS SELECT [sid],[loginname],[sysadmin] FROM [master].[sys].[syslogins]; "@ - $null = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Database 'Master' -Query $serverView + $null = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Database 'Master' -Query $ServerView } - AfterAll { - $dropView = "DROP VIEW dbo.v_dbatoolsci_sysadmin;" - $null = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Database 'Master' -Query $dropView - } - - BeforeAll { - $results = Find-DbaView -SqlInstance $TestConfig.instance2 -Pattern dbatools* -IncludeSystemDatabases + $DropView = "DROP VIEW dbo.v_dbatoolsci_sysadmin;" + $null = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Database 'Master' -Query $DropView } + $results = Find-DbaView -SqlInstance $TestConfig.instance2 -Pattern dbatools* -IncludeSystemDatabases It "Should find a specific View named v_dbatoolsci_sysadmin" { - $results.Name | Should -Be "v_dbatoolsci_sysadmin" + $results.Name | Should Be "v_dbatoolsci_sysadmin" } - It "Should find v_dbatoolsci_sysadmin in Master" { - $results.Database | Should -Be "Master" + $results.Database | Should Be "Master" $results.DatabaseId | Should -Be (Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database Master).ID } } - - Context "When finding views in a user database" { + Context "Command finds View in a User Database" { BeforeAll { $null = New-DbaDatabase -SqlInstance $TestConfig.instance2 -Name 'dbatoolsci_viewdb' - $databaseView = @" + $DatabaseView = @" CREATE VIEW dbo.v_dbatoolsci_sysadmin AS SELECT [sid],[loginname],[sysadmin] FROM [master].[sys].[syslogins]; "@ - $null = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Database 'dbatoolsci_viewdb' -Query $databaseView - $resultsInDb = Find-DbaView -SqlInstance $TestConfig.instance2 -Pattern dbatools* -Database 'dbatoolsci_viewdb' - $resultsExcluded = Find-DbaView -SqlInstance $TestConfig.instance2 -Pattern dbatools* -ExcludeDatabase 'dbatoolsci_viewdb' + $null = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Database 'dbatoolsci_viewdb' -Query $DatabaseView } - AfterAll { $null = Remove-DbaDatabase -SqlInstance $TestConfig.instance2 -Database 'dbatoolsci_viewdb' -Confirm:$false } + $results = Find-DbaView -SqlInstance $TestConfig.instance2 -Pattern dbatools* -Database 'dbatoolsci_viewdb' It "Should find a specific view named v_dbatoolsci_sysadmin" { - $resultsInDb.Name | Should -Be "v_dbatoolsci_sysadmin" + $results.Name | Should Be "v_dbatoolsci_sysadmin" } - It "Should find v_dbatoolsci_sysadmin in dbatoolsci_viewdb Database" { - $resultsInDb.Database | Should -Be "dbatoolsci_viewdb" - $resultsInDb.DatabaseId | Should -Be (Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database dbatoolsci_viewdb).ID + $results.Database | Should Be "dbatoolsci_viewdb" + $results.DatabaseId | Should -Be (Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database dbatoolsci_viewdb).ID } - + $results = Find-DbaView -SqlInstance $TestConfig.instance2 -Pattern dbatools* -ExcludeDatabase 'dbatoolsci_viewdb' It "Should find no results when Excluding dbatoolsci_viewdb" { - $resultsExcluded | Should -BeNullOrEmpty + $results | Should Be $null } } } diff --git a/tests/Get-DbaAgentJob.Tests.ps1 b/tests/Get-DbaAgentJob.Tests.ps1 index fc88da5a30..d5c41b23cc 100644 --- a/tests/Get-DbaAgentJob.Tests.ps1 +++ b/tests/Get-DbaAgentJob.Tests.ps1 @@ -1,117 +1,85 @@ -#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} -param( - $ModuleName = "dbatools", - $PSDefaultParameterValues = ($global:TestConfig = Get-TestConfig).Defaults -) +$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan +$global:TestConfig = Get-TestConfig -Describe "Get-DbaAgentJob" -Tag "UnitTests" { - BeforeAll { - $command = Get-Command Get-DbaAgentJob - $knownParameters = @( - 'SqlInstance' - 'SqlCredential' - 'Job' - 'ExcludeJob' - 'Database' - 'Category' - 'ExcludeCategory' - 'ExcludeDisabledJobs' - 'IncludeExecution' - 'Type' - 'EnableException' - ) - } - - Context "Parameter validation" { - It "Has parameter: <_>" -ForEach $knownParameters { - $command | Should -HaveParameter $PSItem - } +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', 'Job', 'ExcludeJob', 'Database', 'Category', 'ExcludeDisabledJobs', 'EnableException', 'ExcludeCategory', 'IncludeExecution', 'Type' - It "Should have exactly the number of parameters ($($knownParameters.Count))" { - $params = $command.Parameters.Values.Name + It "Should only contain our specific parameters" { Compare-Object -ReferenceObject $knownParameters -DifferenceObject $params | Should -BeNullOrEmpty } } } -Describe "Get-DbaAgentJob" -Tag "IntegrationTests" { - Context "When getting jobs" { +Describe "$commandname Integration Tests" -Tags "IntegrationTests" { + Context "Command gets jobs" { BeforeAll { $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob_disabled -Disabled } - AfterAll { $null = Remove-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob, dbatoolsci_testjob_disabled -Confirm:$false } - - It "Returns 2 dbatoolsci jobs" { - $results = Get-DbaAgentJob -SqlInstance $TestConfig.instance2 | Where-Object Name -Match "dbatoolsci_testjob" - $results.Count | Should -Be 2 + $results = Get-DbaAgentJob -SqlInstance $TestConfig.instance2 | Where-Object { $_.Name -match "dbatoolsci_testjob" } + It "Should get 2 dbatoolsci jobs" { + $results.count | Should Be 2 } - - It "Returns a specific job by name" { - $results = Get-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob - $results.Name | Should -Be "dbatoolsci_testjob" + $results = Get-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob + It "Should get a specific job" { + $results.name | Should Be "dbatoolsci_testjob" } - } - Context "When excluding disabled jobs" { + } + Context "Command gets no disabled jobs" { BeforeAll { $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob_disabled -Disabled } - AfterAll { $null = Remove-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob, dbatoolsci_testjob_disabled -Confirm:$false } - - It "Returns only enabled jobs" { - $results = Get-DbaAgentJob -SqlInstance $TestConfig.instance2 -ExcludeDisabledJobs | Where-Object Name -Match "dbatoolsci_testjob" - $results.Enabled -contains $false | Should -Be $false + $results = Get-DbaAgentJob -SqlInstance $TestConfig.instance2 -ExcludeDisabledJobs | Where-Object { $_.Name -match "dbatoolsci_testjob" } + It "Should return only enabled jobs" { + $results.enabled -contains $False | Should Be $False } } - - Context "When excluding specific jobs" { + Context "Command doesn't get excluded job" { BeforeAll { $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob_disabled -Disabled } - AfterAll { $null = Remove-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob, dbatoolsci_testjob_disabled -Confirm:$false } - - It "Does not return excluded jobs" { - $results = Get-DbaAgentJob -SqlInstance $TestConfig.instance2 -ExcludeJob dbatoolsci_testjob | Where-Object Name -Match "dbatoolsci_testjob" - $results.Name -contains "dbatoolsci_testjob" | Should -Be $false + $results = Get-DbaAgentJob -SqlInstance $TestConfig.instance2 -ExcludeJob dbatoolsci_testjob | Where-Object { $_.Name -match "dbatoolsci_testjob" } + It "Should not return excluded job" { + $results.name -contains "dbatoolsci_testjob" | Should Be $False } } - - Context "When excluding job categories" { + Context "Command doesn't get excluded category" { BeforeAll { $null = New-DbaAgentJobCategory -SqlInstance $TestConfig.instance2 -Category 'Cat1' $null = New-DbaAgentJobCategory -SqlInstance $TestConfig.instance2 -Category 'Cat2' + $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob_cat1 -Category 'Cat1' $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob_cat2 -Category 'Cat2' } - AfterAll { $null = Remove-DbaAgentJobCategory -SqlInstance $TestConfig.instance2 -Category 'Cat1', 'Cat2' -Confirm:$false + $null = Remove-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob_cat1, dbatoolsci_testjob_cat2 -Confirm:$false } - - It "Does not return jobs from excluded categories" { - $results = Get-DbaAgentJob -SqlInstance $TestConfig.instance2 -ExcludeCategory 'Cat2' | Where-Object Name -Match "dbatoolsci_testjob" - $results.Name -contains "dbatoolsci_testjob_cat2" | Should -Be $false + $results = Get-DbaAgentJob -SqlInstance $TestConfig.instance2 -ExcludeCategory 'Cat2' | Where-Object { $_.Name -match "dbatoolsci_testjob" } + It "Should not return excluded job" { + $results.name -contains "dbatoolsci_testjob_cat2" | Should Be $False } } - - Context "When filtering by database" { + Context "Command gets jobs when databases are specified" { BeforeAll { $jobName1 = "dbatoolsci_dbfilter_$(Get-Random)" $jobName2 = "dbatoolsci_dbfilter_$(Get-Random)" - $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job $jobName1 -Disabled $null = New-DbaAgentJobStep -SqlInstance $TestConfig.instance2 -Job $jobName1 -StepName "TSQL-x" -Subsystem TransactSql -Database "msdb" $null = New-DbaAgentJobStep -SqlInstance $TestConfig.instance2 -Job $jobName1 -StepName "TSQL-y" -Subsystem TransactSql -Database "tempdb" @@ -122,21 +90,23 @@ Describe "Get-DbaAgentJob" -Tag "IntegrationTests" { $null = New-DbaAgentJobStep -SqlInstance $TestConfig.instance2 -Job $jobName2 -StepName "TSQL-y" -Subsystem TransactSql -Database "model" $null = New-DbaAgentJobStep -SqlInstance $TestConfig.instance2 -Job $jobName2 -StepName "TSQL-z" -Subsystem TransactSql -Database "master" } - AfterAll { $null = Remove-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job $jobName1, $jobName2 -Confirm:$false } - - It "Returns jobs for a single database" { - $resultSingleDatabase = Get-DbaAgentJob -SqlInstance $TestConfig.instance2 -Database tempdb + $resultSingleDatabase = Get-DbaAgentJob -SqlInstance $TestConfig.instance2 -Database tempdb + It "Returns result with single database" { $resultSingleDatabase.Count | Should -BeGreaterOrEqual 1 - $resultSingleDatabase.Name -contains $jobName1 | Should -BeTrue + } + It "Returns job result for Database: tempdb" { + $resultSingleDatabase.name -contains $jobName1 | Should -BeTrue } - It "Returns jobs for multiple databases" { - $resultMultipleDatabases = Get-DbaAgentJob -SqlInstance $TestConfig.instance2 -Database tempdb, model + $resultMultipleDatabases = Get-DbaAgentJob -SqlInstance $TestConfig.instance2 -Database tempdb, model + It "Returns both jobs with double database" { $resultMultipleDatabases.Count | Should -BeGreaterOrEqual 2 - $resultMultipleDatabases.Name -contains $jobName2 | Should -BeTrue + } + It "Includes job result for Database: model" { + $resultMultipleDatabases.name -contains $jobName2 | Should -BeTrue } } } diff --git a/tests/Get-DbaComputerCertificate.Tests.ps1 b/tests/Get-DbaComputerCertificate.Tests.ps1 index 3ac5b9bbab..94918a9910 100644 --- a/tests/Get-DbaComputerCertificate.Tests.ps1 +++ b/tests/Get-DbaComputerCertificate.Tests.ps1 @@ -1,65 +1,41 @@ -#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} -param( - $ModuleName = "dbatools", - $PSDefaultParameterValues = ($global:TestConfig = Get-TestConfig).Defaults -) - -Describe "Get-DbaComputerCertificate" -Tag "UnitTests" { - BeforeAll { - $command = Get-Command Get-DbaComputerCertificate - $expected = $TestConfig.CommonParameters - $expected += @( - "ComputerName", - "Credential", - "Store", - "Folder", - "Type", - "Path", - "Thumbprint", - "EnableException" - ) - } - - Context "Parameter validation" { - It "Has parameter: <_>" -ForEach $expected { - $command | Should -HaveParameter $PSItem - } - - It "Should have exactly the number of expected parameters ($($expected.Count))" { - $hasparms = $command.Parameters.Values.Name - Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty +$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan +$global:TestConfig = Get-TestConfig + +Describe "$CommandName Unit Tests" -Tag 'UnitTests' { + Context "Validate parameters" { + [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} + [object[]]$knownParameters = 'ComputerName', 'Credential', 'Store', 'Folder', 'Path', 'Thumbprint', 'EnableException', '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 "Get-DbaComputerCertificate" -Tag "IntegrationTests" { - Context "When getting a specific certificate" { +Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { + Context "Can get a certificate" { BeforeAll { - $thumbprint = "29C469578D6C6211076A09CEE5C5797EEA0C2713" $null = Add-DbaComputerCertificate -Path "$($TestConfig.appveyorlabrepo)\certificates\localhost.crt" -Confirm:$false - $cert = Get-DbaComputerCertificate -Thumbprint $thumbprint + $thumbprint = "29C469578D6C6211076A09CEE5C5797EEA0C2713" } - AfterAll { Remove-DbaComputerCertificate -Thumbprint $thumbprint -Confirm:$false } - It "Returns a single certificate with the specified thumbprint" { - $cert.Thumbprint | Should -Be $thumbprint - } - } + $cert = Get-DbaComputerCertificate -Thumbprint $thumbprint - Context "When getting all certificates" { - BeforeAll { - $allCerts = Get-DbaComputerCertificate + It "returns a single certificate with a specific thumbprint" { + $cert.Thumbprint | Should Be $thumbprint } - It "Returns all certificates including one with the specified thumbprint" { - "$($allCerts.Thumbprint)" | Should -Match "29C469578D6C6211076A09CEE5C5797EEA0C2713" - } + $cert = Get-DbaComputerCertificate - It "Returns certificates with the expected enhanced key usage" { - "$($allCerts.EnhancedKeyUsageList)" | Should -Match '1\.3\.6\.1\.5\.5\.7\.3\.1' + It "returns all certificates and at least one has the specified thumbprint" { + "$($cert.Thumbprint)" -match $thumbprint | Should Be $true + } + It "returns all certificates and at least one has the specified EnhancedKeyUsageList" { + "$($cert.EnhancedKeyUsageList)" -match '1\.3\.6\.1\.5\.5\.7\.3\.1' | Should Be $true } } } diff --git a/tests/Get-DbaDbCompression.Tests.ps1 b/tests/Get-DbaDbCompression.Tests.ps1 index 70d2150148..e6eb3bb58c 100644 --- a/tests/Get-DbaDbCompression.Tests.ps1 +++ b/tests/Get-DbaDbCompression.Tests.ps1 @@ -1,36 +1,19 @@ -#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} -param( - $ModuleName = "dbatools", - $PSDefaultParameterValues = ($global:TestConfig = Get-TestConfig).Defaults -) - -Describe "Get-DbaDbCompression" -Tag "UnitTests" { - BeforeAll { - $command = Get-Command Get-DbaDbCompression - $expected = $TestConfig.CommonParameters - $expected += @( - "SqlInstance", - "SqlCredential", - "Database", - "ExcludeDatabase", - "Table", - "EnableException" - ) - } - - Context "Parameter validation" { - It "Has parameter: <_>" -ForEach $expected { - $command | Should -HaveParameter $PSItem - } - - It "Should have exactly the number of expected parameters ($($expected.Count))" { - $hasparms = $command.Parameters.Values.Name - Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty +$commandname = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan +$global:TestConfig = Get-TestConfig + +Describe "$CommandName Unit Tests" -Tag 'UnitTests' { + Context "Validate parameters" { + [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } + [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'ExcludeDatabase', 'Table', '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 "Get-DbaDbCompression" -Tag "IntegrationTests" { +Describe "$commandname Integration Tests" -Tags "IntegrationTests" { BeforeAll { $dbname = "dbatoolsci_test_$(Get-Random)" $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 @@ -40,36 +23,38 @@ Describe "Get-DbaDbCompression" -Tag "IntegrationTests" { create clustered index CL_sysallparams on sysallparams (object_id) create nonclustered index NC_syscols on syscols (precision) include (collation_name)", $dbname) } - AfterAll { Get-DbaProcess -SqlInstance $TestConfig.instance2 -Database $dbname | Stop-DbaProcess -WarningAction SilentlyContinue Remove-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname -Confirm:$false } + $results = Get-DbaDbCompression -SqlInstance $TestConfig.instance2 -Database $dbname - Context "When getting compression information" { - BeforeAll { - $results = Get-DbaDbCompression -SqlInstance $TestConfig.instance2 -Database $dbname + Context "Command handles heaps and clustered indexes" { + It "Gets results" { + $results | Should Not Be $null + $results.Database | Get-Unique | Should -Be $dbname + $results.DatabaseId | Get-Unique | Should -Be $server.Query("SELECT database_id FROM sys.databases WHERE name = '$dbname'").database_id } - - It "Returns results" { - $results | Should -Not -BeNullOrEmpty - $results.Database | Select-Object -Unique | Should -Be $dbname - $results.DatabaseId | Select-Object -Unique | Should -Be $server.Query("SELECT database_id FROM sys.databases WHERE name = '$dbname'").database_id + Foreach ($row in $results | Where-Object { $_.IndexId -le 1 }) { + It "Should return compression level for object $($row.TableName)" { + $row.DataCompression | Should BeIn ('None', 'Row', 'Page') + } } - - It "Returns correct compression level for object " -ForEach @($results | Where-Object { $PSItem.IndexId -le 1 }) { - $PSItem.DataCompression | Should -BeIn @('None', 'Row', 'Page') + } + Context "Command handles nonclustered indexes" { + It "Gets results" { + $results | Should Not Be $null } - - It "Returns correct compression level for nonclustered index " -ForEach @($results | Where-Object { $PSItem.IndexId -gt 1 }) { - $PSItem.DataCompression | Should -BeIn @('None', 'Row', 'Page') + Foreach ($row in $results | Where-Object { $_.IndexId -gt 1 }) { + It "Should return compression level for nonclustered index $($row.IndexName)" { + $row.DataCompression | Should BeIn ('None', 'Row', 'Page') + } } } - Context "When excluding databases" { - It "Should not return results for excluded database" { - $excludedResults = Get-DbaDbCompression -SqlInstance $TestConfig.instance2 -Database $dbname -ExcludeDatabase $dbname - $excludedResults | Should -Not -Match $dbname + Context "Command excludes results for specified database" { + It "Shouldn't get any results for $dbname" { + $(Get-DbaDbCompression -SqlInstance $TestConfig.instance2 -Database $dbname -ExcludeDatabase $dbname) | Should not Match $dbname } } }