diff --git a/.aitools/module/Repair-PullRequestTest.ps1 b/.aitools/module/Repair-PullRequestTest.ps1 index a12724baf30..7f6caa247cc 100644 --- a/.aitools/module/Repair-PullRequestTest.ps1 +++ b/.aitools/module/Repair-PullRequestTest.ps1 @@ -21,6 +21,11 @@ function Repair-PullRequestTest { Specific AppVeyor build number to target instead of automatically detecting from PR checks. When specified, uses this build number directly rather than finding the latest build for the PR. + .PARAMETER CopyOnly + If specified, stops the repair process right after copying working test files + from the development branch to the current branch, without running Update-PesterTest + or committing any changes. + .NOTES Tags: Testing, Pester, PullRequest, CI Author: dbatools team @@ -47,7 +52,8 @@ function Repair-PullRequestTest { [int]$PRNumber, [switch]$AutoCommit, [int]$MaxPRs = 5, - [int]$BuildNumber + [int]$BuildNumber, + [switch]$CopyOnly ) begin { @@ -303,9 +309,27 @@ function Repair-PullRequestTest { $workingTempPath = Join-Path $tempDir "working-$fileName" if ($workingTestPath -and (Test-Path $workingTestPath)) { - Copy-Item $workingTestPath $workingTempPath -Force - $copiedFiles += $fileName - Write-Verbose "Copied working test: $fileName" + $maxAttempts = 2 + $attempt = 0 + $copied = $false + while (-not $copied -and $attempt -lt $maxAttempts) { + try { + $attempt++ + Copy-Item -Path $workingTestPath -Destination $workingTempPath -Force -ErrorAction Stop + $copiedFiles += $fileName + Write-Verbose "Copied working test: $fileName (attempt $attempt)" + $copied = $true + } catch { + Write-Warning ("Attempt {0}: Failed to copy working test file for {1} from development branch: {2}" -f $attempt, $fileName, $_.Exception.Message) + if ($attempt -lt $maxAttempts) { + Start-Sleep -Seconds 1 + } + } + } + if (-not $copied) { + Write-Error "Unable to copy working test file for $fileName after $maxAttempts attempts. Aborting repair process for this file." + break + } } else { Write-Warning "Could not find working test file in Development branch: tests/$fileName" } @@ -373,6 +397,12 @@ function Repair-PullRequestTest { } } + # If CopyOnly is specified, return immediately after copying + if ($CopyOnly) { + Write-Verbose "CopyOnly flag set - stopping after copying working tests to current branch" + return + } + # Now run Update-PesterTest in parallel with Start-Job (simplified approach) Write-Verbose "Starting parallel Update-PesterTest jobs for $($fileErrorMap.Keys.Count) files" diff --git a/public/Invoke-DbatoolsFormatter.ps1 b/public/Invoke-DbatoolsFormatter.ps1 index a9fdf847df9..1c820fb5407 100644 --- a/public/Invoke-DbatoolsFormatter.ps1 +++ b/public/Invoke-DbatoolsFormatter.ps1 @@ -9,10 +9,6 @@ function Invoke-DbatoolsFormatter { .PARAMETER Path The path to the ps1 file that needs to be formatted - .PARAMETER SkipInvisibleOnly - Skip files that would only have invisible changes (BOM, line endings, trailing whitespace, tabs). - Use this to avoid unnecessary version control noise when only non-visible characters would change. - .PARAMETER EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting. @@ -35,15 +31,14 @@ function Invoke-DbatoolsFormatter { Reformats C:\dbatools\public\Get-DbaDatabase.ps1 to dbatools' standards .EXAMPLE - PS C:\> Invoke-DbatoolsFormatter -Path C:\dbatools\public\*.ps1 -SkipInvisibleOnly + PS C:\> Get-ChildItem *.ps1 | Invoke-DbatoolsFormatter - Reformats all ps1 files but skips those that would only have BOM/line ending changes + Reformats all .ps1 files in the current directory, showing progress for the batch operation #> [CmdletBinding()] param ( [parameter(Mandatory, ValueFromPipeline)] [object[]]$Path, - [switch]$SkipInvisibleOnly, [switch]$EnableException ) begin { @@ -72,147 +67,137 @@ function Invoke-DbatoolsFormatter { $OSEOL = "`r`n" } - function Test-OnlyInvisibleChanges { - param( - [string]$OriginalContent, - [string]$ModifiedContent - ) - - # Normalize line endings to Unix style for comparison - $originalNormalized = $OriginalContent -replace '\r\n', "`n" -replace '\r', "`n" - $modifiedNormalized = $ModifiedContent -replace '\r\n', "`n" -replace '\r', "`n" + # Collect all paths for progress tracking + $allPaths = @() + } + process { + if (Test-FunctionInterrupt) { return } + # Collect all paths from pipeline + $allPaths += $Path + } + end { + if (Test-FunctionInterrupt) { return } - # Split into lines - $originalLines = $originalNormalized -split "`n" - $modifiedLines = $modifiedNormalized -split "`n" + $totalFiles = $allPaths.Count + $currentFile = 0 + $processedFiles = 0 + $updatedFiles = 0 - # Normalize each line: trim trailing whitespace and convert tabs to spaces - $originalLines = $originalLines | ForEach-Object { $_.TrimEnd().Replace("`t", " ") } - $modifiedLines = $modifiedLines | ForEach-Object { $_.TrimEnd().Replace("`t", " ") } + foreach ($p in $allPaths) { + $currentFile++ - # Remove trailing empty lines from both - while ($originalLines.Count -gt 0 -and $originalLines[-1] -eq '') { - $originalLines = $originalLines[0..($originalLines.Count - 2)] - } - while ($modifiedLines.Count -gt 0 -and $modifiedLines[-1] -eq '') { - $modifiedLines = $modifiedLines[0..($modifiedLines.Count - 2)] + try { + $realPath = (Resolve-Path -Path $p -ErrorAction Stop).Path + } catch { + Write-Progress -Activity "Formatting PowerShell files" -Status "Error resolving path: $p" -PercentComplete (($currentFile / $totalFiles) * 100) -CurrentOperation "File $currentFile of $totalFiles" + Stop-Function -Message "Cannot find or resolve $p" -Continue + continue } - # Compare the normalized content - if ($originalLines.Count -ne $modifiedLines.Count) { - return $false + # Skip directories + if (Test-Path -Path $realPath -PathType Container) { + Write-Progress -Activity "Formatting PowerShell files" -Status "Skipping directory: $realPath" -PercentComplete (($currentFile / $totalFiles) * 100) -CurrentOperation "File $currentFile of $totalFiles" + Write-Message -Level Verbose "Skipping directory: $realPath" + continue } - for ($i = 0; $i -lt $originalLines.Count; $i++) { - if ($originalLines[$i] -ne $modifiedLines[$i]) { - return $false + $fileName = Split-Path -Leaf $realPath + Write-Progress -Activity "Formatting PowerShell files" -Status "Processing: $fileName" -PercentComplete (($currentFile / $totalFiles) * 100) -CurrentOperation "File $currentFile of $totalFiles" + + $originalContent = Get-Content -Path $realPath -Raw -Encoding UTF8 + $content = $originalContent + + if ($OSEOL -eq "`r`n") { + # See #5830, we are in Windows territory here + # Is the file containing at least one `r ? + $containsCR = ($content -split "`r").Length -gt 1 + if (-not($containsCR)) { + # If not, maybe even on Windows the user is using Unix-style endings, which are supported + $OSEOL = "`n" } } - return $true - } + #strip ending empty lines + $content = $content -replace "(?s)$OSEOL\s*$" - function Format-ScriptContent { - param( - [string]$Content, - [string]$LineEnding - ) + # Preserve aligned assignments before formatting + # Look for patterns with multiple spaces before OR after the = sign + $alignedPatterns = [regex]::Matches($content, '(?m)^\s*(\$\w+|\w+)\s{2,}=\s*.+$|^\s*(\$\w+|\w+)\s*=\s{2,}.+$') + $placeholders = @{ } - # Strip ending empty lines - $Content = $Content -replace "(?s)$LineEnding\s*$" + foreach ($match in $alignedPatterns) { + $placeholder = "___ALIGNMENT_PLACEHOLDER_$($placeholders.Count)___" + $placeholders[$placeholder] = $match.Value + $content = $content.Replace($match.Value, $placeholder) + } try { - # Save original lines before formatting - $originalLines = $Content -split "`n" - - # Run the formatter - $formattedContent = Invoke-Formatter -ScriptDefinition $Content -Settings CodeFormattingOTBS -ErrorAction Stop - - # Automatically restore spaces before = signs - $formattedLines = $formattedContent -split "`n" - for ($i = 0; $i -lt $formattedLines.Count; $i++) { - if ($i -lt $originalLines.Count) { - # Check if original had multiple spaces before = - if ($originalLines[$i] -match '^(\s*)(.+?)(\s{2,})(=)(.*)$') { - $indent = $matches[1] - $beforeEquals = $matches[2] - $spacesBeforeEquals = $matches[3] - $rest = $matches[4] + $matches[5] - - # Apply the same spacing to the formatted line - if ($formattedLines[$i] -match '^(\s*)(.+?)(\s*)(=)(.*)$') { - $formattedLines[$i] = $matches[1] + $matches[2] + $spacesBeforeEquals + '=' + $matches[5] - } - } - } + $formattedContent = Invoke-Formatter -ScriptDefinition $content -Settings CodeFormattingOTBS -ErrorAction Stop + if ($formattedContent) { + $content = $formattedContent } - $Content = $formattedLines -join "`n" } catch { - Write-Message -Level Warning "Unable to format content" + # Just silently continue - the formatting might still work partially } - # Match the ending indentation of CBH with the starting one - $CBH = $CBHRex.Match($Content).Value + # Restore the aligned patterns + foreach ($key in $placeholders.Keys) { + $content = $content.Replace($key, $placeholders[$key]) + } + + #match the ending indentation of CBH with the starting one, see #4373 + $CBH = $CBHRex.Match($content).Value if ($CBH) { + #get starting spaces $startSpaces = $CBHStartRex.Match($CBH).Groups['spaces'] if ($startSpaces) { + #get end $newCBH = $CBHEndRex.Replace($CBH, "$startSpaces#>") if ($newCBH) { - $Content = $Content.Replace($CBH, $newCBH) + #replace the CBH + $content = $content.Replace($CBH, $newCBH) } } } - - # Apply case corrections and clean up lines - $correctCase = @('DbaInstanceParameter', 'PSCredential', 'PSCustomObject', 'PSItem') + $Utf8NoBomEncoding = New-Object System.Text.UTF8Encoding $False + $correctCase = @( + 'DbaInstanceParameter' + 'PSCredential' + 'PSCustomObject' + 'PSItem' + ) $realContent = @() - foreach ($line in $Content.Split("`n")) { + foreach ($line in $content.Split("`n")) { foreach ($item in $correctCase) { $line = $line -replace $item, $item } + #trim whitespace lines $realContent += $line.Replace("`t", " ").TrimEnd() } - return ($realContent -Join $LineEnding) - } - } - process { - if (Test-FunctionInterrupt) { return } - foreach ($p in $Path) { - try { - $realPath = (Resolve-Path -Path $p -ErrorAction Stop).Path - } catch { - Stop-Function -Message "Cannot find or resolve $p" -Continue - } + $newContent = $realContent -Join "$OSEOL" - # Read file once - $originalBytes = [System.IO.File]::ReadAllBytes($realPath) - $originalContent = [System.IO.File]::ReadAllText($realPath) + # Compare without empty lines to detect real changes + $originalNonEmpty = ($originalContent -split "[\r\n]+" | Where-Object { $_.Trim() }) -join "" + $newNonEmpty = ($newContent -split "[\r\n]+" | Where-Object { $_.Trim() }) -join "" - # Detect line ending style from original file - $detectedOSEOL = $OSEOL - if ($psVersionTable.Platform -ne 'Unix') { - # We're on Windows, check if file uses Unix endings - $containsCR = ($originalContent -split "`r").Length -gt 1 - if (-not($containsCR)) { - $detectedOSEOL = "`n" - } + if ($originalNonEmpty -ne $newNonEmpty) { + [System.IO.File]::WriteAllText($realPath, $newContent, $Utf8NoBomEncoding) + Write-Message -Level Verbose "Updated: $realPath" + $updatedFiles++ + } else { + Write-Message -Level Verbose "No changes needed: $realPath" } - # Format the content - $formattedContent = Format-ScriptContent -Content $originalContent -LineEnding $detectedOSEOL + $processedFiles++ + } - # If SkipInvisibleOnly is set, check if formatting would only change invisible characters - if ($SkipInvisibleOnly) { - if (Test-OnlyInvisibleChanges -OriginalContent $originalContent -ModifiedContent $formattedContent) { - Write-Verbose "Skipping $realPath - only invisible changes (BOM/line endings/whitespace)" - continue - } - } + # Complete the progress bar + Write-Progress -Activity "Formatting PowerShell files" -Status "Complete" -PercentComplete 100 -CurrentOperation "Processed $processedFiles files, updated $updatedFiles" + Start-Sleep -Milliseconds 500 # Brief pause to show completion + Write-Progress -Activity "Formatting PowerShell files" -Completed - # Save the formatted content - $Utf8NoBomEncoding = New-Object System.Text.UTF8Encoding $False - [System.IO.File]::WriteAllText($realPath, $formattedContent, $Utf8NoBomEncoding) - } + # Summary message + Write-Message -Level Verbose "Formatting complete: Processed $processedFiles files, updated $updatedFiles files" } } \ No newline at end of file diff --git a/tests/Disable-DbaDbEncryption.Tests.ps1 b/tests/Disable-DbaDbEncryption.Tests.ps1 index a6db4c4354a..7debaeec57e 100644 --- a/tests/Disable-DbaDbEncryption.Tests.ps1 +++ b/tests/Disable-DbaDbEncryption.Tests.ps1 @@ -1,15 +1,16 @@ -#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } param( $ModuleName = "dbatools", + $CommandName = "Disable-DbaDbEncryption", $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults ) -Describe "Disable-DbaDbEncryption" -Tag "UnitTests" { +Describe $CommandName -Tag UnitTests { Context "Parameter validation" { BeforeAll { - $command = Get-Command Disable-DbaDbEncryption - $expected = $TestConfig.CommonParameters - $expected += @( + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( "SqlInstance", "SqlCredential", "Database", @@ -19,18 +20,13 @@ Describe "Disable-DbaDbEncryption" -Tag "UnitTests" { ) } - It "Has parameter: <_>" -ForEach $expected { - $command | Should -HaveParameter $PSItem - } - - It "Should have exactly the number of expected parameters ($($expected.Count))" { - $hasparms = $command.Parameters.Values.Name | Where-Object { $PSItem -notin "WhatIf", "Confirm" } - Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "Disable-DbaDbEncryption" -Tag "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { $PSDefaultParameterValues["*:Confirm"] = $false $passwd = ConvertTo-SecureString "dbatools.IO" -AsPlainText -Force @@ -78,7 +74,7 @@ Describe "Disable-DbaDbEncryption" -Tag "IntegrationTests" { } It "Should complete without warnings" { - $warn | Where-Object { $_ -NotLike '*Connect-DbaInstance*'} | Should -BeNullOrEmpty + $warn | Where-Object { $_ -NotLike "*Connect-DbaInstance*" } | Should -BeNullOrEmpty } It "Should disable encryption" { @@ -93,17 +89,17 @@ Describe "Disable-DbaDbEncryption" -Tag "IntegrationTests" { $splatDisable = @{ SqlInstance = $TestConfig.instance2 - Database = $testDb.Name + Database = $testDb.Name } $results = Disable-DbaDbEncryption @splatDisable -WarningVariable warn 3> $null } It "Should complete without warnings" { - $warn | Where-Object { $_ -NotLike '*Connect-DbaInstance*'} | Should -BeNullOrEmpty + $warn | Where-Object { $_ -NotLike "*Connect-DbaInstance*" } | Should -BeNullOrEmpty } It "Should disable encryption" { $results.EncryptionEnabled | Should -Be $false } } -} +} \ No newline at end of file diff --git a/tests/Disable-DbaFilestream.Tests.ps1 b/tests/Disable-DbaFilestream.Tests.ps1 index d34b4a2ec0a..0b1246339e8 100644 --- a/tests/Disable-DbaFilestream.Tests.ps1 +++ b/tests/Disable-DbaFilestream.Tests.ps1 @@ -1,36 +1,73 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Disable-DbaFilestream", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Credential', 'Force', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Credential", + "Force", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } <# -Describe "Disable-DbaFilestream" -Tag "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { - $OriginalFileStream = Get-DbaFilestream -SqlInstance $TestConfig.instance1 + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # Store the original FileStream level to restore after testing + $originalFileStream = Get-DbaFilestream -SqlInstance $TestConfig.instance1 + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } AfterAll { - Set-DbaFilestream -SqlInstance $TestConfig.instance1 -FileStreamLevel $OriginalFileStream.InstanceAccessLevel -Force + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # Restore the original FileStream level + Set-DbaFilestream -SqlInstance $TestConfig.instance1 -FileStreamLevel $originalFileStream.InstanceAccessLevel -Force + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } Context "When changing FileStream Level" { BeforeAll { - $NewLevel = ($OriginalFileStream.FileStreamStateId + 1) % 3 #Move it on one, but keep it less than 4 with modulo division - $results = Set-DbaFilestream -SqlInstance $TestConfig.instance1 -FileStreamLevel $NewLevel -Force -WarningAction SilentlyContinue -ErrorVariable errvar -ErrorAction SilentlyContinue + # Move it on one, but keep it less than 4 with modulo division + $newLevel = ($originalFileStream.FileStreamStateId + 1) % 3 + $splatFilestream = @{ + SqlInstance = $TestConfig.instance1 + FileStreamLevel = $newLevel + Force = $true + WarningAction = "SilentlyContinue" + ErrorVariable = "errvar" + ErrorAction = "SilentlyContinue" + } + $results = Set-DbaFilestream @splatFilestream } It "Should change the FileStream Level" { - $results.InstanceAccessLevel | Should -Be $NewLevel + $results.InstanceAccessLevel | Should -Be $newLevel } } } diff --git a/tests/Disable-DbaForceNetworkEncryption.Tests.ps1 b/tests/Disable-DbaForceNetworkEncryption.Tests.ps1 index 3ab13c0a2bf..d2d3806e54a 100644 --- a/tests/Disable-DbaForceNetworkEncryption.Tests.ps1 +++ b/tests/Disable-DbaForceNetworkEncryption.Tests.ps1 @@ -1,35 +1,29 @@ -#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } param( - $ModuleName = "dbatools", + $ModuleName = "dbatools", + $CommandName = "Disable-DbaForceNetworkEncryption", $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults ) -Describe "Disable-DbaForceNetworkEncryption" -Tag "UnitTests" { +Describe $CommandName -Tag UnitTests { Context "Parameter validation" { BeforeAll { - $command = Get-Command Disable-DbaForceNetworkEncryption - $expected = $TestConfig.CommonParameters - $expected += @( + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( "SqlInstance", "Credential", - "EnableException", - "Confirm", - "WhatIf" + "EnableException" ) } - It "Has parameter: <_>" -ForEach $expected { - $command | Should -HaveParameter $PSItem - } - - It "Should have exactly the number of expected parameters ($($expected.Count))" { - $hasparms = $command.Parameters.Values.Name - Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "Disable-DbaForceNetworkEncryption" -Tag "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { Context "When disabling force network encryption" { BeforeAll { $results = Disable-DbaForceNetworkEncryption -SqlInstance $TestConfig.instance1 -EnableException @@ -39,4 +33,4 @@ Describe "Disable-DbaForceNetworkEncryption" -Tag "IntegrationTests" { $results.ForceEncryption | Should -BeFalse } } -} +} \ No newline at end of file diff --git a/tests/Disable-DbaHideInstance.Tests.ps1 b/tests/Disable-DbaHideInstance.Tests.ps1 index 6f9c7271ef1..803e4ab4b56 100644 --- a/tests/Disable-DbaHideInstance.Tests.ps1 +++ b/tests/Disable-DbaHideInstance.Tests.ps1 @@ -1,42 +1,51 @@ -#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } param( - $ModuleName = "dbatools", - $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults + $ModuleName = "dbatools", + $CommandName = "Disable-DbaHideInstance", + $PSDefaultParameterValues = $TestConfig.Defaults ) -Describe "Disable-DbaHideInstance" -Tag "UnitTests" { +Describe $CommandName -Tag UnitTests { Context "Parameter validation" { BeforeAll { - $command = Get-Command Disable-DbaHideInstance - $expected = $TestConfig.CommonParameters - $expected += @( + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( "SqlInstance", "Credential", - "EnableException", - "Confirm", - "WhatIf" + "EnableException" ) } - It "Has parameter: <_>" -ForEach $expected { - $command | Should -HaveParameter $PSItem - } - - It "Should have exactly the number of expected parameters ($($expected.Count))" { - $hasparms = $command.Parameters.Values.Name - Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "Disable-DbaHideInstance" -Tag "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { Context "When disabling hide instance" { BeforeAll { - $results = Disable-DbaHideInstance -SqlInstance $TestConfig.instance1 -EnableException + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + $hideInstanceResults = Disable-DbaHideInstance -SqlInstance $TestConfig.instance1 + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') + } + + AfterAll { + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # No specific cleanup needed for this test + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } It "Returns result with HideInstance set to false" { - $results.HideInstance | Should -BeFalse + $hideInstanceResults.HideInstance | Should -BeFalse } } -} +} \ No newline at end of file diff --git a/tests/Disable-DbaReplDistributor.Tests.ps1 b/tests/Disable-DbaReplDistributor.Tests.ps1 index 5fcb683ae50..763130768a7 100644 --- a/tests/Disable-DbaReplDistributor.Tests.ps1 +++ b/tests/Disable-DbaReplDistributor.Tests.ps1 @@ -1,6 +1,7 @@ -#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } param( - $ModuleName = "dbatools", + $ModuleName = "dbatools", + $CommandName = "Disable-DbaReplDistributor", $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults ) @@ -8,30 +9,23 @@ Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan Add-ReplicationLibrary -Describe "Disable-DbaReplDistributor" -Tag "UnitTests" { - BeforeAll { - $command = Get-Command Disable-DbaReplDistributor - $expected = $TestConfig.CommonParameters - $expected += @( - "SqlInstance", - "SqlCredential", - "Force", - "EnableException", - "Confirm", - "WhatIf" - ) - } - +Describe $CommandName -Tag UnitTests { Context "Parameter validation" { - It "Has parameter: <_>" -ForEach $expected { - $command | Should -HaveParameter $PSItem + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Force", + "EnableException" + ) } - It "Should have exactly the number of expected parameters ($($expected.Count))" { - $hasparms = $command.Parameters.Values.Name - Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } # Integration tests for replication are in GitHub Actions and run from \tests\gh-actions-repl-*.ps1 -} +} \ No newline at end of file diff --git a/tests/Disable-DbaReplPublishing.Tests.ps1 b/tests/Disable-DbaReplPublishing.Tests.ps1 index 5f069bc2400..abc97d82bc1 100644 --- a/tests/Disable-DbaReplPublishing.Tests.ps1 +++ b/tests/Disable-DbaReplPublishing.Tests.ps1 @@ -1,37 +1,31 @@ -#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } param( - $ModuleName = "dbatools", - $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults + $ModuleName = "dbatools", + $CommandName = "Disable-DbaReplPublishing", + $PSDefaultParameterValues = $TestConfig.Defaults ) Add-ReplicationLibrary -Describe "Disable-DbaReplPublishing" -Tag "UnitTests" { +Describe $CommandName -Tag UnitTests { Context "Parameter validation" { BeforeAll { - $command = Get-Command Disable-DbaReplPublishing - $expected = $TestConfig.CommonParameters - $expected += @( + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( "SqlInstance", "SqlCredential", "Force", - "EnableException", - "Confirm", - "WhatIf" + "EnableException" ) } - It "Has parameter: <_>" -ForEach $expected { - $command | Should -HaveParameter $PSItem - } - - It "Should have exactly the number of expected parameters ($($expected.Count))" { - $hasParams = $command.Parameters.Values.Name - Compare-Object -ReferenceObject $expected -DifferenceObject $hasParams | Should -BeNullOrEmpty + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } <# Integration tests for replication are in GitHub Actions and run from \tests\gh-actions-repl-*.ps1.ps1 -#> +#> \ No newline at end of file diff --git a/tests/Disable-DbaStartupProcedure.Tests.ps1 b/tests/Disable-DbaStartupProcedure.Tests.ps1 index dfaa7e991a0..d3b8a58e709 100644 --- a/tests/Disable-DbaStartupProcedure.Tests.ps1 +++ b/tests/Disable-DbaStartupProcedure.Tests.ps1 @@ -1,55 +1,67 @@ -#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } param( - $ModuleName = "dbatools", + $ModuleName = "dbatools", + $CommandName = "Disable-DbaStartupProcedure", $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults ) -Describe "Disable-DbaStartupProcedure" -Tag "UnitTests" { +Describe $CommandName -Tag UnitTests { Context "Parameter validation" { BeforeAll { - $command = Get-Command Disable-DbaStartupProcedure - $expected = $TestConfig.CommonParameters - $expected += @( + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( "SqlInstance", "SqlCredential", "StartupProcedure", "InputObject", - "EnableException", - "Confirm", - "WhatIf" + "EnableException" ) } - It "Has parameter: <_>" -ForEach $expected { - $command | Should -HaveParameter $PSItem - } - - It "Should have exactly the number of expected parameters ($($expected.Count))" { - $hasparms = $command.Parameters.Values.Name - Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "Disable-DbaStartupProcedure" -Tag "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # Set up test environment $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 $random = Get-Random $startupProcName = "StartUpProc$random" $startupProc = "dbo.$startupProcName" - $dbname = 'master' + $dbname = "master" $null = $server.Query("CREATE PROCEDURE $startupProc AS Select 1", $dbname) $null = $server.Query("EXEC sp_procoption '$startupProc', 'startup', 'on'", $dbname) + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } AfterAll { + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # Clean up test objects $null = $server.Query("DROP PROCEDURE $startupProc", $dbname) + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } Context "When disabling a startup procedure" { BeforeAll { - $result = Disable-DbaStartupProcedure -SqlInstance $TestConfig.instance2 -StartupProcedure $startupProc -Confirm:$false + $splatDisable = @{ + SqlInstance = $TestConfig.instance2 + StartupProcedure = $startupProc + Confirm = $false + } + $result = Disable-DbaStartupProcedure @splatDisable } It "Should return correct schema" { @@ -75,7 +87,12 @@ Describe "Disable-DbaStartupProcedure" -Tag "IntegrationTests" { Context "When disabling an already disabled procedure" { BeforeAll { - $result = Disable-DbaStartupProcedure -SqlInstance $TestConfig.instance2 -StartupProcedure $startupProc -Confirm:$false + $splatDisableAgain = @{ + SqlInstance = $TestConfig.instance2 + StartupProcedure = $startupProc + Confirm = $false + } + $result = Disable-DbaStartupProcedure @splatDisableAgain } It "Should return correct schema" { @@ -101,7 +118,12 @@ Describe "Disable-DbaStartupProcedure" -Tag "IntegrationTests" { Context "When using pipeline input" { BeforeAll { - $null = Enable-DbaStartupProcedure -SqlInstance $TestConfig.instance2 -StartupProcedure $startupProc -Confirm:$false + $splatEnable = @{ + SqlInstance = $TestConfig.instance2 + StartupProcedure = $startupProc + Confirm = $false + } + $null = Enable-DbaStartupProcedure @splatEnable $result = Get-DbaStartupProcedure -SqlInstance $TestConfig.instance2 | Disable-DbaStartupProcedure -Confirm:$false } @@ -125,4 +147,4 @@ Describe "Disable-DbaStartupProcedure" -Tag "IntegrationTests" { $result.Note | Should -Be "Disable succeded" } } -} +} \ No newline at end of file diff --git a/tests/Disable-DbaTraceFlag.Tests.ps1 b/tests/Disable-DbaTraceFlag.Tests.ps1 index 824c8d26086..764a96764ab 100644 --- a/tests/Disable-DbaTraceFlag.Tests.ps1 +++ b/tests/Disable-DbaTraceFlag.Tests.ps1 @@ -1,59 +1,71 @@ -#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } param( - $ModuleName = "dbatools", - $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults + $ModuleName = "dbatools", + $CommandName = "Disable-DbaTraceFlag", + $PSDefaultParameterValues = $TestConfig.Defaults ) -Describe "Disable-DbaTraceFlag" -Tag "UnitTests" { +Describe $CommandName -Tag UnitTests { Context "Parameter validation" { BeforeAll { - $command = Get-Command Disable-DbaTraceFlag - $expected = $TestConfig.CommonParameters - $expected += @( + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( "SqlInstance", "SqlCredential", "TraceFlag", - "EnableException", - "Confirm", - "WhatIf" + "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 + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "Disable-DbaTraceFlag" -Tag "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { - $server = Connect-DbaInstance -SqlInstance $TestConfig.instance1 + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # Explain what needs to be set up for the test: + # To test disabling trace flags, we need to ensure a trace flag is enabled first. + # We use trace flag 3226 which is safe for testing as it only suppresses backup success messages. + + # Set variables. They are available in all the It blocks. + $safeTraceFlag = 3226 + $server = Connect-DbaInstance -SqlInstance $TestConfig.instance1 $startingTraceFlags = Get-DbaTraceFlag -SqlInstance $server - $safeTraceFlag = 3226 + # Create the objects. if ($startingTraceFlags.TraceFlag -notcontains $safeTraceFlag) { $null = $server.Query("DBCC TRACEON($safeTraceFlag,-1)") } + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } AfterAll { + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # Cleanup all created object. if ($startingTraceFlags.TraceFlag -contains $safeTraceFlag) { $server.Query("DBCC TRACEON($safeTraceFlag,-1) WITH NO_INFOMSGS") } + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } Context "When disabling trace flags" { BeforeAll { - $results = Disable-DbaTraceFlag -SqlInstance $server -TraceFlag $safeTraceFlag + $disableResults = Disable-DbaTraceFlag -SqlInstance $server -TraceFlag $safeTraceFlag } It "Should disable trace flag $safeTraceFlag" { - $results.TraceFlag | Should -Contain $safeTraceFlag + $disableResults.TraceFlag | Should -Contain $safeTraceFlag } } -} +} \ No newline at end of file diff --git a/tests/Disconnect-DbaInstance.Tests.ps1 b/tests/Disconnect-DbaInstance.Tests.ps1 index 08c9c3f9030..6d1ec87ec69 100644 --- a/tests/Disconnect-DbaInstance.Tests.ps1 +++ b/tests/Disconnect-DbaInstance.Tests.ps1 @@ -1,45 +1,56 @@ -#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } param( - $ModuleName = "dbatools", - $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults + $ModuleName = "dbatools", + $CommandName = "Disconnect-DbaInstance", + $PSDefaultParameterValues = $TestConfig.Defaults ) -Describe "Disconnect-DbaInstance" -Tag "UnitTests" { +Describe $CommandName -Tag UnitTests { Context "Parameter validation" { BeforeAll { - $command = Get-Command Disconnect-DbaInstance - $expected = $TestConfig.CommonParameters - $expected += @( + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( "InputObject", - "EnableException", - "Confirm", - "WhatIf" + "EnableException" ) } - It "Has parameter: <_>" -ForEach $expected { - $command | Should -HaveParameter $PSItem - } - - It "Should have exactly the number of expected parameters ($($expected.Count))" { - $hasparms = $command.Parameters.Values.Name - Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "Disconnect-DbaInstance" -Tag "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { - $null = Connect-DbaInstance -SqlInstance $TestConfig.Instance1 + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true + + # Connect to instance for testing + $null = Connect-DbaInstance -SqlInstance $TestConfig.instance1 + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove("*-Dba*:EnableException") + } + + AfterAll { + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true + + # Cleanup - disconnect any remaining connections + $null = Get-DbaConnectedInstance | Disconnect-DbaInstance + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } Context "When disconnecting a server" { BeforeAll { - $results = Get-DbaConnectedInstance | Disconnect-DbaInstance + $disconnectResults = @(Get-DbaConnectedInstance | Disconnect-DbaInstance) } It "Returns results" { - $results | Should -Not -BeNullOrEmpty + $disconnectResults | Should -Not -BeNullOrEmpty } } -} +} \ No newline at end of file diff --git a/tests/Dismount-DbaDatabase.Tests.ps1 b/tests/Dismount-DbaDatabase.Tests.ps1 index d2a846425b2..a20cbeb1221 100644 --- a/tests/Dismount-DbaDatabase.Tests.ps1 +++ b/tests/Dismount-DbaDatabase.Tests.ps1 @@ -1,40 +1,38 @@ -#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } param( - $ModuleName = "dbatools", + $ModuleName = "dbatools", + $CommandName = "Dismount-DbaDatabase", $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults ) -Describe "Dismount-DbaDatabase" -Tag "UnitTests" { - BeforeAll { - $command = Get-Command Dismount-DbaDatabase - $expected = $TestConfig.CommonParameters - $expected += @( - "SqlInstance", - "SqlCredential", - "Database", - "InputObject", - "UpdateStatistics", - "Force", - "EnableException", - "Confirm", - "WhatIf" - ) - } +Describe $CommandName -Tag UnitTests { Context "Parameter validation" { - It "Has parameter: <_>" -ForEach $expected { - $command | Should -HaveParameter $PSItem + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Database", + "InputObject", + "UpdateStatistics", + "Force", + "EnableException" + ) } - It "Should have exactly the number of expected parameters ($($expected.Count))" { - $hasparms = $command.Parameters.Values.Name - Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "Dismount-DbaDatabase" -Tag "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { - Get-DbaProcess -SqlInstance $TestConfig.instance3 -Program 'dbatools PowerShell module - dbatools.io' | Stop-DbaProcess -WarningAction SilentlyContinue + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + Get-DbaProcess -SqlInstance $TestConfig.instance3 -Program "dbatools PowerShell module - dbatools.io" | Stop-DbaProcess -WarningAction SilentlyContinue $dbName = "dbatoolsci_detachattach" $null = Get-DbaDatabase -SqlInstance $TestConfig.instance3 -Database $dbName | Remove-DbaDatabase -Confirm:$false @@ -44,11 +42,19 @@ Describe "Dismount-DbaDatabase" -Tag "IntegrationTests" { foreach ($file in (Get-DbaDbFile -SqlInstance $TestConfig.instance3 -Database $dbName).PhysicalName) { $null = $fileStructure.Add($file) } + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } AfterAll { + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + $null = Mount-DbaDatabase -SqlInstance $TestConfig.instance3 -Database $dbName -FileStructure $fileStructure $null = Get-DbaDatabase -SqlInstance $TestConfig.instance3 -Database $dbName | Remove-DbaDatabase -Confirm:$false + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } Context "When detaching a single database" { @@ -68,7 +74,7 @@ Describe "Dismount-DbaDatabase" -Tag "IntegrationTests" { Context "When detaching databases with snapshots" { BeforeAll { - Get-DbaProcess -SqlInstance $TestConfig.instance3 -Program 'dbatools PowerShell module - dbatools.io' | Stop-DbaProcess -WarningAction SilentlyContinue + Get-DbaProcess -SqlInstance $TestConfig.instance3 -Program "dbatools PowerShell module - dbatools.io" | Stop-DbaProcess -WarningAction SilentlyContinue $server = Connect-DbaInstance -SqlInstance $TestConfig.instance3 $dbDetached = "dbatoolsci_dbsetstate_detached" @@ -88,9 +94,9 @@ Describe "Dismount-DbaDatabase" -Tag "IntegrationTests" { } AfterAll { - $null = Remove-DbaDbSnapshot -SqlInstance $TestConfig.instance3 -Database $dbWithSnapshot -Force - $null = Mount-DbaDatabase -SqlInstance $TestConfig.instance3 -Database $dbDetached -FileStructure $splatFileStructure - $null = Get-DbaDatabase -SqlInstance $TestConfig.instance3 -Database $dbDetached, $dbWithSnapshot | Remove-DbaDatabase -Confirm:$false + $null = Remove-DbaDbSnapshot -SqlInstance $TestConfig.instance3 -Database $dbWithSnapshot -Force -ErrorAction SilentlyContinue + $null = Mount-DbaDatabase -SqlInstance $TestConfig.instance3 -Database $dbDetached -FileStructure $splatFileStructure -ErrorAction SilentlyContinue + $null = Get-DbaDatabase -SqlInstance $TestConfig.instance3 -Database $dbDetached, $dbWithSnapshot | Remove-DbaDatabase -Confirm:$false -ErrorAction SilentlyContinue } It "Should skip detachment if database has snapshots" { @@ -112,4 +118,4 @@ Describe "Dismount-DbaDatabase" -Tag "IntegrationTests" { } } } -#$TestConfig.instance2 - to make it show up in appveyor, long story +#$TestConfig.instance2 - to make it show up in appveyor, long story \ No newline at end of file diff --git a/tests/Enable-DbaAgHadr.Tests.ps1 b/tests/Enable-DbaAgHadr.Tests.ps1 index 38913e70c07..9f1d211b7a9 100644 --- a/tests/Enable-DbaAgHadr.Tests.ps1 +++ b/tests/Enable-DbaAgHadr.Tests.ps1 @@ -1,47 +1,58 @@ #Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} param( - $ModuleName = "dbatools", + $ModuleName = "dbatools", + $CommandName = "Enable-DbaAgHadr", $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults ) -Describe "Enable-DbaAgHadr" -Tag "UnitTests" { +Describe $CommandName -Tag UnitTests { Context "Parameter validation" { BeforeAll { - $command = Get-Command Enable-DbaAgHadr - $expected = $TestConfig.CommonParameters - $expected += @( + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( "SqlInstance", "Credential", "Force", - "EnableException", - "Confirm", - "WhatIf" + "EnableException" ) } - It "Has parameter: <_>" -ForEach $expected { - $command | Should -HaveParameter $PSItem - } - - It "Should have exactly the number of expected parameters ($($expected.Count))" { - $hasparms = $command.Parameters.Values.Name - Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "Enable-DbaAgHadr" -Tag "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { - Disable-DbaAgHadr -SqlInstance $TestConfig.instance3 -Confirm:$false -Force + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # Disable HADR to ensure clean state for testing + Disable-DbaAgHadr -SqlInstance $TestConfig.instance3 -Force + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') + } + + AfterAll { + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # Disable HADR after test to restore original state + Disable-DbaAgHadr -SqlInstance $TestConfig.instance3 -Force -ErrorAction SilentlyContinue + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } Context "When enabling HADR" { BeforeAll { - $results = Enable-DbaAgHadr -SqlInstance $TestConfig.instance3 -Confirm:$false -Force + $results = Enable-DbaAgHadr -SqlInstance $TestConfig.instance3 -Force } It "Successfully enables HADR" { $results.IsHadrEnabled | Should -BeTrue } } -} +} \ No newline at end of file diff --git a/tests/Enable-DbaDbEncryption.Tests.ps1 b/tests/Enable-DbaDbEncryption.Tests.ps1 index b4ccfd1a46f..310cf028d36 100644 --- a/tests/Enable-DbaDbEncryption.Tests.ps1 +++ b/tests/Enable-DbaDbEncryption.Tests.ps1 @@ -1,41 +1,37 @@ -#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } param( - $ModuleName = "dbatools", - $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults + $ModuleName = "dbatools", + $CommandName = "Enable-DbaDbEncryption", + $PSDefaultParameterValues = $TestConfig.Defaults ) -Describe "Enable-DbaDbEncryption" -Tag "UnitTests" { +Describe $CommandName -Tag UnitTests { Context "Parameter validation" { BeforeAll { - $command = Get-Command Enable-DbaDbEncryption - $expected = $TestConfig.CommonParameters - $expected += @( + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( "SqlInstance", "SqlCredential", "Database", "EncryptorName", "InputObject", "Force", - "EnableException", - "Confirm", - "WhatIf" + "EnableException" ) } - It "Has parameter: <_>" -ForEach $expected { - $command | Should -HaveParameter $PSItem - } - - It "Should have exactly the number of expected parameters ($($expected.Count))" { - $hasparms = $command.Parameters.Values.Name - Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "Enable-DbaDbEncryption" -Tag "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { - $PSDefaultParameterValues["*:Confirm"] = $false + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + $passwd = ConvertTo-SecureString "dbatools.IO" -AsPlainText -Force $masterkey = Get-DbaDbMasterKey -SqlInstance $TestConfig.instance2 -Database master @@ -57,24 +53,32 @@ Describe "Enable-DbaDbEncryption" -Tag "IntegrationTests" { $testDb | New-DbaDbMasterKey -SecurePassword $passwd $testDb | New-DbaDbCertificate $testDb | New-DbaDbEncryptionKey -Force + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } AfterAll { + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + if ($testDb) { - $testDb | Remove-DbaDatabase + $testDb | Remove-DbaDatabase -ErrorAction SilentlyContinue } if ($delmastercert) { - $mastercert | Remove-DbaDbCertificate + $mastercert | Remove-DbaDbCertificate -ErrorAction SilentlyContinue } if ($delmasterkey) { - $masterkey | Remove-DbaDbMasterKey + $masterkey | Remove-DbaDbMasterKey -ErrorAction SilentlyContinue } + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } Context "When enabling encryption via pipeline" { It "Should enable encryption on a database" { - $results = $testDb | Enable-DbaDbEncryption -EncryptorName $mastercert.Name -Force - $results.EncryptionEnabled | Should -Be $true + $results = @($testDb | Enable-DbaDbEncryption -EncryptorName $mastercert.Name -Force) + $results[0].EncryptionEnabled | Should -Be $true } } @@ -84,8 +88,14 @@ Describe "Enable-DbaDbEncryption" -Tag "IntegrationTests" { } It "Should enable encryption on a database" { - $results = Enable-DbaDbEncryption -SqlInstance $TestConfig.instance2 -EncryptorName $mastercert.Name -Database $testDb.Name -Force - $results.EncryptionEnabled | Should -Be $true + $splatEnableEncryption = @{ + SqlInstance = $TestConfig.instance2 + EncryptorName = $mastercert.Name + Database = $testDb.Name + Force = $true + } + $results = @(Enable-DbaDbEncryption @splatEnableEncryption) + $results[0].EncryptionEnabled | Should -Be $true } } -} +} \ No newline at end of file diff --git a/tests/Enable-DbaFilestream.Tests.ps1 b/tests/Enable-DbaFilestream.Tests.ps1 index 40be3977390..7023b70ac3c 100644 --- a/tests/Enable-DbaFilestream.Tests.ps1 +++ b/tests/Enable-DbaFilestream.Tests.ps1 @@ -1,59 +1,66 @@ -#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } param( - $ModuleName = "dbatools", - $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults + $ModuleName = "dbatools", + $CommandName = "Enable-DbaFilestream", + $PSDefaultParameterValues = $TestConfig.Defaults ) -Describe "Enable-DbaFilestream" -Tag "UnitTests" { +Describe $CommandName -Tag UnitTests { Context "Parameter validation" { BeforeAll { - $command = Get-Command Enable-DbaFilestream - $expected = $TestConfig.CommonParameters - $expected += @( + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( "SqlInstance", "SqlCredential", "Credential", "FileStreamLevel", "ShareName", "Force", - "EnableException", - "Confirm", - "WhatIf" + "EnableException" ) } - It "Has parameter: <_>" -ForEach $expected { - $command | Should -HaveParameter $PSItem - } - - It "Should have exactly the number of expected parameters ($($expected.Count))" { - $hasparms = $command.Parameters.Values.Name - Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "Enable-DbaFilestream" -Tag "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { - $global:OriginalFileStream = Get-DbaFilestream -SqlInstance $TestConfig.instance1 + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true + + # Store the original FileStream level so we can restore it after the test + $originalFileStream = Get-DbaFilestream -SqlInstance $TestConfig.instance1 + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove("*-Dba*:EnableException") } AfterAll { - if ($global:OriginalFileStream.InstanceAccessLevel -eq 0) { - Disable-DbaFilestream -SqlInstance $TestConfig.instance1 -Confirm:$false -WarningAction SilentlyContinue + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true + + # Restore the original FileStream level + if ($originalFileStream.InstanceAccessLevel -eq 0) { + $null = Disable-DbaFilestream -SqlInstance $TestConfig.instance1 -Confirm:$false } else { - Enable-DbaFilestream -SqlInstance $TestConfig.instance1 -FileStreamLevel $global:OriginalFileStream.InstanceAccessLevel -Confirm:$false -WarningAction SilentlyContinue + $null = Enable-DbaFilestream -SqlInstance $TestConfig.instance1 -FileStreamLevel $originalFileStream.InstanceAccessLevel -Confirm:$false } + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } Context "When changing FileStream Level" { BeforeAll { - $NewLevel = ($global:OriginalFileStream.InstanceAccessLevel + 1) % 3 #Move it on one, but keep it less than 4 with modulo division - $results = Enable-DbaFilestream -SqlInstance $TestConfig.instance1 -FileStreamLevel $NewLevel -Confirm:$false -WarningAction SilentlyContinue + $newLevel = ($originalFileStream.InstanceAccessLevel + 1) % 3 #Move it on one, but keep it less than 4 with modulo division + $results = Enable-DbaFilestream -SqlInstance $TestConfig.instance1 -FileStreamLevel $newLevel -Confirm:$false } It "Should change the FileStream Level to the new value" { - $results.InstanceAccessLevel | Should -Be $NewLevel + $results.InstanceAccessLevel | Should -Be $newLevel } } -} +} \ No newline at end of file diff --git a/tests/Enable-DbaForceNetworkEncryption.Tests.ps1 b/tests/Enable-DbaForceNetworkEncryption.Tests.ps1 index a67b8dd32c7..8efc4e18a55 100644 --- a/tests/Enable-DbaForceNetworkEncryption.Tests.ps1 +++ b/tests/Enable-DbaForceNetworkEncryption.Tests.ps1 @@ -1,35 +1,44 @@ -#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } param( - $ModuleName = "dbatools", + $ModuleName = "dbatools", + $CommandName = "Enable-DbaForceNetworkEncryption", $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults ) -Describe "Enable-DbaForceNetworkEncryption" -Tag "UnitTests" { +Describe $CommandName -Tag UnitTests { Context "Parameter validation" { BeforeAll { - $command = Get-Command Enable-DbaForceNetworkEncryption - $expected = $TestConfig.CommonParameters - $expected += @( + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( "SqlInstance", "Credential", - "EnableException", - "Confirm", - "WhatIf" + "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 + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "Enable-DbaForceNetworkEncryption" -Tag "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { + BeforeAll { + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove("*-Dba*:EnableException") + } + + AfterAll { + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. + } + Context "When enabling force network encryption" { BeforeAll { $results = Enable-DbaForceNetworkEncryption -SqlInstance $TestConfig.instance1 -EnableException @@ -39,4 +48,4 @@ Describe "Enable-DbaForceNetworkEncryption" -Tag "IntegrationTests" { $results.ForceEncryption | Should -BeTrue } } -} +} \ No newline at end of file diff --git a/tests/Enable-DbaHideInstance.Tests.ps1 b/tests/Enable-DbaHideInstance.Tests.ps1 index d5f9bac77ad..2005a327901 100644 --- a/tests/Enable-DbaHideInstance.Tests.ps1 +++ b/tests/Enable-DbaHideInstance.Tests.ps1 @@ -1,46 +1,46 @@ -#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } param( - $ModuleName = "dbatools", + $ModuleName = "dbatools", + $CommandName = "Enable-DbaHideInstance", $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults ) -Describe "Enable-DbaHideInstance" -Tag "UnitTests" { +Describe $CommandName -Tag UnitTests { Context "Parameter validation" { BeforeAll { - $command = Get-Command Enable-DbaHideInstance - $expected = $TestConfig.CommonParameters - $expected += @( + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( "SqlInstance", "Credential", - "EnableException", - "Confirm", - "WhatIf" + "EnableException" ) } - It "Has parameter: <_>" -ForEach $expected { - $command | Should -HaveParameter $PSItem - } - - It "Should have exactly the number of expected parameters ($($expected.Count))" { - $hasparms = $command.Parameters.Values.Name - Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "Enable-DbaHideInstance" -Tag "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { - $instance = $TestConfig.instance1 - $results = Enable-DbaHideInstance -SqlInstance $instance -EnableException + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true + + $testInstance = $TestConfig.instance1 + $results = Enable-DbaHideInstance -SqlInstance $testInstance + + $PSDefaultParameterValues.Remove("*-Dba*:EnableException") } AfterAll { - $null = Disable-DbaHideInstance -SqlInstance $instance + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true + + $null = Disable-DbaHideInstance -SqlInstance $testInstance -ErrorAction SilentlyContinue } It "Returns an object with HideInstance property set to true" { $results | Should -Not -BeNullOrEmpty $results.HideInstance | Should -BeTrue } -} +} \ No newline at end of file diff --git a/tests/Enable-DbaReplDistributor.Tests.ps1 b/tests/Enable-DbaReplDistributor.Tests.ps1 index e9de66c058f..710dd02c5c9 100644 --- a/tests/Enable-DbaReplDistributor.Tests.ps1 +++ b/tests/Enable-DbaReplDistributor.Tests.ps1 @@ -1,33 +1,27 @@ -#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } param( - $ModuleName = "dbatools", - $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults + $ModuleName = "dbatools", + $CommandName = "Enable-DbaReplDistributor", + $PSDefaultParameterValues = $TestConfig.Defaults ) Add-ReplicationLibrary -Describe "Enable-DbaReplDistributor" -Tag "UnitTests" { +Describe $CommandName -Tag UnitTests { Context "Parameter validation" { BeforeAll { - $command = Get-Command Enable-DbaReplDistributor - $expected = $TestConfig.CommonParameters - $expected += @( + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( "SqlInstance", "SqlCredential", "DistributionDatabase", - "EnableException", - "Confirm", - "WhatIf" + "EnableException" ) } - It "Has parameter: <_>" -ForEach $expected { - $command | Should -HaveParameter $PSItem - } - - It "Should have exactly the number of expected parameters ($($expected.Count))" { - $hasparms = $command.Parameters.Values.Name - Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } \ No newline at end of file diff --git a/tests/Enable-DbaReplPublishing.Tests.ps1 b/tests/Enable-DbaReplPublishing.Tests.ps1 index ab45b3a37e4..4c445b36aad 100644 --- a/tests/Enable-DbaReplPublishing.Tests.ps1 +++ b/tests/Enable-DbaReplPublishing.Tests.ps1 @@ -1,12 +1,13 @@ #Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} param( - $ModuleName = "dbatools", + $ModuleName = "dbatools", + $CommandName = "Enable-DbaReplPublishing", $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults ) Add-ReplicationLibrary -Describe "Enable-DbaReplPublishing" -Tag "UnitTests" { +Describe $CommandName -Tag UnitTests { Context "Parameter validation" { BeforeAll { $command = Get-Command Enable-DbaReplPublishing @@ -22,13 +23,15 @@ Describe "Enable-DbaReplPublishing" -Tag "UnitTests" { ) } - It "Has parameter: <_>" -ForEach $expected { - $command | Should -HaveParameter $PSItem + foreach ($param in $expected) { + It "Has parameter: $param" { + $command | Should -HaveParameter $param + } } - It "Should have exactly the number of expected parameters ($($expected.Count))" { - $hasparms = $command.Parameters.Values.Name - Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty + It "Should have exactly the expected parameters" { + $hasParameters = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } \ No newline at end of file diff --git a/tests/Enable-DbaStartupProcedure.Tests.ps1 b/tests/Enable-DbaStartupProcedure.Tests.ps1 index 46e460ec942..499ca558e43 100644 --- a/tests/Enable-DbaStartupProcedure.Tests.ps1 +++ b/tests/Enable-DbaStartupProcedure.Tests.ps1 @@ -1,53 +1,67 @@ -#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } param( $ModuleName = "dbatools", + $CommandName = "Enable-DbaStartupProcedure", $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults ) -Describe "Enable-DbaStartupProcedure" -Tag "UnitTests" { +Describe $CommandName -Tag UnitTests { Context "Parameter validation" { BeforeAll { - $command = Get-Command Enable-DbaStartupProcedure - $expected = ($TestConfig = Get-TestConfig).CommonParameters - $expected += @( + $command = Get-Command $CommandName + $hasParameters = $command.Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( "SqlInstance", "SqlCredential", "StartupProcedure", - "EnableException", - "WhatIf", - "Confirm" + "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 + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "Enable-DbaStartupProcedure" -Tag "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { - $server = Connect-DbaInstance -SqlInstance $TestConfig.Instance2 - $random = Get-Random - $startupProcName = "StartUpProc$random" - $startupProc = "dbo.$startupProcName" - $dbname = 'master' + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true + # Set variables. They are available in all the It blocks. + $server = Connect-DbaInstance -SqlInstance $TestConfig.Instance2 + $random = Get-Random + $startupProcName = "StartUpProc$random" + $startupProc = "dbo.$startupProcName" + $dbname = "master" + + # Create the test startup procedure $null = $server.Query("CREATE PROCEDURE $startupProc AS Select 1", $dbname) + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove("*-Dba*:EnableException") } AfterAll { + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true + + # Cleanup all created objects. $null = $server.Query("DROP PROCEDURE $startupProc", $dbname) + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } Context "When enabling a startup procedure" { BeforeAll { - $result = Enable-DbaStartupProcedure -SqlInstance $TestConfig.Instance2 -StartupProcedure $startupProc -Confirm:$false + $splatEnable = @{ + SqlInstance = $TestConfig.Instance2 + StartupProcedure = $startupProc + Confirm = $false + } + $result = Enable-DbaStartupProcedure @splatEnable } It "Should return successful enable results" { @@ -61,7 +75,12 @@ Describe "Enable-DbaStartupProcedure" -Tag "IntegrationTests" { Context "When enabling an already enabled procedure" { BeforeAll { - $result = Enable-DbaStartupProcedure -SqlInstance $TestConfig.Instance2 -StartupProcedure $startupProc -Confirm:$false + $splatAlreadyEnabled = @{ + SqlInstance = $TestConfig.Instance2 + StartupProcedure = $startupProc + Confirm = $false + } + $result = Enable-DbaStartupProcedure @splatAlreadyEnabled } It "Should return already enabled status" { @@ -75,7 +94,14 @@ Describe "Enable-DbaStartupProcedure" -Tag "IntegrationTests" { Context "When enabling a non-existent procedure" { BeforeAll { - $result = Enable-DbaStartupProcedure -SqlInstance $TestConfig.Instance2 -StartupProcedure "Unknown.NotHere" -Confirm:$false -WarningVariable warn -WarningAction SilentlyContinue + $splatNonExistent = @{ + SqlInstance = $TestConfig.Instance2 + StartupProcedure = "Unknown.NotHere" + Confirm = $false + WarningVariable = "warn" + WarningAction = "SilentlyContinue" + } + $result = Enable-DbaStartupProcedure @splatNonExistent } It "Should return null" { @@ -88,7 +114,14 @@ Describe "Enable-DbaStartupProcedure" -Tag "IntegrationTests" { Context "When using an invalid procedure name format" { BeforeAll { - $result = Enable-DbaStartupProcedure -SqlInstance $TestConfig.Instance2 -StartupProcedure "Four.Part.Schema.Name" -Confirm:$false -WarningVariable warn -WarningAction SilentlyContinue + $splatInvalidFormat = @{ + SqlInstance = $TestConfig.Instance2 + StartupProcedure = "Four.Part.Schema.Name" + Confirm = $false + WarningVariable = "warn" + WarningAction = "SilentlyContinue" + } + $result = Enable-DbaStartupProcedure @splatInvalidFormat } It "Should return null" { @@ -98,4 +131,4 @@ Describe "Enable-DbaStartupProcedure" -Tag "IntegrationTests" { $warn | Should -Match "Requested procedure Four.Part.Schema.Name could not be parsed" } } -} +} \ No newline at end of file diff --git a/tests/Enable-DbaTraceFlag.Tests.ps1 b/tests/Enable-DbaTraceFlag.Tests.ps1 index ce469b3db87..fc021478e2f 100644 --- a/tests/Enable-DbaTraceFlag.Tests.ps1 +++ b/tests/Enable-DbaTraceFlag.Tests.ps1 @@ -1,59 +1,65 @@ -#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } param( - $ModuleName = "dbatools", + $ModuleName = "dbatools", + $CommandName = "Enable-DbaTraceFlag", $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults ) -Describe "Enable-DbaTraceFlag" -Tag "UnitTests" { +Describe $CommandName -Tag UnitTests { Context "Parameter validation" { BeforeAll { - $command = Get-Command Enable-DbaTraceFlag - $expected = $TestConfig.CommonParameters - $expected += @( + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( "SqlInstance", "SqlCredential", "TraceFlag", - "EnableException", - "Confirm", - "WhatIf" + "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 + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "Enable-DbaTraceFlag" -Tag "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { - $instance = Connect-DbaInstance -SqlInstance $TestConfig.instance2 + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # Set variables for the test + $testInstance = Connect-DbaInstance -SqlInstance $TestConfig.instance2 $safeTraceFlag = 3226 $startingTraceFlags = Get-DbaTraceFlag -SqlInstance $TestConfig.instance2 if ($startingTraceFlags.TraceFlag -contains $safeTraceFlag) { - $instance.Query("DBCC TRACEOFF($safeTraceFlag,-1)") + $testInstance.Query("DBCC TRACEOFF($safeTraceFlag,-1)") } + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } AfterAll { + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + if ($startingTraceFlags.TraceFlag -notcontains $safeTraceFlag) { - $instance.Query("DBCC TRACEOFF($safeTraceFlag,-1)") + $testInstance.Query("DBCC TRACEOFF($safeTraceFlag,-1)") } + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } Context "When enabling a trace flag" { BeforeAll { - $results = Enable-DbaTraceFlag -SqlInstance $instance -TraceFlag $safeTraceFlag + $enableResults = Enable-DbaTraceFlag -SqlInstance $testInstance -TraceFlag $safeTraceFlag } It "Should enable the specified trace flag" { - $results.TraceFlag -contains $safeTraceFlag | Should -BeTrue + $enableResults.TraceFlag -contains $safeTraceFlag | Should -BeTrue } } -} +} \ No newline at end of file diff --git a/tests/Expand-DbaDbLogFile.Tests.ps1 b/tests/Expand-DbaDbLogFile.Tests.ps1 index ce7c93b64f1..2d12bd43a7b 100644 --- a/tests/Expand-DbaDbLogFile.Tests.ps1 +++ b/tests/Expand-DbaDbLogFile.Tests.ps1 @@ -1,34 +1,70 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Expand-DbaDbLogFile", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'ExcludeDatabase', 'TargetLogSize', 'IncrementSize', 'LogFileId', 'ShrinkLogFile', 'ShrinkSize', 'BackupDirectory', 'ExcludeDiskSpaceValidation', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Database", + "ExcludeDatabase", + "TargetLogSize", + "IncrementSize", + "LogFileId", + "ShrinkLogFile", + "ShrinkSize", + "BackupDirectory", + "ExcludeDiskSpaceValidation", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # Set variables. They are available in all the It blocks. $db1Name = "dbatoolsci_expand" $db1 = New-DbaDatabase -SqlInstance $TestConfig.instance1 -Name $db1Name + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } + AfterAll { + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + Remove-DbaDatabase -Confirm:$false -SqlInstance $TestConfig.instance1 -Database $db1Name + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } Context "Ensure command functionality" { + BeforeAll { + $results = Expand-DbaDbLogFile -SqlInstance $TestConfig.instance1 -Database $db1 -TargetLogSize 128 + } - $results = Expand-DbaDbLogFile -SqlInstance $TestConfig.instance1 -Database $db1 -TargetLogSize 128 - - It -Skip "Should have correct properties" { - $ExpectedProps = 'ComputerName,InstanceName,SqlInstance,Database,ID,Name,LogFileCount,InitialSize,CurrentSize,InitialVLFCount,CurrentVLFCount'.Split(',') - ($results[0].PsObject.Properties.Name | Sort-Object) | Should Be ($ExpectedProps | Sort-Object) + It "Should have correct properties" -Skip:$true { + $ExpectedProps = "ComputerName", "InstanceName", "SqlInstance", "Database", "ID", "Name", "LogFileCount", "InitialSize", "CurrentSize", "InitialVLFCount", "CurrentVLFCount" + ($results[0].PsObject.Properties.Name | Sort-Object) | Should -Be ($ExpectedProps | Sort-Object) } It "Should have database name and ID of $db1" { @@ -44,4 +80,4 @@ Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { } } } -} +} \ No newline at end of file diff --git a/tests/Export-DbaBinaryFile.Tests.ps1 b/tests/Export-DbaBinaryFile.Tests.ps1 index fc66fb48f65..0ef9931ee4f 100644 --- a/tests/Export-DbaBinaryFile.Tests.ps1 +++ b/tests/Export-DbaBinaryFile.Tests.ps1 @@ -1,43 +1,118 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Export-DbaBinaryFile", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'Table', 'Schema', 'FileNameColumn', 'BinaryColumn', 'Path', 'FilePath', 'Query', 'InputObject', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Database", + "Table", + "Schema", + "FileNameColumn", + "BinaryColumn", + "Path", + "Query", + "FilePath", + "InputObject", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { - BeforeEach { - $db = Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database tempdb - $null = $db.Query("CREATE TABLE [dbo].[BunchOFilezz]([FileName123] [nvarchar](50) NULL, [TheFile123] [image] NULL)") - $null = Import-DbaBinaryFile -SqlInstance $TestConfig.instance2 -Database tempdb -Table BunchOFilezz -FilePath "$($TestConfig.appveyorlabrepo)\azure\adalsql.msi" - $null = Get-ChildItem "$($TestConfig.appveyorlabrepo)\certificates" | Import-DbaBinaryFile -SqlInstance $TestConfig.instance2 -Database tempdb -Table BunchOFilezz +Describe $CommandName -Tag IntegrationTests { + BeforeAll { + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true + + # For all the backups that we want to clean up after the test, we create a directory that we can delete at the end. + $exportPath = "C:\temp\exports-$CommandName-$(Get-Random)" + $null = New-Item -Path $exportPath -ItemType Directory -Force + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove("*-Dba*:EnableException") } - AfterEach { - try { + + AfterAll { + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true + + # Remove the export directory. + Remove-Item -Path $exportPath -Recurse -ErrorAction SilentlyContinue + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. + } + + Context "When exporting binary files from database" { + BeforeEach { + # We want to run all commands in the BeforeEach block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true + + # Set up test table and data for each test + $db = Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database tempdb + $null = $db.Query("CREATE TABLE [dbo].[BunchOFilezz]([FileName123] [nvarchar](50) NULL, [TheFile123] [image] NULL)") + + $splatImportMain = @{ + SqlInstance = $TestConfig.instance2 + Database = "tempdb" + Table = "BunchOFilezz" + FilePath = "$($TestConfig.appveyorlabrepo)\azure\adalsql.msi" + } + $null = Import-DbaBinaryFile @splatImportMain + + $null = Get-ChildItem "$($TestConfig.appveyorlabrepo)\certificates" | Import-DbaBinaryFile -SqlInstance $TestConfig.instance2 -Database tempdb -Table BunchOFilezz + + # We want to run all commands outside of the BeforeEach block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove("*-Dba*:EnableException") + } + + AfterEach { + # We want to run all commands in the AfterEach block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true + + # Clean up test table + $db = Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database tempdb $null = $db.Query("DROP TABLE dbo.BunchOFilezz") - Remove-Item -Path C:\temp\exports -Recurse - } catch { - $null = 1 + + # Clean up exported files for this specific test + Remove-Item -Path "$exportPath\*" -Recurse -ErrorAction SilentlyContinue + + # We want to run all commands outside of the AfterEach block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove("*-Dba*:EnableException") } - } - It "exports the table data to file" { - $results = Export-DbaBinaryFile -SqlInstance $TestConfig.instance2 -Database tempdb -Path C:\temp\exports - $results.Name.Count | Should -Be 3 - $results.Name | Should -Be @('adalsql.msi', 'localhost.crt', 'localhost.pfx') - } + It "Exports the table data to file using SqlInstance" { + $splatExport = @{ + SqlInstance = $TestConfig.instance2 + Database = "tempdb" + Path = $exportPath + } + $results = Export-DbaBinaryFile @splatExport + + $results.Name.Count | Should -BeExactly 3 + $results.Name | Should -Be @("adalsql.msi", "localhost.crt", "localhost.pfx") + } - It "exports the table data to file" { - $results = Get-DbaBinaryFileTable -SqlInstance $TestConfig.instance2 -Database tempdb | Export-DbaBinaryFile -Path C:\temp\exports - $results.Name.Count | Should -Be 3 - $results.Name | Should -Be @('adalsql.msi', 'localhost.crt', 'localhost.pfx') + It "Exports the table data to file using pipeline from Get-DbaBinaryFileTable" { + $results = Get-DbaBinaryFileTable -SqlInstance $TestConfig.instance2 -Database tempdb | Export-DbaBinaryFile -Path $exportPath + + $results.Name.Count | Should -BeExactly 3 + $results.Name | Should -Be @("adalsql.msi", "localhost.crt", "localhost.pfx") + } } -} +} \ No newline at end of file diff --git a/tests/Export-DbaCredential.Tests.ps1 b/tests/Export-DbaCredential.Tests.ps1 index e31d3801c7a..feaf3afaede 100644 --- a/tests/Export-DbaCredential.Tests.ps1 +++ b/tests/Export-DbaCredential.Tests.ps1 @@ -1,102 +1,193 @@ -$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', 'Identity', 'SqlCredential', 'Credential', 'Path', 'FilePath', 'ExcludePassword', 'Append', 'InputObject', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Export-DbaCredential", + $PSDefaultParameterValues = $TestConfig.Defaults +) + +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "Identity", + "SqlCredential", + "Credential", + "Path", + "FilePath", + "ExcludePassword", + "Append", + "InputObject", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } - -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { - $plaintext = "ReallyT3rrible!" - $password = ConvertTo-SecureString $plaintext -AsPlainText -Force - $null = New-DbaCredential -SqlInstance $TestConfig.instance2 -Name dbatoolsci_CaptainAcred -Identity dbatoolsci_CaptainAcredId -Password $password - $null = New-DbaCredential -SqlInstance $TestConfig.instance2 -Identity dbatoolsci_Hulk -Password $password - $allfiles = @() + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true + + # For all the files that we want to clean up after the test, we create an array that we can iterate through at the end. + $allFiles = @() + + # Explain what needs to be set up for the test: + # To test exporting credentials, we need to create test credentials with specific identities and passwords. + + # Set variables. They are available in all the It blocks. + $plaintext = "ReallyT3rrible!" + $password = ConvertTo-SecureString $plaintext -AsPlainText -Force + $captainCredName = "dbatoolsci_CaptainAcred" + $captainCredIdentity = "dbatoolsci_CaptainAcredId" + $hulkCredIdentity = "dbatoolsci_Hulk" + + # Create the objects. + $splatCaptain = @{ + SqlInstance = $TestConfig.instance2 + Name = $captainCredName + Identity = $captainCredIdentity + Password = $password + EnableException = $true + } + $null = New-DbaCredential @splatCaptain + + $splatHulk = @{ + SqlInstance = $TestConfig.instance2 + Identity = $hulkCredIdentity + Password = $password + EnableException = $true + } + $null = New-DbaCredential @splatHulk + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove("*-Dba*:EnableException") } + AfterAll { - try { - (Get-DbaCredential -SqlInstance $TestConfig.instance2 -Identity dbatoolsci_CaptainAcred, dbatoolsci_Hulk -ErrorAction Stop -WarningAction SilentlyContinue).Drop() - } catch { } - $null = $allfiles | Remove-Item -ErrorAction Ignore + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true + + # Cleanup all created objects. + $splatCleanup = @{ + SqlInstance = $TestConfig.instance2 + Identity = $captainCredIdentity, $hulkCredIdentity + EnableException = $true + WarningAction = "SilentlyContinue" + } + $credentialsToRemove = Get-DbaCredential @splatCleanup + if ($credentialsToRemove) { + $credentialsToRemove.Drop() + } + + # Remove all test files. + Remove-Item -Path $allFiles -ErrorAction SilentlyContinue + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } - Context "Should export all credentails" { - $file = Export-DbaCredential -SqlInstance $TestConfig.instance2 - $results = Get-Content -Path $file -Raw - $allfiles += $file + Context "Should export all credentials" { + BeforeAll { + $exportFile = Export-DbaCredential -SqlInstance $TestConfig.instance2 + $exportResults = Get-Content -Path $exportFile -Raw + $allFiles += $exportFile + } + It "Should have information" { - $results | Should -Not -Be Null + $exportResults | Should -Not -BeNullOrEmpty } + It "Should have all users" { - $results | Should -Match 'CaptainACred|Hulk' + $exportResults | Should -Match "CaptainACred|Hulk" } + It "Should have the password" { - $results | Should -Match 'ReallyT3rrible!' + $exportResults | Should -Match "ReallyT3rrible!" } } Context "Should export a specific credential" { - $filepath = "$env:USERPROFILE\Documents\dbatoolsci_credential.sql" - $null = Export-DbaCredential -SqlInstance $TestConfig.instance2 -Identity 'dbatoolsci_CaptainAcredId' -FilePath $filepath - $results = Get-Content -Path $filepath - $allfiles += $filepath + BeforeAll { + $specificFilePath = "$env:USERPROFILE\Documents\dbatoolsci_credential.sql" + $splatExportSpecific = @{ + SqlInstance = $TestConfig.instance2 + Identity = $captainCredIdentity + FilePath = $specificFilePath + } + $null = Export-DbaCredential @splatExportSpecific + $specificResults = Get-Content -Path $specificFilePath + $allFiles += $specificFilePath + } It "Should have information" { - $results | Should Not Be Null + $specificResults | Should -Not -BeNullOrEmpty } It "Should only have one credential" { - $results | Should Match 'CaptainAcred' + $specificResults | Should -Match "CaptainAcred" } It "Should have the password" { - $results | Should Match 'ReallyT3rrible!' + $specificResults | Should -Match "ReallyT3rrible!" } } - Context "Should export a specific credential and append it to exisiting export" { - $filepath = "$env:USERPROFILE\Documents\dbatoolsci_credential.sql" - $null = Export-DbaCredential -SqlInstance $TestConfig.instance2 -Identity 'dbatoolsci_Hulk' -FilePath $filepath -Append - $results = Get-Content -Path $filepath + Context "Should export a specific credential and append it to existing export" { + BeforeAll { + $appendFilePath = "$env:USERPROFILE\Documents\dbatoolsci_credential.sql" + $splatExportAppend = @{ + SqlInstance = $TestConfig.instance2 + Identity = $hulkCredIdentity + FilePath = $appendFilePath + Append = $true + } + $null = Export-DbaCredential @splatExportAppend + $appendResults = Get-Content -Path $appendFilePath + } It "Should have information" { - $results | Should Not Be Null + $appendResults | Should -Not -BeNullOrEmpty } - It "Should have multiple credential" { - $results | Should Match 'Hulk|CaptainA' + It "Should have multiple credentials" { + $appendResults | Should -Match "Hulk|CaptainA" } It "Should have the password" { - $results | Should Match 'ReallyT3rrible!' + $appendResults | Should -Match "ReallyT3rrible!" } } Context "Should export a specific credential excluding the password" { - $filepath = "$env:USERPROFILE\Documents\temp-credential.sql" - $null = Export-DbaCredential -SqlInstance $TestConfig.instance2 -Identity 'dbatoolsci_CaptainAcredId' -FilePath $filepath -ExcludePassword - $results = Get-Content -Path $filepath - $allfiles += $filepath + BeforeAll { + $excludePasswordFilePath = "$env:USERPROFILE\Documents\temp-credential.sql" + $splatExportNoPassword = @{ + SqlInstance = $TestConfig.instance2 + Identity = $captainCredIdentity + FilePath = $excludePasswordFilePath + ExcludePassword = $true + } + $null = Export-DbaCredential @splatExportNoPassword + $excludePasswordResults = Get-Content -Path $excludePasswordFilePath + $allFiles += $excludePasswordFilePath + } It "Should have information" { - $results | Should Not Be $null + $excludePasswordResults | Should -Not -BeNullOrEmpty } It "Should contain the correct identity (see #7282)" { - $results | Should Match "IDENTITY = N'dbatoolsci_CaptainAcredId'" + $excludePasswordResults | Should -Match "IDENTITY = N'dbatoolsci_CaptainAcredId'" } It "Should not have the password" { - $results | Should Not Match 'ReallyT3rrible!' + $excludePasswordResults | Should -Not -Match "ReallyT3rrible!" } } -} +} \ No newline at end of file diff --git a/tests/Export-DbaDacPackage.Tests.ps1 b/tests/Export-DbaDacPackage.Tests.ps1 index 4bef8bd2487..67dcb61b0ea 100644 --- a/tests/Export-DbaDacPackage.Tests.ps1 +++ b/tests/Export-DbaDacPackage.Tests.ps1 @@ -1,20 +1,50 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Export-DbaDacPackage", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'ExcludeDatabase', 'AllUserDatabases', 'Path', 'FilePath', 'DacOption', 'ExtendedParameters', 'ExtendedProperties', 'Type', '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 $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Database", + "ExcludeDatabase", + "AllUserDatabases", + "Path", + "FilePath", + "DacOption", + "ExtendedParameters", + "ExtendedProperties", + "Type", + "Table", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # For all the backups that we want to clean up after the test, we create a directory that we can delete at the end. + # Other files can be written there as well, maybe we change the name of that variable later. But for now we focus on backups. + $testFolder = "$($TestConfig.Temp)\$CommandName-$(Get-Random)" + $random = Get-Random $dbname = "dbatoolsci_exportdacpac_$random" try { @@ -27,15 +57,31 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { FROM sys.objects") } catch { } # No idea why appveyor can't handle this - $testFolder = 'C:\Temp\dacpacs' - $dbName2 = "dbatoolsci:2_$random" $dbName2Escaped = "dbatoolsci`$2_$random" $null = New-DbaDatabase -SqlInstance $TestConfig.instance1 -Name $dbName2 + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } + AfterAll { - Remove-DbaDatabase -SqlInstance $TestConfig.instance1 -Database $dbname, $dbName2 -Confirm:$false + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # Cleanup all created object. + $splatRemoveDb = @{ + SqlInstance = $TestConfig.instance1 + Database = $dbname, $dbName2 + Confirm = $false + } + Remove-DbaDatabase @splatRemoveDb + + # Remove the backup directory. + Remove-Item -Path $testFolder -Recurse -ErrorAction SilentlyContinue + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } # See https://github.com/dataplat/dbatools/issues/7038 @@ -47,96 +93,137 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { It "Database names with invalid filesystem chars are successfully exported" { $result = Export-DbaDacPackage -SqlInstance $TestConfig.instance1 -Database $dbname, $dbName2 - $result.Path.Count | Should -Be 2 + $result.Path.Count | Should -BeExactly 2 $result.Path[0] | Should -BeLike "*$($dbName)*" $result.Path[1] | Should -BeLike "*$($dbName2Escaped)*" } } + Context "Extract dacpac" { BeforeEach { - New-Item $testFolder -ItemType Directory -Force - Push-Location $testFolder + $currentTestFolder = "$testFolder\dacpac-$(Get-Random)" + New-Item $currentTestFolder -ItemType Directory -Force + Push-Location $currentTestFolder } + AfterEach { Pop-Location - Remove-Item $testFolder -Force -Recurse + Remove-Item $currentTestFolder -Force -Recurse -ErrorAction SilentlyContinue } - if ((Get-DbaDbTable -SqlInstance $TestConfig.instance1 -Database $dbname -Table example)) { + + BeforeAll { + $tableExists = Get-DbaDbTable -SqlInstance $TestConfig.instance1 -Database $dbname -Table example + } + + It "exports a dacpac" -Skip:(-not $tableExists) { # Sometimes appveyor bombs - It "exports a dacpac" { - $results = Export-DbaDacPackage -SqlInstance $TestConfig.instance1 -Database $dbname - $results.Path | Should -Not -BeNullOrEmpty - Test-Path $results.Path | Should -Be $true - if (($results).Path) { - Remove-Item -Confirm:$false -Path ($results).Path -ErrorAction SilentlyContinue - } + $results = Export-DbaDacPackage -SqlInstance $TestConfig.instance1 -Database $dbname + $results.Path | Should -Not -BeNullOrEmpty + Test-Path $results.Path | Should -BeTrue + if (($results).Path) { + Remove-Item -Confirm:$false -Path ($results).Path -ErrorAction SilentlyContinue + } + } + + It "exports to the correct directory" -Skip:(-not $tableExists) { + $relativePath = ".\" + $expectedPath = (Resolve-Path $relativePath).Path + $results = Export-DbaDacPackage -SqlInstance $TestConfig.instance1 -Database $dbname -Path $relativePath + $results.Path | Split-Path | Should -Be $expectedPath + Test-Path $results.Path | Should -BeTrue + } + + It "exports dacpac with a table list" -Skip:(-not $tableExists) { + $relativePath = ".\extract.dacpac" + $expectedPath = Join-Path (Get-Item .) "extract.dacpac" + $splatExportTable = @{ + SqlInstance = $TestConfig.instance1 + Database = $dbname + FilePath = $relativePath + Table = "example" } - It "exports to the correct directory" { - $relativePath = '.\' - $expectedPath = (Resolve-Path $relativePath).Path - $results = Export-DbaDacPackage -SqlInstance $TestConfig.instance1 -Database $dbname -Path $relativePath - $results.Path | Split-Path | Should -Be $expectedPath - Test-Path $results.Path | Should -Be $true + $results = Export-DbaDacPackage @splatExportTable + $results.Path | Should -Be $expectedPath + Test-Path $results.Path | Should -BeTrue + if (($results).Path) { + Remove-Item -Confirm:$false -Path ($results).Path -ErrorAction SilentlyContinue } - It "exports dacpac with a table list" { - $relativePath = '.\extract.dacpac' - $expectedPath = Join-Path (Get-Item .) 'extract.dacpac' - $results = Export-DbaDacPackage -SqlInstance $TestConfig.instance1 -Database $dbname -FilePath $relativePath -Table example - $results.Path | Should -Be $expectedPath - Test-Path $results.Path | Should -Be $true - if (($results).Path) { - Remove-Item -Confirm:$false -Path ($results).Path -ErrorAction SilentlyContinue - } + } + + It "uses EXE to extract dacpac" -Skip:(-not $tableExists) { + $exportProperties = "/p:ExtractAllTableData=True" + $splatExportExtended = @{ + SqlInstance = $TestConfig.instance1 + Database = $dbname + ExtendedProperties = $exportProperties } - It "uses EXE to extract dacpac" { - $exportProperties = "/p:ExtractAllTableData=True" - $results = Export-DbaDacPackage -SqlInstance $TestConfig.instance1 -Database $dbname -ExtendedProperties $exportProperties - $results.Path | Should -Not -BeNullOrEmpty - Test-Path $results.Path | Should -Be $true - if (($results).Path) { - Remove-Item -Confirm:$false -Path ($results).Path -ErrorAction SilentlyContinue - } + $results = Export-DbaDacPackage @splatExportExtended + $results.Path | Should -Not -BeNullOrEmpty + Test-Path $results.Path | Should -BeTrue + if (($results).Path) { + Remove-Item -Confirm:$false -Path ($results).Path -ErrorAction SilentlyContinue } } } + Context "Extract bacpac" { BeforeEach { - New-Item $testFolder -ItemType Directory -Force - Push-Location $testFolder + $currentTestFolder = "$testFolder\bacpac-$(Get-Random)" + New-Item $currentTestFolder -ItemType Directory -Force + Push-Location $currentTestFolder } + AfterEach { Pop-Location - Remove-Item $testFolder -Force -Recurse + Remove-Item $currentTestFolder -Force -Recurse -ErrorAction SilentlyContinue + } + + BeforeAll { + $tableExists = Get-DbaDbTable -SqlInstance $TestConfig.instance1 -Database $dbname -Table example } - if ((Get-DbaDbTable -SqlInstance $TestConfig.instance1 -Database $dbname -Table example)) { + + It "exports a bacpac" -Skip:(-not $tableExists) { # Sometimes appveyor bombs - It "exports a bacpac" { - $results = Export-DbaDacPackage -SqlInstance $TestConfig.instance1 -Database $dbname -Type Bacpac - $results.Path | Should -Not -BeNullOrEmpty - Test-Path $results.Path | Should -Be $true - if (($results).Path) { - Remove-Item -Confirm:$false -Path ($results).Path -ErrorAction SilentlyContinue - } + $results = Export-DbaDacPackage -SqlInstance $TestConfig.instance1 -Database $dbname -Type Bacpac + $results.Path | Should -Not -BeNullOrEmpty + Test-Path $results.Path | Should -BeTrue + if (($results).Path) { + Remove-Item -Confirm:$false -Path ($results).Path -ErrorAction SilentlyContinue } - It "exports bacpac with a table list" { - $relativePath = '.\extract.bacpac' - $expectedPath = Join-Path (Get-Item .) 'extract.bacpac' - $results = Export-DbaDacPackage -SqlInstance $TestConfig.instance1 -Database $dbname -FilePath $relativePath -Table example -Type Bacpac - $results.Path | Should -Be $expectedPath - Test-Path $results.Path | Should -Be $true - if (($results).Path) { - Remove-Item -Confirm:$false -Path ($results).Path -ErrorAction SilentlyContinue - } + } + + It "exports bacpac with a table list" -Skip:(-not $tableExists) { + $relativePath = ".\extract.bacpac" + $expectedPath = Join-Path (Get-Item .) "extract.bacpac" + $splatExportBacpac = @{ + SqlInstance = $TestConfig.instance1 + Database = $dbname + FilePath = $relativePath + Table = "example" + Type = "Bacpac" } - It "uses EXE to extract bacpac" { - $exportProperties = "/p:TargetEngineVersion=Default" - $results = Export-DbaDacPackage -SqlInstance $TestConfig.instance1 -Database $dbname -ExtendedProperties $exportProperties -Type Bacpac - $results.Path | Should -Not -BeNullOrEmpty - Test-Path $results.Path | Should -Be $true - if (($results).Path) { - Remove-Item -Confirm:$false -Path ($results).Path -ErrorAction SilentlyContinue - } + $results = Export-DbaDacPackage @splatExportBacpac + $results.Path | Should -Be $expectedPath + Test-Path $results.Path | Should -BeTrue + if (($results).Path) { + Remove-Item -Confirm:$false -Path ($results).Path -ErrorAction SilentlyContinue + } + } + + It "uses EXE to extract bacpac" -Skip:(-not $tableExists) { + $exportProperties = "/p:TargetEngineVersion=Default" + $splatExportBacpacExt = @{ + SqlInstance = $TestConfig.instance1 + Database = $dbname + ExtendedProperties = $exportProperties + Type = "Bacpac" + } + $results = Export-DbaDacPackage @splatExportBacpacExt + $results.Path | Should -Not -BeNullOrEmpty + Test-Path $results.Path | Should -BeTrue + if (($results).Path) { + Remove-Item -Confirm:$false -Path ($results).Path -ErrorAction SilentlyContinue } } } -} +} \ No newline at end of file diff --git a/tests/Export-DbaDbRole.Tests.ps1 b/tests/Export-DbaDbRole.Tests.ps1 index e70895f7718..92786dbcd83 100644 --- a/tests/Export-DbaDbRole.Tests.ps1 +++ b/tests/Export-DbaDbRole.Tests.ps1 @@ -1,29 +1,61 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Export-DbaDbRole", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'InputObject', 'ScriptingOptionsObject', 'Database', 'Role', 'ExcludeRole', 'ExcludeFixedRole', 'IncludeRoleMember', 'Path', 'FilePath', 'Passthru', 'BatchSeparator', 'NoClobber', 'Append', 'NoPrefix', 'Encoding', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "InputObject", + "ScriptingOptionsObject", + "Database", + "Role", + "ExcludeRole", + "ExcludeFixedRole", + "IncludeRoleMember", + "Path", + "FilePath", + "Passthru", + "BatchSeparator", + "NoClobber", + "Append", + "NoPrefix", + "Encoding", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { - $AltExportPath = "$env:USERPROFILE\Documents" - $outputFile1 = "$AltExportPath\Dbatoolsci_DbRole_CustomFile1.sql" - try { - $random = Get-Random - $dbname1 = "dbatoolsci_exportdbadbrole$random" - $login1 = "dbatoolsci_exportdbadbrole_login1$random" - $user1 = "dbatoolsci_exportdbadbrole_user1$random" - $dbRole = "dbatoolsci_SpExecute$random" + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + $altExportPath = "$env:USERPROFILE\Documents" + $outputFile1 = "$altExportPath\Dbatoolsci_DbRole_CustomFile1.sql" + $resourcesToCleanup = @($outputFile1) + + $random = Get-Random + $dbname1 = "dbatoolsci_exportdbadbrole$random" + $login1 = "dbatoolsci_exportdbadbrole_login1$random" + $user1 = "dbatoolsci_exportdbadbrole_user1$random" + $dbRole = "dbatoolsci_SpExecute$random" + try { $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 $null = $server.Query("CREATE DATABASE [$dbname1]") $null = $server.Query("CREATE LOGIN [$login1] WITH PASSWORD = 'GoodPass1234!'") @@ -33,56 +65,77 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { $server.Databases[$dbname1].ExecuteNonQuery("GRANT SELECT ON SCHEMA::dbo to [$dbRole]") $server.Databases[$dbname1].ExecuteNonQuery("GRANT EXECUTE ON SCHEMA::dbo to [$dbRole]") $server.Databases[$dbname1].ExecuteNonQuery("GRANT VIEW DEFINITION ON SCHEMA::dbo to [$dbRole]") - } catch {} + } catch { + # Ignore setup errors for now + } + + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } + AfterAll { + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + try { Remove-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname1 -Confirm:$false Remove-DbaLogin -SqlInstance $TestConfig.instance2 -Login $login1 -Confirm:$false - } catch { } - (Get-ChildItem $outputFile1 -ErrorAction SilentlyContinue) | Remove-Item -ErrorAction SilentlyContinue + } catch { + # Ignore cleanup errors + } + + Remove-Item -Path $resourcesToCleanup -ErrorAction SilentlyContinue } Context "Check if output file was created" { + BeforeAll { + $null = Export-DbaDbRole -SqlInstance $TestConfig.instance2 -Database msdb -FilePath $outputFile1 + } - $null = Export-DbaDbRole -SqlInstance $TestConfig.instance2 -Database msdb -FilePath $outputFile1 It "Exports results to one sql file" { - (Get-ChildItem $outputFile1).Count | Should Be 1 + (Get-ChildItem $outputFile1).Count | Should -Be 1 } + It "Exported file is bigger than 0" { - (Get-ChildItem $outputFile1).Length | Should BeGreaterThan 0 + (Get-ChildItem $outputFile1).Length | Should -BeGreaterThan 0 } } Context "Check piping support" { + BeforeAll { + $role = Get-DbaDbRole -SqlInstance $TestConfig.instance2 -Database $dbname1 -Role $dbRole + $null = $role | Export-DbaDbRole -FilePath $outputFile1 + $global:results = $role | Export-DbaDbRole -Passthru + } - $role = Get-DbaDbRole -SqlInstance $TestConfig.instance2 -Database $dbname1 -Role $dbRole - $null = $role | Export-DbaDbRole -FilePath $outputFile1 It "Exports results to one sql file" { - (Get-ChildItem $outputFile1).Count | Should Be 1 + (Get-ChildItem $outputFile1).Count | Should -Be 1 } + It "Exported file is bigger than 0" { - (Get-ChildItem $outputFile1).Length | Should BeGreaterThan 0 + (Get-ChildItem $outputFile1).Length | Should -BeGreaterThan 0 } - $script:results = $role | Export-DbaDbRole -Passthru It "should include the defined BatchSeparator" { - $script:results -match "GO" + $global:results -match "GO" } + It "should include the role" { - $script:results -match "CREATE ROLE [$dbRole]" + $global:results -match "CREATE ROLE [$dbRole]" } + It "should include GRANT EXECUTE ON SCHEMA" { - $script:results -match "GRANT EXECUTE ON SCHEMA::[dbo] TO [$dbRole];" + $global:results -match "GRANT EXECUTE ON SCHEMA::[dbo] TO [$dbRole];" } + It "should include GRANT SELECT ON SCHEMA" { - $script:results -match "GRANT SELECT ON SCHEMA::[dbo] TO [$dbRole];" + $global:results -match "GRANT SELECT ON SCHEMA::[dbo] TO [$dbRole];" } + It "should include GRANT VIEW DEFINITION ON SCHEMA" { - $script:results -match "GRANT VIEW DEFINITION ON SCHEMA::[dbo] TO [$dbRole];" + $global:results -match "GRANT VIEW DEFINITION ON SCHEMA::[dbo] TO [$dbRole];" } + It "should include ALTER ROLE ADD MEMBER" { - $script:results -match "ALTER ROLE [$dbRole] ADD MEMBER [$user1];" + $global:results -match "ALTER ROLE [$dbRole] ADD MEMBER [$user1];" } } -} +} \ No newline at end of file diff --git a/tests/Export-DbaDbTableData.Tests.ps1 b/tests/Export-DbaDbTableData.Tests.ps1 index 67ebc1b3f31..f4bcf3af912 100644 --- a/tests/Export-DbaDbTableData.Tests.ps1 +++ b/tests/Export-DbaDbTableData.Tests.ps1 @@ -1,50 +1,86 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Export-DbaDbTableData", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'InputObject', 'Path', 'FilePath', 'Encoding', 'BatchSeparator', 'NoPrefix', 'Passthru', 'NoClobber', 'Append', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "InputObject", + "Path", + "FilePath", + "Encoding", + "BatchSeparator", + "NoPrefix", + "Passthru", + "NoClobber", + "Append", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # Set up test database connection and test tables $db = Get-DbaDatabase -SqlInstance $TestConfig.instance1 -Database tempdb $null = $db.Query("CREATE TABLE dbo.dbatoolsci_example (id int); INSERT dbo.dbatoolsci_example SELECT top 10 1 FROM sys.objects") $null = $db.Query("Select * into dbatoolsci_temp from sys.databases") + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } + AfterAll { + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # Cleanup test tables try { $null = $db.Query("DROP TABLE dbo.dbatoolsci_example") $null = $db.Query("DROP TABLE dbo.dbatoolsci_temp") } catch { $null = 1 } - } - It "exports the table data" { - $escaped = [regex]::escape('INSERT [dbo].[dbatoolsci_example] ([id]) VALUES (1)') - $secondescaped = [regex]::escape('INSERT [dbo].[dbatoolsci_temp] ([name], [database_id],') - $results = Get-DbaDbTable -SqlInstance $TestConfig.instance1 -Database tempdb -Table dbatoolsci_example | Export-DbaDbTableData -Passthru - "$results" | Should -match $escaped - $results = Get-DbaDbTable -SqlInstance $TestConfig.instance1 -Database tempdb -Table dbatoolsci_temp | Export-DbaDbTableData -Passthru - "$results" | Should -Match $secondescaped + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } - It "supports piping more than one table" { - $escaped = [regex]::escape('INSERT [dbo].[dbatoolsci_example] ([id]) VALUES (1)') - $secondescaped = [regex]::escape('INSERT [dbo].[dbatoolsci_temp] ([name], [database_id],') - $results = Get-DbaDbTable -SqlInstance $TestConfig.instance1 -Database tempdb -Table dbatoolsci_example, dbatoolsci_temp | Export-DbaDbTableData -Passthru - "$results" | Should -match $escaped - "$results" | Should -match $secondescaped + Context "When exporting table data" { + It "exports the table data" { + $escaped = [regex]::escape("INSERT [dbo].[dbatoolsci_example] ([id]) VALUES (1)") + $secondescaped = [regex]::escape("INSERT [dbo].[dbatoolsci_temp] ([name], [database_id],") + $results = Get-DbaDbTable -SqlInstance $TestConfig.instance1 -Database tempdb -Table dbatoolsci_example | Export-DbaDbTableData -Passthru + "$results" | Should -Match $escaped + $results = Get-DbaDbTable -SqlInstance $TestConfig.instance1 -Database tempdb -Table dbatoolsci_temp | Export-DbaDbTableData -Passthru + "$results" | Should -Match $secondescaped + } + + It "supports piping more than one table" { + $escaped = [regex]::escape("INSERT [dbo].[dbatoolsci_example] ([id]) VALUES (1)") + $secondescaped = [regex]::escape("INSERT [dbo].[dbatoolsci_temp] ([name], [database_id],") + $results = Get-DbaDbTable -SqlInstance $TestConfig.instance1 -Database tempdb -Table dbatoolsci_example, dbatoolsci_temp | Export-DbaDbTableData -Passthru + "$results" | Should -Match $escaped + "$results" | Should -Match $secondescaped + } } -} +} \ No newline at end of file diff --git a/tests/Export-DbaDiagnosticQuery.Tests.ps1 b/tests/Export-DbaDiagnosticQuery.Tests.ps1 index 3c4090a86ae..88ba6641a45 100644 --- a/tests/Export-DbaDiagnosticQuery.Tests.ps1 +++ b/tests/Export-DbaDiagnosticQuery.Tests.ps1 @@ -1,27 +1,67 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Export-DbaDiagnosticQuery", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'InputObject', 'ConvertTo', 'Path', 'Suffix', 'NoPlanExport', 'NoQueryExport', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "InputObject", + "ConvertTo", + "Path", + "Suffix", + "NoPlanExport", + "NoQueryExport", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { + BeforeAll { + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # For all the backups that we want to clean up after the test, we create a directory that we can delete at the end. + # Other files can be written there as well, maybe we change the name of that variable later. But for now we focus on backups. + $backupPath = "$($TestConfig.Temp)\$CommandName-$(Get-Random)" + $null = New-Item -Path $backupPath -ItemType Directory + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') + } + AfterAll { - Get-ChildItem "C:\temp\dbatoolsci" -Recurse | Remove-Item -ErrorAction Ignore - Get-Item "C:\temp\dbatoolsci" | Remove-Item -ErrorAction Ignore + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # Remove the backup directory. + Remove-Item -Path $backupPath -Recurse -ErrorAction SilentlyContinue + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } + Context "Verifying output" { It "exports results to one file and creates directory if required" { - $null = Invoke-DbaDiagnosticQuery -SqlInstance $TestConfig.instance2 -QueryName 'Memory Clerk Usage' | Export-DbaDiagnosticQuery -Path "C:\temp\dbatoolsci" - (Get-ChildItem "C:\temp\dbatoolsci").Count | Should Be 1 + $splatInvoke = @{ + SqlInstance = $TestConfig.instance2 + QueryName = "Memory Clerk Usage" + } + $null = Invoke-DbaDiagnosticQuery @splatInvoke | Export-DbaDiagnosticQuery -Path $backupPath + (Get-ChildItem $backupPath).Count | Should -BeExactly 1 } } -} +} \ No newline at end of file diff --git a/tests/Export-DbaExecutionPlan.Tests.ps1 b/tests/Export-DbaExecutionPlan.Tests.ps1 index 89a15f6f968..cd62633ba4c 100644 --- a/tests/Export-DbaExecutionPlan.Tests.ps1 +++ b/tests/Export-DbaExecutionPlan.Tests.ps1 @@ -1,14 +1,33 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Export-DbaExecutionPlan", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'ExcludeDatabase', 'Path', 'SinceCreation', 'SinceLastExecution', 'InputObject', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Database", + "ExcludeDatabase", + "Path", + "SinceCreation", + "SinceLastExecution", + "InputObject", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } diff --git a/tests/Export-DbaInstance.Tests.ps1 b/tests/Export-DbaInstance.Tests.ps1 index 8223f7ee81c..408b4470ee6 100644 --- a/tests/Export-DbaInstance.Tests.ps1 +++ b/tests/Export-DbaInstance.Tests.ps1 @@ -358,4 +358,4 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { # placeholder for a future test with availability groups It -Skip "Export availability groups" { } -} +} \ No newline at end of file diff --git a/tests/Export-DbaLinkedServer.Tests.ps1 b/tests/Export-DbaLinkedServer.Tests.ps1 index dd29fdec44d..9378a028b38 100644 --- a/tests/Export-DbaLinkedServer.Tests.ps1 +++ b/tests/Export-DbaLinkedServer.Tests.ps1 @@ -1,14 +1,31 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Export-DbaLinkedServer", + $PSDefaultParameterValues = $TestConfig.Defaults +) -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'LinkedServer', 'SqlCredential', 'Credential', 'Path', 'FilePath', 'ExcludePassword', 'Append', 'InputObject', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "LinkedServer", + "SqlCredential", + "Credential", + "Path", + "FilePath", + "ExcludePassword", + "Append", + "InputObject", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } diff --git a/tests/Export-DbaPfDataCollectorSetTemplate.Tests.ps1 b/tests/Export-DbaPfDataCollectorSetTemplate.Tests.ps1 index 23ff591bae5..3d0e76aebd1 100644 --- a/tests/Export-DbaPfDataCollectorSetTemplate.Tests.ps1 +++ b/tests/Export-DbaPfDataCollectorSetTemplate.Tests.ps1 @@ -1,33 +1,66 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Export-DbaPfDataCollectorSetTemplate", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'ComputerName', 'Credential', 'CollectorSet', 'Path', 'FilePath', 'InputObject', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "ComputerName", + "Credential", + "CollectorSet", + "Path", + "FilePath", + "InputObject", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { - BeforeEach { - $null = Get-DbaPfDataCollectorSetTemplate -Template 'Long Running Queries' | Import-DbaPfDataCollectorSetTemplate +Describe $CommandName -Tag IntegrationTests { + BeforeAll { + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # Set up collector set for testing + $null = Get-DbaPfDataCollectorSetTemplate -Template "Long Running Queries" | Import-DbaPfDataCollectorSetTemplate + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } + AfterAll { - $null = Get-DbaPfDataCollectorSet -CollectorSet 'Long Running Queries' | Remove-DbaPfDataCollectorSet -Confirm:$false + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # Cleanup + $null = Get-DbaPfDataCollectorSet -CollectorSet "Long Running Queries" | Remove-DbaPfDataCollectorSet -Confirm:$false + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } + Context "Verifying command returns all the required results" { - It "returns a file system object" { - $results = Get-DbaPfDataCollectorSet -CollectorSet 'Long Running Queries' | Export-DbaPfDataCollectorSetTemplate - $results.BaseName | Should Be 'Long Running Queries' + It "returns a file system object using piped input" { + $results = Get-DbaPfDataCollectorSet -CollectorSet "Long Running Queries" | Export-DbaPfDataCollectorSetTemplate + $results.BaseName | Should -Be "Long Running Queries" } - It "returns a file system object" { - $results = Export-DbaPfDataCollectorSetTemplate -CollectorSet 'Long Running Queries' - $results.BaseName | Should Be 'Long Running Queries' + + It "returns a file system object using direct parameter" { + $results = Export-DbaPfDataCollectorSetTemplate -CollectorSet "Long Running Queries" + $results.BaseName | Should -Be "Long Running Queries" } } } \ No newline at end of file diff --git a/tests/Export-DbaRegServer.Tests.ps1 b/tests/Export-DbaRegServer.Tests.ps1 index ac84fdb8d76..3b11689e435 100644 --- a/tests/Export-DbaRegServer.Tests.ps1 +++ b/tests/Export-DbaRegServer.Tests.ps1 @@ -1,20 +1,42 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Export-DbaRegServer", + $PSDefaultParameterValues = $TestConfig.Defaults +) + 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 $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "InputObject", + "Path", + "FilePath", + "CredentialPersistenceType", + "EnableException", + "Group", + "ExcludeGroup", + "Overwrite" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeEach { + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true + $srvName = "dbatoolsci-server1" $group = "dbatoolsci-group1" $regSrvName = "dbatoolsci-server12" @@ -38,26 +60,31 @@ Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { $newServer3 = Add-DbaRegServer -SqlInstance $TestConfig.instance2 -ServerName $srvName3 -Name $regSrvName3 -Description $regSrvDesc3 $random = Get-Random - $newDirectory = "C:\temp\$random" + $newDirectory = "$($TestConfig.Temp)\$CommandName-$random" + $null = New-Item -Path $newDirectory -ItemType Directory -Force + + $PSDefaultParameterValues.Remove("*-Dba*:EnableException") } AfterEach { + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true + 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 + $results, $results2, $results3 | Remove-Item -ErrorAction SilentlyContinue - Remove-Item $newDirectory -ErrorAction Ignore -Recurse -Force + Remove-Item $newDirectory -ErrorAction SilentlyContinue -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 + $results.Extension -eq ".xml" | Should -Be $true } It "should create a specific xml file when using Path" { $results2 = $newGroup2 | Export-DbaRegServer -Path $newDirectory $results2 -is [System.IO.FileInfo] | Should -Be $true - $results2.FullName | Should -match 'C\:\\temp' + $results2.FullName | Should -Match "C:\\temp" Get-Content -Path $results2 -Raw | Should -Match $group2 } @@ -152,4 +179,4 @@ Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { $fileText | Should -Match $group $fileText | Should -Not -Match $group2 } -} +} \ No newline at end of file diff --git a/tests/Export-DbaReplServerSetting.Tests.ps1 b/tests/Export-DbaReplServerSetting.Tests.ps1 index 60263b015aa..f50031479e0 100644 --- a/tests/Export-DbaReplServerSetting.Tests.ps1 +++ b/tests/Export-DbaReplServerSetting.Tests.ps1 @@ -1,17 +1,37 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Export-DbaReplServerSetting", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig - Add-ReplicationLibrary -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Path', 'FilePath', 'ScriptOption', 'InputObject', 'Encoding', 'Passthru', 'NoClobber', 'Append', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Path", + "FilePath", + "ScriptOption", + "InputObject", + "Encoding", + "Passthru", + "NoClobber", + "Append", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } diff --git a/tests/Export-DbaServerRole.Tests.ps1 b/tests/Export-DbaServerRole.Tests.ps1 index 174001f17ce..783c38964d1 100644 --- a/tests/Export-DbaServerRole.Tests.ps1 +++ b/tests/Export-DbaServerRole.Tests.ps1 @@ -1,88 +1,141 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Export-DbaServerRole", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { +Describe $CommandName -Tag UnitTests { Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'InputObject', 'ScriptingOptionsObject', 'ServerRole', 'ExcludeServerRole', 'ExcludeFixedRole', 'IncludeRoleMember', 'Path', 'FilePath', 'Passthru', 'BatchSeparator', 'NoClobber', 'Append', 'NoPrefix', 'Encoding', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "InputObject", + "ScriptingOptionsObject", + "ServerRole", + "ExcludeServerRole", + "ExcludeFixedRole", + "IncludeRoleMember", + "Path", + "FilePath", + "Passthru", + "BatchSeparator", + "NoClobber", + "Append", + "NoPrefix", + "Encoding", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # Create a directory for test output files $AltExportPath = "$env:USERPROFILE\Documents" $outputFile = "$AltExportPath\Dbatoolsci_ServerRole.sql" - try { - $random = Get-Random - $login1 = "dbatoolsci_exportdbaserverrole_login1$random" - $svRole = "dbatoolsci_ScriptPermissions$random" - - $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 - $null = $server.Query("CREATE LOGIN [$login1] WITH PASSWORD = 'GoodPass1234!'") - $null = $server.Query("CREATE SERVER ROLE [$svRole] AUTHORIZATION [$login1]") - $null = $server.Query("ALTER SERVER ROLE [dbcreator] ADD MEMBER [$svRole]") - $null = $server.Query("GRANT CREATE TRACE EVENT NOTIFICATION TO [$svRole]") - $null = $server.Query("DENY SELECT ALL USER SECURABLES TO [$svRole]") - $null = $server.Query("GRANT VIEW ANY DEFINITION TO [$svRole]") - $null = $server.Query("GRANT VIEW ANY DATABASE TO [$svRole]") - } catch {} + + # Create test objects + $random = Get-Random + $login1 = "dbatoolsci_exportdbaserverrole_login1$random" + $svRole = "dbatoolsci_ScriptPermissions$random" + + $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 + $null = $server.Query("CREATE LOGIN [$login1] WITH PASSWORD = 'GoodPass1234!'") + $null = $server.Query("CREATE SERVER ROLE [$svRole] AUTHORIZATION [$login1]") + $null = $server.Query("ALTER SERVER ROLE [dbcreator] ADD MEMBER [$svRole]") + $null = $server.Query("GRANT CREATE TRACE EVENT NOTIFICATION TO [$svRole]") + $null = $server.Query("DENY SELECT ALL USER SECURABLES TO [$svRole]") + $null = $server.Query("GRANT VIEW ANY DEFINITION TO [$svRole]") + $null = $server.Query("GRANT VIEW ANY DATABASE TO [$svRole]") + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } + AfterAll { - try { - Remove-DbaServerRole -SqlInstance $TestConfig.instance2 -ServerRole $svRole -Confirm:$false - Remove-DbaLogin -SqlInstance $TestConfig.instance2 -Login $login1 -Confirm:$false + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # Cleanup all created objects. + $null = Remove-DbaServerRole -SqlInstance $TestConfig.instance2 -ServerRole $svRole + $null = Remove-DbaLogin -SqlInstance $TestConfig.instance2 -Login $login1 - } catch { } - (Get-ChildItem $outputFile -ErrorAction SilentlyContinue) | Remove-Item -ErrorAction SilentlyContinue + # Remove test files + Remove-Item -Path $outputFile -ErrorAction SilentlyContinue + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } Context "Check if output file was created" { + BeforeAll { + $null = Export-DbaServerRole -SqlInstance $TestConfig.instance2 -FilePath $outputFile + } - $null = Export-DbaServerRole -SqlInstance $TestConfig.instance2 -FilePath $outputFile It "Exports results to one sql file" { - (Get-ChildItem $outputFile).Count | Should Be 1 + @(Get-ChildItem $outputFile).Count | Should -BeExactly 1 } + It "Exported file is bigger than 0" { - (Get-ChildItem $outputFile).Length | Should BeGreaterThan 0 + (Get-ChildItem $outputFile).Length | Should -BeGreaterThan 0 } } Context "Check using piped input created" { - $role = Get-DbaServerRole -SqlInstance $TestConfig.instance2 -ServerRole $svRole - $null = $role | Export-DbaServerRole -FilePath $outputFile + BeforeAll { + $role = Get-DbaServerRole -SqlInstance $TestConfig.instance2 -ServerRole $svRole + $null = $role | Export-DbaServerRole -FilePath $outputFile + $global:results = $role | Export-DbaServerRole -Passthru + } + It "Exports results to one sql file" { - (Get-ChildItem $outputFile).Count | Should Be 1 + @(Get-ChildItem $outputFile).Count | Should -BeExactly 1 } + It "Exported file is bigger than 0" { - (Get-ChildItem $outputFile).Length | Should BeGreaterThan 0 + (Get-ChildItem $outputFile).Length | Should -BeGreaterThan 0 } - $script:results = $role | Export-DbaServerRole -Passthru It "should include the defined BatchSeparator" { - $script:results -match "GO" + $global:results -match "GO" | Should -BeTrue } + It "should include the role" { - $script:results -match "CREATE SERVER ROLE [$svRole]" + $global:results -match "CREATE SERVER ROLE \[$svRole\]" | Should -BeTrue } + It "should include ADD MEMBER" { - $script:results -match "ALTER SERVER ROLE [dbcreator] ADD MEMBER [$svRole]" + $global:results -match "ALTER SERVER ROLE \[dbcreator\] ADD MEMBER \[$svRole\]" | Should -BeTrue } + It "should include GRANT CREATE TRACE EVENT" { - $script:results -match "GRANT CREATE TRACE EVENT NOTIFICATION TO [$svRole]" + $global:results -match "GRANT CREATE TRACE EVENT NOTIFICATION TO \[$svRole\]" | Should -BeTrue } + It "should include DENY SELECT ALL USER SECURABLES" { - $script:results -match "DENY SELECT ALL USER SECURABLES TO [$svRole]" + $global:results -match "DENY SELECT ALL USER SECURABLES TO \[$svRole\]" | Should -BeTrue } + It "should include VIEW ANY DEFINITION" { - $script:results -match "GRANT VIEW ANY DEFINITION TO [$svRole];" + $global:results -match "GRANT VIEW ANY DEFINITION TO \[$svRole\];" | Should -BeTrue } + It "should include GRANT VIEW ANY DATABASE" { - $script:results -match "GRANT VIEW ANY DATABASE TO [$svRole];" + $global:results -match "GRANT VIEW ANY DATABASE TO \[$svRole\];" | Should -BeTrue } } -} +} \ No newline at end of file diff --git a/tests/Export-DbaSpConfigure.Tests.ps1 b/tests/Export-DbaSpConfigure.Tests.ps1 index 12427593aac..aa291b320a2 100644 --- a/tests/Export-DbaSpConfigure.Tests.ps1 +++ b/tests/Export-DbaSpConfigure.Tests.ps1 @@ -1,19 +1,31 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Export-DbaSpConfigure", + $PSDefaultParameterValues = $TestConfig.Defaults +) -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Path', 'FilePath', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Path", + "FilePath", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -<# - Integration test should appear below and are custom to the command you are writing. - Read https://github.com/dataplat/dbatools/blob/development/contributing.md#tests - for more guidence. -#> \ No newline at end of file +# +# Integration test should appear below and are custom to the command you are writing. +# Read https://github.com/dataplat/dbatools/blob/development/contributing.md#tests +# for more guidence. +# \ No newline at end of file diff --git a/tests/Export-DbaSysDbUserObject.Tests.ps1 b/tests/Export-DbaSysDbUserObject.Tests.ps1 index 5b65d5285d3..b1ce1421806 100644 --- a/tests/Export-DbaSysDbUserObject.Tests.ps1 +++ b/tests/Export-DbaSysDbUserObject.Tests.ps1 @@ -1,20 +1,46 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Export-DbaSysDbUserObject", + $PSDefaultParameterValues = $TestConfig.Defaults +) -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'IncludeDependencies', 'BatchSeparator', 'Path', 'FilePath', 'NoPrefix', 'ScriptingOptionsObject', 'NoClobber', 'PassThru', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "IncludeDependencies", + "BatchSeparator", + "Path", + "FilePath", + "NoPrefix", + "ScriptingOptionsObject", + "NoClobber", + "PassThru", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # For all the backups that we want to clean up after the test, we create a directory that we can delete at the end. + # Other files can be written there as well, maybe we change the name of that variable later. But for now we focus on backups. + $backupPath = "$($TestConfig.Temp)\$CommandName-$(Get-Random)" + $null = New-Item -Path $backupPath -ItemType Directory + $random = Get-Random $tableName = "dbatoolsci_UserTable_$random" $viewName = "dbatoolsci_View_$random" @@ -31,8 +57,15 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { $server.query("CREATE FUNCTION dbo.$tableFunctionName () RETURNS TABLE AS RETURN SELECT 1 as test", "master") $server.query("CREATE FUNCTION dbo.$scalarFunctionName (@int int) RETURNS INT AS BEGIN RETURN @int END", "master") $server.query("CREATE RULE dbo.$ruleName AS @range>= 1 AND @range <10;", "master") + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } + AfterAll { + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 -SqlCredential $SqlCredential $server.query("DROP TABLE dbo.$tableName", "master") $server.query("DROP VIEW dbo.$viewName", "master") @@ -41,56 +74,72 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { $server.query("DROP FUNCTION dbo.$tableFunctionName", "master") $server.query("DROP FUNCTION dbo.$scalarFunctionName", "master") $server.query("DROP RULE dbo.$ruleName", "master") + + # Remove the backup directory. + Remove-Item -Path $backupPath -Recurse -ErrorAction SilentlyContinue + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } + Context "works as expected with passthru" { - $script = Export-DbaSysDbUserObject -SqlInstance $TestConfig.instance2 -PassThru | Out-String + BeforeAll { + $script = Export-DbaSysDbUserObject -SqlInstance $TestConfig.instance2 -PassThru | Out-String + } + It "should export text matching table name '$tableName'" { - $script -match $tableName | Should be $true + $script -match $tableName | Should -Be $true } It "should export text matching view name '$viewName'" { - $script -match $viewName | Should be $true + $script -match $viewName | Should -Be $true } It "should export text matching stored procedure name '$procName'" { - $script -match $procName | Should be $true + $script -match $procName | Should -Be $true } It "should export text matching trigger name '$triggerName'" { - $script -match $triggerName | Should be $true + $script -match $triggerName | Should -Be $true } It "should export text matching table function name '$tableFunctionName'" { - $script -match $tableFunctionName | Should be $true + $script -match $tableFunctionName | Should -Be $true } It "should export text matching scalar function name '$scalarFunctionName'" { - $script -match $scalarFunctionName | Should be $true + $script -match $scalarFunctionName | Should -Be $true } It "should export text matching rule name '$ruleName'" { - $script -match $ruleName | Should be $true + $script -match $ruleName | Should -Be $true } } Context "works as expected with filename" { - $null = Export-DbaSysDbUserObject -SqlInstance $TestConfig.instance2 -FilePath "C:\Temp\objects_$random.sql" - $file = get-content "C:\Temp\objects_$random.sql" | Out-String - Remove-Item -Path "C:\Temp\objects_$random.sql" + BeforeAll { + $filePath = "$backupPath\objects_$random.sql" + $null = Export-DbaSysDbUserObject -SqlInstance $TestConfig.instance2 -FilePath $filePath + $file = Get-Content $filePath | Out-String + } + + AfterAll { + Remove-Item -Path $filePath -ErrorAction SilentlyContinue + } + It "should export text matching table name '$tableName'" { - $file -match $tableName | Should be $true + $file -match $tableName | Should -Be $true } It "should export text matching view name '$viewName'" { - $file -match $viewName | Should be $true + $file -match $viewName | Should -Be $true } It "should export text matching stored procedure name '$procName'" { - $file -match $procName | Should be $true + $file -match $procName | Should -Be $true } It "should export text matching trigger name '$triggerName'" { - $file -match $triggerName | Should be $true + $file -match $triggerName | Should -Be $true } It "should export text matching table function name '$tableFunctionName'" { - $file -match $tableFunctionName | Should be $true + $file -match $tableFunctionName | Should -Be $true } It "should export text matching scalar function name '$scalarFunctionName'" { - $file -match $scalarFunctionName | Should be $true + $file -match $scalarFunctionName | Should -Be $true } It "should export text matching scalar function name '$ruleName'" { - $file -match $ruleName | Should be $true + $file -match $ruleName | Should -Be $true } } -} +} \ No newline at end of file diff --git a/tests/Export-DbaUser.Tests.ps1 b/tests/Export-DbaUser.Tests.ps1 index b4c6b3c81e7..8769006c281 100644 --- a/tests/Export-DbaUser.Tests.ps1 +++ b/tests/Export-DbaUser.Tests.ps1 @@ -1,163 +1,231 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Export-DbaUser", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -$PSDefaultParameterValues = $TestConfig.Defaults - -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'ExcludeDatabase', 'User', 'DestinationVersion', 'Encoding', 'Path', 'FilePath', 'InputObject', 'NoClobber', 'Append', 'EnableException', 'ScriptingOptionsObject', 'ExcludeGoBatchSeparator', 'Passthru', 'Template' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 + +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "InputObject", + "SqlCredential", + "Database", + "ExcludeDatabase", + "User", + "DestinationVersion", + "Path", + "FilePath", + "Encoding", + "NoClobber", + "Append", + "Passthru", + "Template", + "EnableException", + "ScriptingOptionsObject", + "ExcludeGoBatchSeparator" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # For all the backups that we want to clean up after the test, we create a directory that we can delete at the end. + # Other files can be written there as well, maybe we change the name of that variable later. But for now we focus on backups. + $backupPath = "$($TestConfig.Temp)\$CommandName-$(Get-Random)" + $null = New-Item -Path $backupPath -ItemType Directory + + # Explain what needs to be set up for the test: + # To test user export, we need a database with users, logins, roles, and permissions. + # For testing role dependencies, we need multiple users and roles with complex relationships. + + # Set variables. They are available in all the It blocks. + $dbname = "dbatoolsci_exportdbauser" + $login = "dbatoolsci_exportdbauser_login" + $login2 = "dbatoolsci_exportdbauser_login2" + $user = "dbatoolsci_exportdbauser_user" + $user2 = "dbatoolsci_exportdbauser_user2" + $table = "dbatoolsci_exportdbauser_table" + $role = "dbatoolsci_exportdbauser_role" + $outputPath = "$($TestConfig.Temp)\Dbatoolsci_user_CustomFolder" $outputFile = "$($TestConfig.Temp)\Dbatoolsci_user_CustomFile.sql" $outputFile2 = "$($TestConfig.Temp)\Dbatoolsci_user_CustomFile2.sql" - try { - $dbname = "dbatoolsci_exportdbauser" - $login = "dbatoolsci_exportdbauser_login" - $login2 = "dbatoolsci_exportdbauser_login2" - $user = "dbatoolsci_exportdbauser_user" - $user2 = "dbatoolsci_exportdbauser_user2" - $table = "dbatoolsci_exportdbauser_table" - $role = "dbatoolsci_exportdbauser_role" - - # For Dependencies elimination test - $login01 = "dbatoolsci_exportdbauser_login01" - $login02 = "dbatoolsci_exportdbauser_login02" - $user01 = "dbatoolsci_exportdbauser_user01" - $user02 = "dbatoolsci_exportdbauser_user02" - $role01 = "dbatoolsci_exportdbauser_role01" - $role02 = "dbatoolsci_exportdbauser_role02" - $role03 = "dbatoolsci_exportdbauser_role03" - - $server = Connect-DbaInstance -SqlInstance $TestConfig.instance1 - $null = $server.Query("CREATE DATABASE [$dbname]") - - $securePassword = $(ConvertTo-SecureString -String "GoodPass1234!" -AsPlainText -Force) - $null = New-DbaLogin -SqlInstance $TestConfig.instance1 -Login $login -Password $securePassword - $null = New-DbaLogin -SqlInstance $TestConfig.instance1 -Login $login2 -Password $securePassword - $null = New-DbaLogin -SqlInstance $TestConfig.instance1 -Login $login01 -Password $securePassword - $null = New-DbaLogin -SqlInstance $TestConfig.instance1 -Login $login02 -Password $securePassword - - $db = Get-DbaDatabase -SqlInstance $TestConfig.instance1 -Database $dbname - $null = $db.Query("CREATE USER [$user] FOR LOGIN [$login]") - $null = $db.Query("CREATE USER [$user2] FOR LOGIN [$login2]") - $null = $db.Query("CREATE USER [$user01] FOR LOGIN [$login01]") - $null = $db.Query("CREATE USER [$user02] FOR LOGIN [$login02]") - $null = $db.Query("CREATE ROLE [$role]") - $null = $db.Query("CREATE ROLE [$role01]") - $null = $db.Query("CREATE ROLE [$role02]") - $null = $db.Query("CREATE ROLE [$role03]") - - $null = $db.Query("CREATE TABLE $table (C1 INT);") - $null = $db.Query("GRANT SELECT ON OBJECT::$table TO [$user];") - $null = $db.Query("EXEC sp_addrolemember '$role', '$user';") - $null = $db.Query("EXEC sp_addrolemember '$role01', '$user01';") - $null = $db.Query("EXEC sp_addrolemember '$role02', '$user01';") - $null = $db.Query("EXEC sp_addrolemember '$role02', '$user02';") - $null = $db.Query("EXEC sp_addrolemember '$role03', '$user02';") - $null = $db.Query("GRANT SELECT ON OBJECT::$table TO [$user2];") - } catch { } # No idea why appveyor can't handle this + + # For Dependencies elimination test + $login01 = "dbatoolsci_exportdbauser_login01" + $login02 = "dbatoolsci_exportdbauser_login02" + $user01 = "dbatoolsci_exportdbauser_user01" + $user02 = "dbatoolsci_exportdbauser_user02" + $role01 = "dbatoolsci_exportdbauser_role01" + $role02 = "dbatoolsci_exportdbauser_role02" + $role03 = "dbatoolsci_exportdbauser_role03" + + # Create the objects. + $server = Connect-DbaInstance -SqlInstance $TestConfig.instance1 + $null = $server.Query("CREATE DATABASE [$dbname]") + + $securePassword = $(ConvertTo-SecureString -String "GoodPass1234!" -AsPlainText -Force) + $null = New-DbaLogin -SqlInstance $TestConfig.instance1 -Login $login -Password $securePassword + $null = New-DbaLogin -SqlInstance $TestConfig.instance1 -Login $login2 -Password $securePassword + $null = New-DbaLogin -SqlInstance $TestConfig.instance1 -Login $login01 -Password $securePassword + $null = New-DbaLogin -SqlInstance $TestConfig.instance1 -Login $login02 -Password $securePassword + + $db = Get-DbaDatabase -SqlInstance $TestConfig.instance1 -Database $dbname + $null = $db.Query("CREATE USER [$user] FOR LOGIN [$login]") + $null = $db.Query("CREATE USER [$user2] FOR LOGIN [$login2]") + $null = $db.Query("CREATE USER [$user01] FOR LOGIN [$login01]") + $null = $db.Query("CREATE USER [$user02] FOR LOGIN [$login02]") + $null = $db.Query("CREATE ROLE [$role]") + $null = $db.Query("CREATE ROLE [$role01]") + $null = $db.Query("CREATE ROLE [$role02]") + $null = $db.Query("CREATE ROLE [$role03]") + + $null = $db.Query("CREATE TABLE $table (C1 INT);") + $null = $db.Query("GRANT SELECT ON OBJECT::$table TO [$user];") + $null = $db.Query("EXEC sp_addrolemember '$role', '$user';") + $null = $db.Query("EXEC sp_addrolemember '$role01', '$user01';") + $null = $db.Query("EXEC sp_addrolemember '$role02', '$user01';") + $null = $db.Query("EXEC sp_addrolemember '$role02', '$user02';") + $null = $db.Query("EXEC sp_addrolemember '$role03', '$user02';") + $null = $db.Query("GRANT SELECT ON OBJECT::$table TO [$user2];") + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } + AfterAll { - Remove-DbaDatabase -SqlInstance $TestConfig.instance1 -Database $dbname - Remove-DbaLogin -SqlInstance $TestConfig.instance1 -Login $login, $login2, $login01, $login02 - (Get-ChildItem $outputFile -ErrorAction SilentlyContinue) | Remove-Item - (Get-ChildItem $outputFile2 -ErrorAction SilentlyContinue) | Remove-Item - Remove-Item -Path $outputPath -Recurse + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # Cleanup all created object. + $null = Remove-DbaDatabase -SqlInstance $TestConfig.instance1 -Database $dbname + $null = Remove-DbaLogin -SqlInstance $TestConfig.instance1 -Login $login, $login2, $login01, $login02 + + # Remove the backup directory. + Remove-Item -Path $backupPath -Recurse -ErrorAction SilentlyContinue + Remove-Item -Path $outputPath -Recurse -ErrorAction SilentlyContinue + Remove-Item -Path $outputFile -ErrorAction SilentlyContinue + Remove-Item -Path $outputFile2 -ErrorAction SilentlyContinue + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } Context "Check if output file was created" { - if (Get-DbaDbUser -SqlInstance $TestConfig.instance1 -Database $dbname | Where-Object Name -eq $user) { - $null = Export-DbaUser -SqlInstance $TestConfig.instance1 -Database $dbname -User $user -FilePath $outputFile - It "Exports results to one sql file" { - (Get-ChildItem $outputFile).Count | Should Be 1 - } - It "Exported file is bigger than 0" { - (Get-ChildItem $outputFile).Length | Should BeGreaterThan 0 + BeforeAll { + $userExists = Get-DbaDbUser -SqlInstance $TestConfig.instance1 -Database $dbname | Where-Object Name -eq $user + if ($userExists) { + $null = Export-DbaUser -SqlInstance $TestConfig.instance1 -Database $dbname -User $user -FilePath $outputFile } } + + It "Exports results to one sql file" -Skip:(-not $userExists) { + @(Get-ChildItem $outputFile).Count | Should -BeExactly 1 + } + + It "Exported file is bigger than 0" -Skip:(-not $userExists) { + (Get-ChildItem $outputFile).Length | Should -BeGreaterThan 0 + } } Context "Respects options specified in the ScriptingOptionsObject parameter" { - It 'Excludes database context' { + It "Excludes database context" { $scriptingOptions = New-DbaScriptingOption $scriptingOptions.IncludeDatabaseContext = $false $null = Export-DbaUser -SqlInstance $TestConfig.instance1 -Database $dbname -ScriptingOptionsObject $scriptingOptions -FilePath $outputFile2 -WarningAction SilentlyContinue $results = Get-Content -Path $outputFile2 -Raw - $results | Should Not BeLike ('*USE `[' + $dbname + '`]*') - (Get-ChildItem $outputFile2 -ErrorAction SilentlyContinue) | Remove-Item -ErrorAction SilentlyContinue + $results | Should -Not -BeLike ("*USE `[" + $dbname + "`]*") + Remove-Item -Path $outputFile2 -ErrorAction SilentlyContinue } - It 'Includes database context' { + + It "Includes database context" { $scriptingOptions = New-DbaScriptingOption $scriptingOptions.IncludeDatabaseContext = $true $null = Export-DbaUser -SqlInstance $TestConfig.instance1 -Database $dbname -ScriptingOptionsObject $scriptingOptions -FilePath $outputFile2 -WarningAction SilentlyContinue $results = Get-Content -Path $outputFile2 -Raw - $results | Should BeLike ('*USE `[' + $dbname + '`]*') - (Get-ChildItem $outputFile2 -ErrorAction SilentlyContinue) | Remove-Item -ErrorAction SilentlyContinue + $results | Should -BeLike ("*USE `[" + $dbname + "`]*") + Remove-Item -Path $outputFile2 -ErrorAction SilentlyContinue } - It 'Defaults to include database context' { + + It "Defaults to include database context" { $null = Export-DbaUser -SqlInstance $TestConfig.instance1 -Database $dbname -FilePath $outputFile2 -WarningAction SilentlyContinue $results = Get-Content -Path $outputFile2 -Raw - $results | Should BeLike ('*USE `[' + $dbname + '`]*') - (Get-ChildItem $outputFile2 -ErrorAction SilentlyContinue) | Remove-Item -ErrorAction SilentlyContinue + $results | Should -BeLike ("*USE `[" + $dbname + "`]*") + Remove-Item -Path $outputFile2 -ErrorAction SilentlyContinue } - It 'Exports as template' { + + It "Exports as template" { $results = Export-DbaUser -SqlInstance $TestConfig.instance1 -Database $dbname -User $user -Template -DestinationVersion SQLServer2016 -WarningAction SilentlyContinue -Passthru - $results | Should BeLike "*CREATE USER ``[{templateUser}``] FOR LOGIN ``[{templateLogin}``]*" - $results | Should BeLike "*GRANT SELECT ON OBJECT::``[dbo``].``[$table``] TO ``[{templateUser}``]*" - $results | Should BeLike "*ALTER ROLE ``[$role``] ADD MEMBER ``[{templateUser}``]*" + $results | Should -BeLike "*CREATE USER ``[{templateUser}``] FOR LOGIN ``[{templateLogin}``]*" + $results | Should -BeLike "*GRANT SELECT ON OBJECT::``[dbo``].``[$table``] TO ``[{templateUser}``]*" + $results | Should -BeLike "*ALTER ROLE ``[$role``] ADD MEMBER ``[{templateUser}``]*" } } Context "Check if one output file per user was created" { - $null = Export-DbaUser -SqlInstance $TestConfig.instance1 -Database $dbname -Path $outputPath + BeforeAll { + $null = Export-DbaUser -SqlInstance $TestConfig.instance1 -Database $dbname -Path $outputPath + $exportedFiles = @(Get-ChildItem $outputPath) + $userCount = @(Get-DbaDbUser -SqlInstance $TestConfig.instance1 -Database $dbname | Where-Object { $PSItem.Name -notin @("dbo", "guest", "sys", "INFORMATION_SCHEMA") }).Count + } + It "Exports files to the path" { - $userCount = (Get-DbaDbUser -SqlInstance $TestConfig.instance1 -Database $dbname | Where-Object { $_.Name -notin @("dbo", "guest", "sys", "INFORMATION_SCHEMA") } | Measure-Object).Count - (Get-ChildItem $outputPath).Count | Should Be $userCount + $exportedFiles.Count | Should -BeExactly $userCount } + It "Exported file name contains username '$user'" { - Get-ChildItem $outputPath | Where-Object Name -like ('*' + $User + '*') | Should BeTrue + $exportedFiles | Where-Object Name -like ("*" + $user + "*") | Should -Not -BeNullOrEmpty } + It "Exported file name contains username '$user2'" { - Get-ChildItem $outputPath | Where-Object Name -like ('*' + $User2 + '*') | Should BeTrue + $exportedFiles | Where-Object Name -like ("*" + $user2 + "*") | Should -Not -BeNullOrEmpty } } Context "Check if the output scripts were self-contained" { - # Clean up the output folder - Remove-Item -Path $outputPath -Recurse -ErrorAction SilentlyContinue - $null = Export-DbaUser -SqlInstance $TestConfig.instance1 -Database $dbname -Path $outputPath + BeforeAll { + # Clean up the output folder + Remove-Item -Path $outputPath -Recurse -ErrorAction SilentlyContinue + $null = Export-DbaUser -SqlInstance $TestConfig.instance1 -Database $dbname -Path $outputPath + } It "Contains the CREATE ROLE and ALTER ROLE statements for its own roles" { - Get-ChildItem $outputPath | Where-Object Name -like ('*' + $user01 + '*') | ForEach-Object { - $content = Get-Content -Path $_.FullName -Raw - $content | Should BeLike "*CREATE ROLE [[]$role01]*" - $content | Should BeLike "*CREATE ROLE [[]$role02]*" - $content | Should Not BeLike "*CREATE ROLE [[]$role03]*" - - $content | Should BeLike "*ALTER ROLE [[]$role01] ADD MEMBER [[]$user01]*" - $content | Should BeLike "*ALTER ROLE [[]$role02] ADD MEMBER [[]$user01]*" - $content | Should Not BeLike "*ALTER ROLE [[]$role03]*" + Get-ChildItem $outputPath | Where-Object Name -like ("*" + $user01 + "*") | ForEach-Object { + $content = Get-Content -Path $PSItem.FullName -Raw + $content | Should -BeLike "*CREATE ROLE [[]$role01]*" + $content | Should -BeLike "*CREATE ROLE [[]$role02]*" + $content | Should -Not -BeLike "*CREATE ROLE [[]$role03]*" + + $content | Should -BeLike "*ALTER ROLE [[]$role01] ADD MEMBER [[]$user01]*" + $content | Should -BeLike "*ALTER ROLE [[]$role02] ADD MEMBER [[]$user01]*" + $content | Should -Not -BeLike "*ALTER ROLE [[]$role03]*" } - Get-ChildItem $outputPath | Where-Object Name -like ('*' + $user02 + '*') | ForEach-Object { - $content = Get-Content -Path $_.FullName -Raw - $content | Should BeLike "*CREATE ROLE [[]$role02]*" - $content | Should BeLike "*CREATE ROLE [[]$role03]*" - $content | Should Not BeLike "*CREATE ROLE [[]$role01]*" + Get-ChildItem $outputPath | Where-Object Name -like ("*" + $user02 + "*") | ForEach-Object { + $content = Get-Content -Path $PSItem.FullName -Raw + $content | Should -BeLike "*CREATE ROLE [[]$role02]*" + $content | Should -BeLike "*CREATE ROLE [[]$role03]*" + $content | Should -Not -BeLike "*CREATE ROLE [[]$role01]*" - $content | Should BeLike "*ALTER ROLE [[]$role02] ADD MEMBER [[]$user02]*" - $content | Should BeLike "*ALTER ROLE [[]$role03] ADD MEMBER [[]$user02]*" - $content | Should Not BeLike "*ALTER ROLE [[]$role01]*" + $content | Should -BeLike "*ALTER ROLE [[]$role02] ADD MEMBER [[]$user02]*" + $content | Should -BeLike "*ALTER ROLE [[]$role03] ADD MEMBER [[]$user02]*" + $content | Should -Not -BeLike "*ALTER ROLE [[]$role01]*" } } } -} +} \ No newline at end of file diff --git a/tests/Export-DbaXECsv.Tests.ps1 b/tests/Export-DbaXECsv.Tests.ps1 index ae4e624c8aa..f9edfa62b1c 100644 --- a/tests/Export-DbaXECsv.Tests.ps1 +++ b/tests/Export-DbaXECsv.Tests.ps1 @@ -1,14 +1,28 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Export-DbaXECsv", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'InputObject', 'Path', 'FilePath', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "InputObject", + "Path", + "FilePath", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } diff --git a/tests/Export-DbaXESession.Tests.ps1 b/tests/Export-DbaXESession.Tests.ps1 index d8dc05c846b..4b94e7d74d7 100644 --- a/tests/Export-DbaXESession.Tests.ps1 +++ b/tests/Export-DbaXESession.Tests.ps1 @@ -1,55 +1,116 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Export-DbaXESession", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'InputObject', 'Session', 'Path', 'FilePath', 'Encoding', 'Passthru', 'BatchSeparator', 'NoPrefix', 'NoClobber', 'Append', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "InputObject", + "Session", + "Path", + "FilePath", + "Encoding", + "Passthru", + "BatchSeparator", + "NoPrefix", + "NoClobber", + "Append", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { - $AltExportPath = "$env:USERPROFILE\Documents" - $outputFile = "$AltExportPath\Dbatoolsci_XE_CustomFile.sql" + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true + + # For all the backups that we want to clean up after the test, we create a directory that we can delete at the end. + # Other files can be written there as well, maybe we change the name of that variable later. But for now we focus on backups. + $backupPath = "$($TestConfig.Temp)\$CommandName-$(Get-Random)" + $null = New-Item -Path $backupPath -ItemType Directory + + # Explain what needs to be set up for the test: + # To test Export-DbaXESession, we need a valid SQL instance with at least one Extended Events session. + # We will use the system_health session which is always available. + + # Set variables. They are available in all the It blocks. + $outputFile = "$backupPath\Dbatoolsci_XE_CustomFile.sql" + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove("*-Dba*:EnableException") } + AfterAll { - (Get-ChildItem $outputFile -ErrorAction SilentlyContinue) | Remove-Item -ErrorAction SilentlyContinue + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true + + # Remove the backup directory. + Remove-Item -Path $backupPath -Recurse -ErrorAction SilentlyContinue + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } Context "Check if output file was created" { - $null = Export-DbaXESession -SqlInstance $TestConfig.instance2 -FilePath $outputFile + BeforeAll { + $null = Export-DbaXESession -SqlInstance $TestConfig.instance2 -FilePath $outputFile + } + It "Exports results to one sql file" { - (Get-ChildItem $outputFile).Count | Should Be 1 + (Get-ChildItem $outputFile).Count | Should -BeExactly 1 } + It "Exported file is bigger than 0" { - (Get-ChildItem $outputFile).Length | Should BeGreaterThan 0 + (Get-ChildItem $outputFile).Length | Should -BeGreaterThan 0 } } Context "Check if session parameter is honored" { - $null = Export-DbaXESession -SqlInstance $TestConfig.instance2 -FilePath $outputFile -Session system_health + BeforeAll { + # Remove previous output file if exists + Remove-Item -Path $outputFile -ErrorAction SilentlyContinue + $null = Export-DbaXESession -SqlInstance $TestConfig.instance2 -FilePath $outputFile -Session system_health + } + It "Exports results to one sql file" { - (Get-ChildItem $outputFile).Count | Should Be 1 + (Get-ChildItem $outputFile).Count | Should -BeExactly 1 } + It "Exported file is bigger than 0" { - (Get-ChildItem $outputFile).Length | Should BeGreaterThan 0 + (Get-ChildItem $outputFile).Length | Should -BeGreaterThan 0 } } Context "Check if supports Pipeline input" { - $null = Get-DbaXESession -SqlInstance $TestConfig.instance2 -Session system_health | Export-DbaXESession -FilePath $outputFile + BeforeAll { + # Remove previous output file if exists + Remove-Item -Path $outputFile -ErrorAction SilentlyContinue + $null = Get-DbaXESession -SqlInstance $TestConfig.instance2 -Session system_health | Export-DbaXESession -FilePath $outputFile + } + It "Exports results to one sql file" { - (Get-ChildItem $outputFile).Count | Should Be 1 + (Get-ChildItem $outputFile).Count | Should -BeExactly 1 } + It "Exported file is bigger than 0" { - (Get-ChildItem $outputFile).Length | Should BeGreaterThan 0 + (Get-ChildItem $outputFile).Length | Should -BeGreaterThan 0 } } -} +} \ No newline at end of file diff --git a/tests/Export-DbatoolsConfig.Tests.ps1 b/tests/Export-DbatoolsConfig.Tests.ps1 index 3d48dfbb1d6..a357192e340 100644 --- a/tests/Export-DbatoolsConfig.Tests.ps1 +++ b/tests/Export-DbatoolsConfig.Tests.ps1 @@ -1,14 +1,31 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Export-DbatoolsConfig", + $PSDefaultParameterValues = $TestConfig.Defaults +) -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'FullName', 'Module', 'Name', 'Config', 'ModuleName', 'ModuleVersion', 'Scope', 'OutPath', 'SkipUnchanged', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "FullName", + "Module", + "Name", + "Config", + "ModuleName", + "ModuleVersion", + "Scope", + "OutPath", + "SkipUnchanged", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } diff --git a/tests/Invoke-DbatoolsFormatter.Tests.ps1 b/tests/Invoke-DbatoolsFormatter.Tests.ps1 index e7f442fdfa6..4e3530ef3e9 100644 --- a/tests/Invoke-DbatoolsFormatter.Tests.ps1 +++ b/tests/Invoke-DbatoolsFormatter.Tests.ps1 @@ -1,6 +1,6 @@ #Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } param( - $ModuleName = "dbatools", + $ModuleName = "dbatools", $CommandName = "Invoke-DbatoolsFormatter", $PSDefaultParameterValues = $TestConfig.Defaults ) @@ -15,7 +15,6 @@ Describe $CommandName -Tag UnitTests { $expectedParameters = $TestConfig.CommonParameters $expectedParameters += @( "Path", - "SkipInvisibleOnly", "EnableException" ) } @@ -87,4 +86,9 @@ function Get-DbaStub { $newcontentUnix | Should -Be $wantedContent.Replace("`r", "") } } + + AfterAll { + # TestDrive is automatically cleaned up by Pester, but adding explicit cleanup for consistency + # No additional cleanup needed as TestDrive handles temporary file cleanup + } } \ No newline at end of file diff --git a/tests/pester.groups.ps1 b/tests/pester.groups.ps1 index 685f4c22ca8..e01bd14aa42 100644 --- a/tests/pester.groups.ps1 +++ b/tests/pester.groups.ps1 @@ -43,7 +43,9 @@ $TestsRunGroups = @{ 'Get-DbaCpuRingBuffer', 'Get-DbaLatchStatistic', # uses a backup that only works on SQL Server 2022 - 'Get-DbaEstimatedCompletionTime' + 'Get-DbaEstimatedCompletionTime', + # fails so often + 'Get-DbaDbMasterKey' ) # do not run everywhere "disabled" = @()