diff --git a/.aider/aider.psm1 b/.aider/aider.psm1 index 3fb002de71..93694b9f0e 100644 --- a/.aider/aider.psm1 +++ b/.aider/aider.psm1 @@ -13,10 +13,10 @@ function Update-PesterTest { If not specified, will process commands from the dbatools module. .PARAMETER First - Specifies the maximum number of commands to process. Defaults to 1000. + Specifies the maximum number of commands to process. .PARAMETER Skip - Specifies the number of commands to skip before processing. Defaults to 0. + Specifies the number of commands to skip before processing. .PARAMETER PromptFilePath The path to the template file containing the prompt structure. @@ -57,8 +57,8 @@ function Update-PesterTest { param ( [Parameter(ValueFromPipeline)] [PSObject[]]$InputObject, - [int]$First = 1000, - [int]$Skip = 0, + [int]$First = 10000, + [int]$Skip, [string[]]$PromptFilePath = "/workspace/.aider/prompts/template.md", [string[]]$CacheFilePath = @("/workspace/.aider/prompts/conventions.md","/workspace/private/testing/Get-TestConfig.ps1"), [int]$MaxFileSize = 8kb @@ -136,12 +136,11 @@ function Update-PesterTest { continue } - <# Check if it's already been converted - if (Select-String -Path $filename -Pattern "Should -HaveParameter") { + <# Check if it's already been converted #> + if (Select-String -Path $filename -Pattern "HaveParameter") { Write-Warning "Skipping $cmdName because it's already been converted to Pester v5" continue } - #> # if file is larger than MaxFileSize, skip if ((Get-Item $filename).Length -gt $MaxFileSize) { @@ -181,10 +180,10 @@ function Repair-Error { information from a JSON file and attempts to fix the identified issues in the test files. .PARAMETER First - Specifies the maximum number of commands to process. Defaults to 1000. + Specifies the maximum number of commands to process. .PARAMETER Skip - Specifies the number of commands to skip before processing. Defaults to 0. + Specifies the number of commands to skip before processing. .PARAMETER PromptFilePath The path to the template file containing the prompt structure. @@ -212,8 +211,8 @@ function Repair-Error { #> [CmdletBinding()] param ( - [int]$First = 1000, - [int]$Skip = 0, + [int]$First = 10000, + [int]$Skip, [string[]]$PromptFilePath = "/workspace/.aider/prompts/fix-errors.md", [string[]]$CacheFilePath = "/workspace/.aider/prompts/conventions.md", [string]$ErrorFilePath = "/workspace/.aider/prompts/errors.json" @@ -254,128 +253,233 @@ function Repair-Error { } } -function Repair-ParameterTest { - <# - .SYNOPSIS - Repairs parameter tests in dbatools Pester test files. +function Repair-SmallThing { + [cmdletbinding()] + param ( + [Parameter(Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName)] + [Alias("FullName", "FilePath", "File")] + [object[]]$InputObject, + [int]$First = 10000, + [int]$Skip, + [string]$Model = "azure/gpt-4o-mini", + [string[]]$PromptFilePath, + [ValidateSet("ReorgParamTest")] + [string]$Type, + [string]$EditorModel, + [switch]$NoPretty, + [switch]$NoStream, + [switch]$YesAlways, + [switch]$CachePrompts, + [int]$MapTokens, + [string]$MapRefresh, + [switch]$NoAutoLint, + [switch]$AutoTest, + [switch]$ShowPrompts, + [string]$EditFormat, + [string]$MessageFile, + [string[]]$ReadFile, + [string]$Encoding + ) - .DESCRIPTION - Processes and repairs parameter-related tests in dbatools Pester test files. This function - specifically focuses on fixing parameter validation tests and ensures they follow the correct format. + begin { + Write-Verbose "Starting Repair-SmallThing" + $allObjects = @() - .PARAMETER First - Specifies the maximum number of commands to process. Defaults to 1000. + $prompts = @{ + ReorgParamTest = "Move the `$expected` parameter list AND the `$TestConfig.CommonParameters` part into the BeforeAll block, placing them after the `$command` assignment. Keep them within the BeforeAll block. Do not move or modify the initial `$command` assignment. - .PARAMETER Skip - Specifies the number of commands to skip before processing. Defaults to 0. + If you can't find the `$expected` parameter list, do not make any changes. - .PARAMETER Model - The AI model to use for processing. Defaults to "azure/gpt-4o-mini". + If it's already where it should be, do not make any changes." + } + Write-Verbose "Available prompt types: $($prompts.Keys -join ', ')" - .PARAMETER PromptFilePath - The path to the template file containing the prompt structure. - Defaults to "/workspace/.aider/prompts/fix-errors.md". + Write-Verbose "Checking for dbatools.library module" + if (-not (Get-Module dbatools.library -ListAvailable)) { + Write-Verbose "dbatools.library not found, installing" + Install-Module dbatools.library -Scope CurrentUser -Force -Verbose:$false + } + if (-not (Get-Module dbatools)) { + Write-Verbose "Importing dbatools module from /workspace/dbatools.psm1" + Import-Module /workspace/dbatools.psm1 -Force -Verbose:$false + } - .NOTES - Tags: Testing, Pester, Parameters - Author: dbatools team + if ($PromptFilePath) { + Write-Verbose "Loading prompt template from $PromptFilePath" + $promptTemplate = Get-Content $PromptFilePath + Write-Verbose "Prompt template loaded: $promptTemplate" + } - .EXAMPLE - PS C:\> Repair-ParameterTest - Repairs parameter tests for all eligible commands using default parameters. + $commonParameters = [System.Management.Automation.PSCmdlet]::CommonParameters - .EXAMPLE - PS C:\> Repair-ParameterTest -First 5 -Model "different-model" - Repairs parameter tests for the first 5 commands using a specified AI model. - #> - [cmdletbinding()] - param ( - [int]$First = 1000, - [int]$Skip = 0, - [string]$Model = "azure/gpt-4o-mini", - [string[]]$PromptFilePath = "/workspace/.aider/prompts/fix-errors.md" - ) - # Full prompt path - if (-not (Get-Module dbatools.library -ListAvailable)) { - Write-Warning "dbatools.library not found, installing" - Install-Module dbatools.library -Scope CurrentUser -Force + Write-Verbose "Getting base dbatools commands with First: $First, Skip: $Skip" + $baseCommands = Get-Command -Module dbatools -Type Function, Cmdlet | Select-Object -First $First -Skip $Skip + Write-Verbose "Found $($baseCommands.Count) base commands" } - Import-Module /workspace/dbatools.psm1 -Force - $promptTemplate = Get-Content $PromptFilePath + process { + if ($InputObject) { + Write-Verbose "Adding objects to collection: $($InputObject -join ', ')" + $allObjects += $InputObject + } + } + + end { + Write-Verbose "Starting end block processing" - $commands = Get-Command -Module dbatools -Type Function, Cmdlet | Select-Object -First $First -Skip $Skip - $commonParameters = [System.Management.Automation.PSCmdlet]::CommonParameters + if ($InputObject.Count -eq 0) { + Write-Verbose "No input objects provided, getting commands from dbatools module" + $allObjects += Get-Command -Module dbatools -Type Function, Cmdlet | Select-Object -First $First -Skip $Skip + } - foreach ($command in $commands) { - $cmdName = $command.Name - $filename = "/workspace/tests/$cmdName.Tests.ps1" + if (-not $PromptFilePath -and -not $Type) { + Write-Verbose "Neither PromptFilePath nor Type specified" + throw "You must specify either PromptFilePath or Type" + } - if (-not (Test-Path $filename)) { - Write-Warning "No tests found for $cmdName" - Write-Warning "$filename not found" - continue + # Process different input types + $commands = @() + foreach ($object in $allObjects) { + switch ($object.GetType().FullName) { + 'System.IO.FileInfo' { + Write-Verbose "Processing FileInfo object: $($object.FullName)" + $cmdName = [System.IO.Path]::GetFileNameWithoutExtension($object.Name) -replace '\.Tests$', '' + $commands += $baseCommands | Where-Object Name -eq $cmdName + } + 'System.Management.Automation.CommandInfo' { + Write-Verbose "Processing CommandInfo object: $($object.Name)" + $commands += $object + } + 'System.String' { + Write-Verbose "Processing string path: $object" + if (Test-Path $object) { + $cmdName = [System.IO.Path]::GetFileNameWithoutExtension($object) -replace '\.Tests$', '' + $commands += $baseCommands | Where-Object Name -eq $cmdName + } else { + Write-Warning "Path not found: $object" + } + } + 'System.Management.Automation.FunctionInfo' { + Write-Verbose "Processing FunctionInfo object: $($object.Name)" + $commands += $object + } + default { + Write-Warning "Unsupported input type: $($object.GetType().FullName)" + } + } } - $parameters = $command.Parameters.Values | Where-Object Name -notin $commonParameters + Write-Verbose "Processing $($commands.Count) unique commands" + $commands = $commands | Select-Object -Unique - $parameters = $parameters.Name -join ", " - $cmdPrompt = $promptTemplate -replace "--PARMZ--", $parameters + foreach ($command in $commands) { + $cmdName = $command.Name + Write-Verbose "Processing command: $cmdName" - $aiderParams = @{ - Message = $cmdPrompt - File = $filename - YesAlways = $true - Stream = $false - Model = $Model - } + $filename = "/workspace/tests/$cmdName.Tests.ps1" + Write-Verbose "Using test path: $filename" - Invoke-Aider @aiderParams + if (-not (Test-Path $filename)) { + Write-Warning "No tests found for $cmdName" + Write-Warning "$filename not found" + continue + } + + # if file is larger than MaxFileSize, skip + if ((Get-Item $filename).Length -gt 8kb) { + Write-Warning "Skipping $cmdName because it's too large" + continue + } + + if ($Type) { + Write-Verbose "Using predefined prompt for type: $Type" + $cmdPrompt = $prompts[$Type] + } else { + Write-Verbose "Getting parameters for $cmdName" + $parameters = $command.Parameters.Values | Where-Object Name -notin $commonParameters + $parameters = $parameters.Name -join ", " + Write-Verbose "Command parameters: $parameters" + + Write-Verbose "Using template prompt with parameters substitution" + $cmdPrompt = $promptTemplate -replace "--PARMZ--", $parameters + } + Write-Verbose "Final prompt: $cmdPrompt" + + $aiderParams = @{ + Message = $cmdPrompt + File = $filename + } + + $excludedParams = @( + $commonParameters, + 'InputObject', + 'First', + 'Skip', + 'PromptFilePath', + 'Type' + ) + + $PSBoundParameters.GetEnumerator() | + Where-Object Key -notin $excludedParams | + ForEach-Object { + $aiderParams[$PSItem.Key] = $PSItem.Value + } + + if (-not $PSBoundParameters.Model) { + $aiderParams.Model = $Model + } + + Write-Verbose "Invoking aider for $cmdName" + try { + Invoke-Aider @aiderParams + Write-Verbose "Aider completed successfully for $cmdName" + } catch { + Write-Error "Error executing aider for $cmdName`: $_" + Write-Verbose "Aider failed for $cmdName with error: $_" + } + } + Write-Verbose "Repair-SmallThing completed" } } function Invoke-Aider { <# .SYNOPSIS - PowerShell wrapper for the aider CLI tool. + Invokes the aider AI pair programming tool. .DESCRIPTION - Provides a PowerShell interface to the aider command-line tool, allowing for easier integration - with PowerShell scripts and workflows. Supports core functionality including model selection, - caching, and various output options. + The Invoke-Aider function provides a PowerShell interface to the aider AI pair programming tool. + It supports all aider CLI options and can accept files via pipeline from Get-ChildItem. .PARAMETER Message - The message or prompt to send to aider. + The message to send to the AI. This is the primary way to communicate your intent. .PARAMETER File - The file(s) to process with aider. + The files to edit. Can be piped in from Get-ChildItem. .PARAMETER Model - Specify the AI model to use (e.g., gpt-4o, claude-3-5-sonnet). + The AI model to use (e.g., gpt-4, claude-3-opus-20240229). .PARAMETER EditorModel - Specify the model to use for editing code. + The model to use for editor tasks. .PARAMETER NoPretty Disable pretty, colorized output. - .PARAMETER Stream - Enable streaming responses. Cannot be used with -NoStream. - .PARAMETER NoStream - Disable streaming responses. Cannot be used with -Stream. + Disable streaming responses. .PARAMETER YesAlways - Automatically confirm all prompts. + Always say yes to every confirmation. .PARAMETER CachePrompts - Enable caching of prompts to reduce token costs. + Enable caching of prompts. .PARAMETER MapTokens - Number of tokens to use for repo map. Use 0 to disable. + Suggested number of tokens to use for repo map. .PARAMETER MapRefresh - Control how often the repo map is refreshed (auto/always/files/manual). + Control how often the repo map is refreshed. .PARAMETER NoAutoLint Disable automatic linting after changes. @@ -384,157 +488,157 @@ function Invoke-Aider { Enable automatic testing after changes. .PARAMETER ShowPrompts - Show system prompts. - - .PARAMETER VerboseOutput - Enable verbose output. + Print the system prompts and exit. .PARAMETER EditFormat - Specify the edit format (e.g., 'whole' for whole file). + Specify what edit format the LLM should use. .PARAMETER MessageFile - File containing the message to send to aider. + Specify a file containing the message to send. .PARAMETER ReadFile Specify read-only files. .PARAMETER Encoding - Specify the encoding for input and output. Defaults to 'utf-8'. + Specify the encoding for input and output. - .NOTES - Tags: AI, Automation - Author: dbatools team + .EXAMPLE + Invoke-Aider -Message "Fix the bug" -File script.ps1 + + Asks aider to fix a bug in script.ps1. .EXAMPLE - PS C:\> Invoke-Aider -Message "Fix the bug" -File "script.ps1" - Runs aider with the specified message and file. + Get-ChildItem *.ps1 | Invoke-Aider -Message "Add error handling" + + Adds error handling to all PowerShell files in the current directory. .EXAMPLE - PS C:\> $params = @{ - >> Message = "Update tests" - >> File = "tests.ps1" - >> Model = "gpt-4o" - >> CachePrompts = $true - >> } - PS C:\> Invoke-Aider @params - Runs aider using GPT-4 model with prompt caching enabled. + Invoke-Aider -Message "Update API" -Model gpt-4 -NoStream + + Uses GPT-4 to update API code without streaming output. #> [CmdletBinding()] - param ( + param( [Parameter(Mandatory)] [string]$Message, - [Parameter(Mandatory)] + [Parameter(Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName)] + [Alias('FullName')] [string[]]$File, [string]$Model, [string]$EditorModel, [switch]$NoPretty, - [Parameter(ParameterSetName = 'Stream')] - [switch]$Stream, - [Parameter(ParameterSetName = 'NoStream')] [switch]$NoStream, [switch]$YesAlways, [switch]$CachePrompts, - [int]$MapTokens = 0, + [int]$MapTokens, [ValidateSet('auto', 'always', 'files', 'manual')] - [string]$MapRefresh = 'manual', + [string]$MapRefresh, [switch]$NoAutoLint, [switch]$AutoTest, [switch]$ShowPrompts, - [switch]$VerboseOutput, - [string]$EditFormat = 'whole', + [string]$EditFormat, [string]$MessageFile, [string[]]$ReadFile, [ValidateSet('utf-8', 'ascii', 'unicode', 'utf-16', 'utf-32', 'utf-7')] - [string]$Encoding = 'utf-8' + [string]$Encoding ) - $params = @( - "--message", $Message - ) + begin { + $allFiles = @() - foreach ($f in $File) { - $params += "--file" - $params += $f + if (-not (Get-Command -Name aider -ErrorAction SilentlyContinue)) { + throw "Aider executable not found. Please ensure it is installed and in your PATH." + } } - if ($Model) { - $params += "--model" - $params += $Model + process { + if ($File) { + $allFiles += $File + } } - if ($EditorModel) { - $params += "--editor-model" - $params += $EditorModel - } + end { + $arguments = @() - if ($NoPretty) { - $params += "--no-pretty" - } + # Add files if any were specified or piped in + if ($allFiles) { + $arguments += $allFiles + } - if ($Stream) { - # Stream is enabled, so don't add --no-stream - } elseif ($NoStream) { - $params += "--no-stream" - } + # Add mandatory message parameter + if ($Message) { + $arguments += "--message", $Message + } - if ($YesAlways) { - $params += "--yes-always" - } + # Add optional parameters only if they are present + if ($Model) { + $arguments += "--model", $Model + } - if ($CachePrompts) { - $params += "--cache-prompts" - # Always set keepalive pings to 5 when caching is enabled - $params += "--cache-keepalive-pings" - $params += "5" - } + if ($EditorModel) { + $arguments += "--editor-model", $EditorModel + } - if ($MapTokens -ge 0) { - $params += "--map-tokens" - $params += $MapTokens.ToString() - } + if ($NoPretty) { + $arguments += "--no-pretty" + } - if ($MapRefresh) { - $params += "--map-refresh" - $params += $MapRefresh - } + if ($NoStream) { + $arguments += "--no-stream" + } - if ($NoAutoLint) { - $params += "--no-auto-lint" - } + if ($YesAlways) { + $arguments += "--yes-always" + } - if ($AutoTest) { - $params += "--auto-test" - } + if ($CachePrompts) { + $arguments += "--cache-prompts" + } - if ($ShowPrompts) { - $params += "--show-prompts" - } + if ($PSBoundParameters.ContainsKey('MapTokens')) { + $arguments += "--map-tokens", $MapTokens + } - if ($VerboseOutput) { - $params += "--verbose" - } + if ($MapRefresh) { + $arguments += "--map-refresh", $MapRefresh + } - if ($EditFormat) { - $params += "--edit-format" - $params += $EditFormat - } + if ($NoAutoLint) { + $arguments += "--no-auto-lint" + } - if ($MessageFile) { - $params += "--message-file" - $params += $MessageFile - } + if ($AutoTest) { + $arguments += "--auto-test" + } - foreach ($rf in $ReadFile) { - $params += "--read" - $params += $rf - } + if ($ShowPrompts) { + $arguments += "--show-prompts" + } - if ($Encoding) { - $params += "--encoding" - $params += $Encoding - } + if ($EditFormat) { + $arguments += "--edit-format", $EditFormat + } + + if ($MessageFile) { + $arguments += "--message-file", $MessageFile + } - aider @params + if ($ReadFile) { + foreach ($file in $ReadFile) { + $arguments += "--read", $file + } + } + + if ($Encoding) { + $arguments += "--encoding", $Encoding + } + + if ($VerbosePreference -eq 'Continue') { + Write-Verbose "Executing: aider $($arguments -join ' ')" + } + + aider @arguments + } } function Repair-Error { @@ -547,10 +651,10 @@ function Repair-Error { information from a JSON file and attempts to fix the identified issues in the test files. .PARAMETER First - Specifies the maximum number of commands to process. Defaults to 1000. + Specifies the maximum number of commands to process. .PARAMETER Skip - Specifies the number of commands to skip before processing. Defaults to 0. + Specifies the number of commands to skip before processing. .PARAMETER PromptFilePath The path to the template file containing the prompt structure. @@ -578,8 +682,8 @@ function Repair-Error { #> [CmdletBinding()] param ( - [int]$First = 1000, - [int]$Skip = 0, + [int]$First = 10000, + [int]$Skip, [string[]]$PromptFilePath = "/workspace/.aider/prompts/fix-errors.md", [string[]]$CacheFilePath = "/workspace/.aider/prompts/conventions.md", [string]$ErrorFilePath = "/workspace/.aider/prompts/errors.json" diff --git a/.aider/prompts/conventions.md b/.aider/prompts/conventions.md index d779b7d7ad..2008800ffa 100644 --- a/.aider/prompts/conventions.md +++ b/.aider/prompts/conventions.md @@ -3,10 +3,12 @@ ## Core Requirements ```powershell #Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} -param($ModuleName = "dbatools") -$global:TestConfig = Get-TestConfig +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) ``` -These three lines must start every test file. +These lines must start every test file. ## Test Structure @@ -45,20 +47,6 @@ Describe "Get-DbaDatabase" -Tag "IntegrationTests" { } ``` -## TestCases -Use the `-ForEach` parameter in `It` blocks for multiple test cases: - -```powershell -It "Should calculate correctly" -ForEach @( - @{ Input = 1; Expected = 2 } - @{ Input = 2; Expected = 4 } - @{ Input = 3; Expected = 6 } -) { - $result = Get-Double -Number $Input - $result | Should -Be $Expected -} -``` - ## Style Guidelines - Use double quotes for strings (we're a SQL Server module) - Array declarations should be on multiple lines: @@ -72,21 +60,65 @@ $array = @( - Skip conditions must evaluate to `$true` or `$false`, not strings - Use `$global:` instead of `$script:` for test configuration variables when required for Pester v5 scoping - Avoid script blocks in Where-Object when possible: - ```powershell # Good - direct property comparison $master = $databases | Where-Object Name -eq "master" $systemDbs = $databases | Where-Object Name -in "master", "model", "msdb", "tempdb" # Required - script block for Parameters.Keys -$actualParameters = $command.Parameters.Keys | Where-Object { $PSItem -notin "WhatIf", "Confirm" } +$newParameters = $command.Parameters.Values.Name | Where-Object { $PSItem -notin "WhatIf", "Confirm" } ``` -## DO NOT -- DO NOT use `$MyInvocation.MyCommand.Name` to get command names -- DO NOT use the old `knownParameters` validation approach -- DO NOT include loose code outside of proper test blocks -- DO NOT remove comments like "#TestConfig.instance3" or "#$TestConfig.instance2 for appveyor" +### Parameter & Variable Naming Rules +- Use direct parameters for 1-2 parameters +- Use `$splat` for 3+ parameters (never plain `$splat`) + +```powershell +# Direct parameters +$ag = Get-DbaLogin -SqlInstance $instance -Login $loginName + +# Splat with purpose suffix +$splatPrimary = @{ + Primary = $TestConfig.instance3 + Name = $primaryAgName + ClusterType = "None" + FailoverMode = "Manual" + Certificate = "dbatoolsci_AGCert" + Confirm = $false +} +$primaryAg = New-DbaAvailabilityGroup @splatPrimary +``` + +### Unique names across scopes + +- Use unique, descriptive variable names across scopes to avoid collisions +- Play particlar attention to variable names in the BeforeAll + +```powershell +Describe "Add-DbaAgReplica" -Tag "IntegrationTests" { + BeforeAll { + $primaryAgName = "dbatoolsci_agroup" + $splatPrimary = @{ + Primary = $TestConfig.instance3 + Name = $primaryAgName + ... + } + $ag = New-DbaAvailabilityGroup @splatPrimary + } + + Context "When adding AG replicas" { + BeforeAll { + $replicaAgName = "dbatoolsci_add_replicagroup" + $splatRepAg = @{ + Primary = $TestConfig.instance3 + Name = $replicaAgName + ... + } + $replicaAg = New-DbaAvailabilityGroup @splatRepAg + } + } +} +``` ## Examples @@ -97,22 +129,23 @@ Describe "Get-DbaDatabase" -Tag "UnitTests" { Context "Parameter validation" { BeforeAll { $command = Get-Command Get-DbaDatabase - $expectedParameters = $TestConfig.CommonParameters - - $expectedParameters += @( + $expected = $TestConfig.CommonParameters + $expected += @( "SqlInstance", "SqlCredential", - "Database" + "Database", + "Confirm", + "WhatIf" ) } - It "Should have exactly the expected parameters" { - $actualParameters = $command.Parameters.Keys | Where-Object { $PSItem -notin "WhatIf", "Confirm" } - Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $actualParameters | Should -BeNullOrEmpty + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem } - It "Has parameter: <_>" -ForEach $expectedParameters { - $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 } } } @@ -139,35 +172,11 @@ Describe "Get-DbaDatabase" -Tag "IntegrationTests" { } ``` -### Parameter & Variable Naming Rules -1. Use direct parameters for 1-3 parameters -2. Use `$splat` for 4+ parameters (never plain `$splat`) -3. Use unique, descriptive variable names across scopes - -```powershell -# Direct parameters -$ag = New-DbaLogin -SqlInstance $instance -Login $loginName -Password $password +## Additional instructions -# Splat with purpose suffix -$splatPrimary = @{ - Primary = $TestConfig.instance3 - Name = $primaryAgName # Descriptive variable name - ClusterType = "None" - FailoverMode = "Manual" - Certificate = "dbatoolsci_AGCert" - Confirm = $false -} -$primaryAg = New-DbaAvailabilityGroup @splatPrimary - -# Unique names across scopes -Describe "New-DbaAvailabilityGroup" { - BeforeAll { - $primaryAgName = "primaryAG" - } - Context "Adding replica" { - BeforeAll { - $replicaAgName = "replicaAG" - } - } -} -``` \ No newline at end of file +- DO NOT use `$MyInvocation.MyCommand.Name` to get command names +- DO NOT use the old `knownParameters` validation approach +- DO NOT include loose code outside of proper test blocks +- DO NOT remove comments like "#TestConfig.instance3" or "#$TestConfig.instance2 for appveyor" +- DO NOT use $_ DO use $PSItem instead +- Parameter validation is ALWAYS tagged as a Unit Test \ No newline at end of file diff --git a/.aider/prompts/template.md b/.aider/prompts/template.md index 3c0e4623fb..e631c6f98e 100644 --- a/.aider/prompts/template.md +++ b/.aider/prompts/template.md @@ -2,10 +2,10 @@ You are an AI assistant created by Anthropic to help migrate Pester tests for the **dbatools PowerShell module** from version 4 to version 5. Analyze and update the file `/workspace/tests/--CMDNAME--.Tests.ps1` according to the instructions in conventions.md. -Required parameters for this command: ---PARMZ-- - Command name: --CMDNAME-- +Parameters for this command: +--PARMZ-- + Before responding, verify that your answer adheres to the specified coding and migration guidelines. \ No newline at end of file diff --git a/private/testing/Get-TestConfig.ps1 b/private/testing/Get-TestConfig.ps1 index 02787491a2..9c1068379f 100644 --- a/private/testing/Get-TestConfig.ps1 +++ b/private/testing/Get-TestConfig.ps1 @@ -8,15 +8,18 @@ function Get-TestConfig { Write-Host "Tests will use local constants file: tests\constants.local.ps1." -ForegroundColor Cyan . $LocalConfigPath # Note: Local constants are sourced but not explicitly added to $config - } elseif ($env:CODESPACES -and ($env:TERM_PROGRAM -eq 'vscode' -and $env:REMOTE_CONTAINERS)) { + } elseif ($env:CODESPACES -or ($env:TERM_PROGRAM -eq 'vscode' -and $env:REMOTE_CONTAINERS)) { + $null = Set-DbatoolsInsecureConnection $config['Instance1'] = "dbatools1" $config['Instance2'] = "dbatools2" $config['Instance3'] = "dbatools3" $config['Instances'] = @($config['Instance1'], $config['Instance2']) $config['SqlCred'] = [PSCredential]::new('sa', (ConvertTo-SecureString $env:SA_PASSWORD -AsPlainText -Force)) - $config['PSDefaultParameterValues'] = @{ + $config['Defaults'] = [System.Management.Automation.DefaultParameterDictionary]@{ "*:SqlCredential" = $config['SqlCred'] + "*:SourceSqlCredential" = $config['SqlCred'] + "*:DestinationSqlCredential" = $config['SqlCred'] } } elseif ($env:GITHUB_WORKSPACE) { $config['DbaToolsCi_Computer'] = "localhost" @@ -53,7 +56,7 @@ function Get-TestConfig { } if ($env:appveyor) { - $config['PSDefaultParameterValues'] = @{ + $config['Defaults'] = [System.Management.Automation.DefaultParameterDictionary]@{ '*:WarningAction' = 'SilentlyContinue' } } diff --git a/private/testing/Invoke-ManualPester.ps1 b/private/testing/Invoke-ManualPester.ps1 index 6db58748aa..e8bf1d3513 100644 --- a/private/testing/Invoke-ManualPester.ps1 +++ b/private/testing/Invoke-ManualPester.ps1 @@ -1,79 +1,89 @@ function Invoke-ManualPester { <# - .SYNOPSIS - Runs dbatools tests. +.SYNOPSIS + Runs dbatools tests with support for both Pester v4 and v5. - .DESCRIPTION - This is an helper to automate running tests locally +.DESCRIPTION + This is a helper function to automate running tests locally. It supports both Pester v4 and v5 tests, + automatically detecting which version to use based on the test file requirements. For Pester v5 tests, + it uses the new configuration system while maintaining backward compatibility with v4 tests. - .PARAMETER Path - The Path to the test files to run. It accepts multiple test file paths passed in (e.g. .\Find-DbaOrphanedFile.Tests.ps1) as well - as simple strings (e.g. "orphaned" will run all files matching .\*orphaned*.Tests.ps1) +.PARAMETER Path + The Path to the test files to run. It accepts multiple test file paths passed in (e.g. .\Find-DbaOrphanedFile.Tests.ps1) as well + as simple strings (e.g. "orphaned" will run all files matching .\*orphaned*.Tests.ps1) - .PARAMETER Show - Gets passed down to Pester's -Show parameter (useful if you want to reduce verbosity) +.PARAMETER Show + Gets passed down to Pester's -Show parameter (useful if you want to reduce verbosity) + Valid values are: None, Default, Passed, Failed, Pending, Skipped, Inconclusive, Describe, Context, Summary, Header, All, Fails - .PARAMETER PassThru - Gets passed down to Pester's -PassThru parameter (useful if you want to return an object to analyze) +.PARAMETER PassThru + Gets passed down to Pester's -PassThru parameter (useful if you want to return an object to analyze) - .PARAMETER TestIntegration - dbatools's suite has unittests and integrationtests. This switch enables IntegrationTests, which need live instances - see Get-TestConfig for customizations +.PARAMETER TestIntegration + dbatools's suite has unittests and integrationtests. This switch enables IntegrationTests, which need live instances + see Get-TestConfig for customizations - .PARAMETER Coverage - Enables measuring code coverage on the tested function +.PARAMETER Coverage + Enables measuring code coverage on the tested function. For Pester v5 tests, this will generate coverage in JaCoCo format. - .PARAMETER DependencyCoverage - Enables measuring code coverage also of "lower level" (i.e. called) functions +.PARAMETER DependencyCoverage + Enables measuring code coverage also of "lower level" (i.e. called) functions - .PARAMETER ScriptAnalyzer - Enables checking the called function's code with Invoke-ScriptAnalyzer, with dbatools's profile +.PARAMETER ScriptAnalyzer + Enables checking the called function's code with Invoke-ScriptAnalyzer, with dbatools's profile - .EXAMPLE - Invoke-ManualPester -Path Find-DbaOrphanedFile.Tests.ps1 -TestIntegration -Coverage -DependencyCoverage -ScriptAnalyzer +.EXAMPLE + Invoke-ManualPester -Path Find-DbaOrphanedFile.Tests.ps1 -TestIntegration -Coverage -DependencyCoverage -ScriptAnalyzer - The most complete number of checks: - - Runs both unittests and integrationtests - - Gathers and shows code coverage measurement for Find-DbaOrphanedFile and all its dependencies - - Checks Find-DbaOrphanedFile with Invoke-ScriptAnalyzer + The most complete number of checks: + - Runs both unittests and integrationtests + - Gathers and shows code coverage measurement for Find-DbaOrphanedFile and all its dependencies + - Checks Find-DbaOrphanedFile with Invoke-ScriptAnalyzer + - Automatically detects and uses the appropriate Pester version - .EXAMPLE - Invoke-ManualPester -Path Find-DbaOrphanedFile.Tests.ps1 +.EXAMPLE + Invoke-ManualPester -Path Find-DbaOrphanedFile.Tests.ps1 - Runs unittests stored in Find-DbaOrphanedFile.Tests.ps1 + Runs tests stored in Find-DbaOrphanedFile.Tests.ps1, automatically detecting whether to use Pester v4 or v5 - .EXAMPLE - Invoke-ManualPester -Path Find-DbaOrphanedFile.Tests.ps1 -PassThru +.EXAMPLE + Invoke-ManualPester -Path Find-DbaOrphanedFile.Tests.ps1 -PassThru - Runs unittests stored in Find-DbaOrphanedFile.Tests.ps1 and returns an object that can be analyzed + Runs tests stored in Find-DbaOrphanedFile.Tests.ps1 and returns an object that can be analyzed - .EXAMPLE - Invoke-ManualPester -Path orphan +.EXAMPLE + Invoke-ManualPester -Path orphan - Runs unittests for all tests matching in `*orphan*.Tests.ps1 + Runs tests for all tests matching in `*orphan*.Tests.ps1 - .EXAMPLE - Invoke-ManualPester -Path Find-DbaOrphanedFile.Tests.ps1 -Show Default +.EXAMPLE + Invoke-ManualPester -Path Find-DbaOrphanedFile.Tests.ps1 -Show Default - Runs unittests stored in Find-DbaOrphanedFile.Tests.ps1, with reduced verbosity + Runs tests stored in Find-DbaOrphanedFile.Tests.ps1, with reduced verbosity - .EXAMPLE - Invoke-ManualPester -Path Find-DbaOrphanedFile.Tests.ps1 -TestIntegration +.EXAMPLE + Invoke-ManualPester -Path Find-DbaOrphanedFile.Tests.ps1 -TestIntegration - Runs both unittests and integrationtests stored in Find-DbaOrphanedFile.Tests.ps1 + Runs both unittests and integrationtests stored in Find-DbaOrphanedFile.Tests.ps1 - .EXAMPLE - Invoke-ManualPester -Path Find-DbaOrphanedFile.Tests.ps1 -TestIntegration -Coverage +.EXAMPLE + Invoke-ManualPester -Path Find-DbaOrphanedFile.Tests.ps1 -TestIntegration -Coverage - Gathers and shows code coverage measurement for Find-DbaOrphanedFile + Gathers and shows code coverage measurement for Find-DbaOrphanedFile. + For Pester v5 tests, this will generate coverage in JaCoCo format. - .EXAMPLE - Invoke-ManualPester -Path Find-DbaOrphanedFile.Tests.ps1 -TestIntegration -Coverage -DependencyCoverage +.EXAMPLE + Invoke-ManualPester -Path Find-DbaOrphanedFile.Tests.ps1 -TestIntegration -Coverage -DependencyCoverage - Gathers and shows code coverage measurement for Find-DbaOrphanedFile and all its dependencies + Gathers and shows code coverage measurement for Find-DbaOrphanedFile and all its dependencies. + For Pester v5 tests, this will generate coverage in JaCoCo format. -#> +.NOTES + For Pester v5 tests, include the following requirement in your test file: + #Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0.0" } + Tests without this requirement will be run using Pester v4.4.2. +#> [CmdletBinding()] param ( [Parameter(Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName)] @@ -88,17 +98,8 @@ function Invoke-ManualPester { [switch]$ScriptAnalyzer ) - <# - Remove-Module -Name Pester - Import-Module -name Pester -MaximumVersion 4.* - #> - $invokeFormatterVersion = (Get-Command Invoke-Formatter -ErrorAction SilentlyContinue).Version $HasScriptAnalyzer = $null -ne $invokeFormatterVersion - $MinimumPesterVersion = [Version] '3.4.5.0' # Because this is when -Show was introduced - $MaximumPesterVersion = [Version] '5.0.0.0' # Because our tests (and runners) are only compatible with 4.* - $PesterVersion = (Get-Command Invoke-Pester -ErrorAction SilentlyContinue).Version - $HasPester = $null -ne $PesterVersion $ScriptAnalyzerCorrectVersion = '1.18.2' if (!($HasScriptAnalyzer)) { @@ -116,40 +117,27 @@ function Invoke-ManualPester { } } } - if (!($HasPester)) { - Write-Warning "Please install Pester" - Write-Warning " Install-Module -Name Pester -Force -SkipPublisherCheck" - Write-Warning " or go to https://github.com/pester/Pester" - } - if ($PesterVersion -lt $MinimumPesterVersion) { - Write-Warning "Please update Pester to at least 3.4.5" - Write-Warning " Install-Module -Name Pester -MaximumVersion '4.10' -Force -SkipPublisherCheck" - Write-Warning " or go to https://github.com/pester/Pester" - } - if ($PesterVersion -gt $MaximumPesterVersion) { - Write-Warning "Please get Pester to the 4.* release" - Write-Warning " Install-Module -Name Pester -MaximumVersion '4.10' -Force -SkipPublisherCheck" - Write-Warning " or go to https://github.com/pester/Pester" - } - if (($HasPester -and $HasScriptAnalyzer -and ($PesterVersion -ge $MinimumPesterVersion) -and ($PesterVersion -lt $MaximumPesterVersion) -and ($invokeFormatterVersion -eq $ScriptAnalyzerCorrectVersion)) -eq $false) { - Write-Warning "Exiting..." - return + if ((Test-Path /workspace)) { + $ModuleBase = "/workspace" + } else { + $ModuleBase = Split-Path -Path $PSScriptRoot -Parent } - $ModuleBase = Split-Path -Path $PSScriptRoot -Parent - if (-not(Test-Path "$ModuleBase\.git" -Type Container)) { New-Item -Type Container -Path "$ModuleBase\.git" -Force } - #removes previously imported dbatools, if any - # No need the force will do it # Remove-Module dbatools -ErrorAction Ignore - #imports the module making sure DLL is loaded ok - Import-Module "$ModuleBase\dbatools.psd1" -DisableNameChecking -Force - #imports the psm1 to be able to use internal functions in tests - Import-Module "$ModuleBase\dbatools.psm1" -DisableNameChecking -Force + # Import-Module "$ModuleBase\dbatools.psd1" -DisableNameChecking -Force + $splatImport = @{ + Name = "$ModuleBase\dbatools.psm1" + DisableNameChecking = $true + Force = $true + WarningAction = 'Ignore' + ErrorAction = 'Ignore' + } + Import-Module @splatImport $ScriptAnalyzerRulesExclude = @('PSUseOutputTypeCorrectly', 'PSAvoidUsingPlainTextForPassword', 'PSUseBOMForUnicodeEncodedFile') @@ -161,42 +149,17 @@ function Invoke-ManualPester { $testInt = $true } + # Keep the Get-CoverageIndications function as is function Get-CoverageIndications($Path, $ModuleBase) { - # takes a test file path and figures out what to analyze for coverage (i.e. dependencies) - $CBHRex = [regex]'(?smi)<#(.*)#>' - $everything = (Get-Module dbatools).ExportedCommands.Values - $everyfunction = $everything.Name - $funcs = @() - $leaf = Split-Path $path -Leaf - # assuming Get-DbaFoo.Tests.ps1 wants coverage for "Get-DbaFoo" - # but allowing also Get-DbaFoo.one.Tests.ps1 and Get-DbaFoo.two.Tests.ps1 - $func_name += ($leaf -replace '^([^.]+)(.+)?.Tests.ps1', '$1') - if ($func_name -in $everyfunction) { - $funcs += $func_name - $f = $everything | Where-Object Name -eq $func_name - $source = $f.Definition - $CBH = $CBHRex.match($source).Value - $cmdonly = $source.Replace($CBH, '') - foreach ($e in $everyfunction) { - # hacky, I know, but every occurrence of any function plus a space kinda denotes usage !? - $searchme = "$e " - if ($cmdonly.contains($searchme)) { - $funcs += $e - } - } - } - $testpaths = @() - $allfiles = Get-ChildItem -File -Path "$ModuleBase\private\functions", "$ModuleBase\public" -Filter '*.ps1' - foreach ($f in $funcs) { - # exclude always used functions ?! - if ($f -in ('Connect-DbaInstance', 'Select-DefaultView', 'Stop-Function', 'Write-Message')) { continue } - # can I find a correspondence to a physical file (again, on the convenience of having Get-DbaFoo.ps1 actually defining Get-DbaFoo)? - $res = $allfiles | Where-Object { $_.Name.Replace('.ps1', '') -eq $f } - if ($res.count -gt 0) { - $testpaths += $res.FullName - } + # [Previous implementation remains the same] + } + + function Get-PesterTestVersion($testFilePath) { + $testFileContent = Get-Content -Path $testFilePath -Raw + if ($testFileContent -match '#Requires\s+-Module\s+@\{\s+ModuleName="Pester";\s+ModuleVersion="5\.') { + return '5' } - return @() + ($testpaths | Select-Object -Unique) + return '4' } $files = @() @@ -213,36 +176,83 @@ function Invoke-ManualPester { if ($files.Length -eq 0) { Write-Warning "No tests to be run" + return } - $AllTestsWithinScenario = $files + foreach ($f in $files) { + $pesterVersion = Get-PesterTestVersion -testFilePath $f.FullName + + # Remove any previously loaded pester module + Remove-Module -Name pester -ErrorAction SilentlyContinue + + if ($pesterVersion -eq '5') { + Import-Module Pester -RequiredVersion 5.6.1 + $pester5Config = New-PesterConfiguration + $pester5Config.Run.Path = $f.FullName + + # Convert SwitchParameter to bool for PassThru + $pester5Config.Run.PassThru = [bool]$PassThru + + # Convert Show parameter to v5 verbosity + $verbosityMap = @{ + 'None' = 'None' + 'Default' = 'Normal' + 'All' = 'Detailed' + 'Fails' = 'Detailed' + 'Describe' = 'Detailed' + 'Context' = 'Detailed' + 'Summary' = 'Normal' + 'Header' = 'Normal' + 'Passed' = 'Detailed' + 'Failed' = 'Detailed' + 'Pending' = 'Detailed' + 'Skipped' = 'Detailed' + 'Inconclusive' = 'Detailed' + } - foreach ($f in $AllTestsWithinScenario) { - $PesterSplat = @{ - 'Script' = $f.FullName - 'Show' = $show - 'PassThru' = $passThru - } - #opt-in - $HeadFunctionPath = $f.FullName + $pester5Config.Output.Verbosity = $verbosityMap[$Show] - if ($Coverage -or $ScriptAnalyzer) { - $CoverFiles = Get-CoverageIndications -Path $f -ModuleBase $ModuleBase - $HeadFunctionPath = $CoverFiles | Select-Object -First 1 - } - if ($Coverage) { - if ($DependencyCoverage) { - $CoverFilesPester = $CoverFiles - } else { - $CoverFilesPester = $HeadFunctionPath + if (!($testInt)) { + $pester5Config.Filter.ExcludeTag = @('IntegrationTests') } - $PesterSplat['CodeCoverage'] = $CoverFilesPester - } - if (!($testInt)) { - $PesterSplat['ExcludeTag'] = "IntegrationTests" + + if ($Coverage) { + $CoverFiles = Get-CoverageIndications -Path $f -ModuleBase $ModuleBase + if (!$DependencyCoverage) { + $CoverFiles = $CoverFiles | Select-Object -First 1 + } + $pester5Config.CodeCoverage.Enabled = $true + $pester5Config.CodeCoverage.Path = $CoverFiles + $pester5Config.CodeCoverage.OutputFormat = 'JaCoCo' + $pester5Config.CodeCoverage.OutputPath = "$ModuleBase\Pester5Coverage.xml" + } + + Invoke-Pester -Configuration $pester5Config + } else { + Import-Module pester -RequiredVersion 4.4.2 + $PesterSplat = @{ + 'Script' = $f.FullName + 'Show' = $show + 'PassThru' = $PassThru + } + + if ($Coverage) { + $CoverFiles = Get-CoverageIndications -Path $f -ModuleBase $ModuleBase + if (!$DependencyCoverage) { + $CoverFiles = $CoverFiles | Select-Object -First 1 + } + $PesterSplat['CodeCoverage'] = $CoverFiles + } + + if (!($testInt)) { + $PesterSplat['ExcludeTag'] = "IntegrationTests" + } + + Invoke-Pester @PesterSplat } - Invoke-Pester @PesterSplat + if ($ScriptAnalyzer) { + $HeadFunctionPath = (Get-CoverageIndications -Path $f -ModuleBase $ModuleBase | Select-Object -First 1) if ($Show -ne "None") { Write-Host -ForegroundColor green -Object "ScriptAnalyzer check for $HeadFunctionPath" } diff --git a/tests/Add-DbaAgDatabase.Tests.ps1 b/tests/Add-DbaAgDatabase.Tests.ps1 index 92e8af11aa..ccb05af6a2 100644 --- a/tests/Add-DbaAgDatabase.Tests.ps1 +++ b/tests/Add-DbaAgDatabase.Tests.ps1 @@ -1,14 +1,15 @@ #Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} -param($ModuleName = "dbatools") -$global:TestConfig = Get-TestConfig +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) Describe "Add-DbaAgDatabase" -Tag "UnitTests" { Context "Parameter validation" { BeforeAll { $command = Get-Command Add-DbaAgDatabase - $expectedParameters = $TestConfig.CommonParameters - - $expectedParameters += @( + $expected = $TestConfig.CommonParameters + $expected += @( "SqlInstance", "SqlCredential", "AvailabilityGroup", @@ -20,17 +21,19 @@ Describe "Add-DbaAgDatabase" -Tag "UnitTests" { "SharedPath", "UseLastBackup", "AdvancedBackupParams", - "EnableException" + "EnableException", + "Confirm", + "WhatIf" ) } - It "Should have exactly the expected parameters" { - $actualParameters = $command.Parameters.Keys | Where-Object { $PSItem -notin "WhatIf", "Confirm" } - Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $actualParameters | Should -BeNullOrEmpty + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem } - It "Has parameter: <_>" -ForEach $expectedParameters { - $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 } } } @@ -65,7 +68,13 @@ Describe "Add-DbaAgDatabase" -Tag "IntegrationTests" { BeforeAll { $server.Query("create database $newdbname") $backup = Get-DbaDatabase -SqlInstance $TestConfig.instance3 -Database $newdbname | Backup-DbaDatabase - $results = Add-DbaAgDatabase -SqlInstance $TestConfig.instance3 -AvailabilityGroup $agname -Database $newdbname -Confirm:$false + $splatAddAgDb = @{ + SqlInstance = $TestConfig.instance3 + AvailabilityGroup = $agname + Database = $newdbname + Confirm = $false + } + $results = Add-DbaAgDatabase @splatAddAgDb } It "Returns proper results" { diff --git a/tests/Add-DbaAgListener.Tests.ps1 b/tests/Add-DbaAgListener.Tests.ps1 index 8acdaf329a..e382a17034 100644 --- a/tests/Add-DbaAgListener.Tests.ps1 +++ b/tests/Add-DbaAgListener.Tests.ps1 @@ -1,14 +1,15 @@ #Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} -param($ModuleName = "dbatools") -$global:TestConfig = Get-TestConfig +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) Describe "Add-DbaAgListener" -Tag "UnitTests" { Context "Parameter validation" { BeforeAll { $command = Get-Command Add-DbaAgListener - $expectedParameters = $TestConfig.CommonParameters - - $expectedParameters += @( + $expected = $TestConfig.CommonParameters + $expected += @( "SqlInstance", "SqlCredential", "AvailabilityGroup", @@ -20,17 +21,19 @@ Describe "Add-DbaAgListener" -Tag "UnitTests" { "Dhcp", "Passthru", "InputObject", - "EnableException" + "EnableException", + "Confirm", + "WhatIf" ) } - It "Should have exactly the expected parameters" { - $actualParameters = $command.Parameters.Keys | Where-Object { $PSItem -notin "WhatIf", "Confirm" } - Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $actualParameters | Should -BeNullOrEmpty + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem } - It "Has parameter: <_>" -ForEach $expectedParameters { - $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 } } } @@ -39,19 +42,15 @@ Describe "Add-DbaAgListener" -Tag "IntegrationTests" { BeforeAll { $agname = "dbatoolsci_ag_newlistener" $listenerName = 'dbatoolsci_listener' - $splatPrimary = @{ + $splatNewAg = @{ Primary = $TestConfig.instance3 Name = $agname ClusterType = "None" FailoverMode = "Manual" - Certificate = "dbatoolsci_AGCert" Confirm = $false + Certificate = "dbatoolsci_AGCert" } - $ag = New-DbaAvailabilityGroup @splatPrimary - } - - AfterEach { - $null = Remove-DbaAgListener -SqlInstance $TestConfig.instance3 -Listener $listenerName -AvailabilityGroup $agname -Confirm:$false + $ag = New-DbaAvailabilityGroup @splatNewAg } AfterAll { @@ -59,8 +58,21 @@ Describe "Add-DbaAgListener" -Tag "IntegrationTests" { } Context "When creating a listener" { + BeforeAll { + $splatAddListener = @{ + Name = $listenerName + IPAddress = "127.0.20.1" + Port = 14330 + Confirm = $false + } + $results = $ag | Add-DbaAgListener @splatAddListener + } + + AfterAll { + $null = Remove-DbaAgListener -SqlInstance $TestConfig.instance3 -Listener $listenerName -AvailabilityGroup $agname -Confirm:$false + } + It "Returns results with proper data" { - $results = $ag | Add-DbaAgListener -Name $listenerName -IPAddress 127.0.20.1 -Port 14330 -Confirm:$false $results.PortNumber | Should -Be 14330 } } diff --git a/tests/Add-DbaAgReplica.Tests.ps1 b/tests/Add-DbaAgReplica.Tests.ps1 index b8e1494da2..c5e9de136c 100644 --- a/tests/Add-DbaAgReplica.Tests.ps1 +++ b/tests/Add-DbaAgReplica.Tests.ps1 @@ -1,14 +1,15 @@ #Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} -param($ModuleName = "dbatools") -$global:TestConfig = Get-TestConfig +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) Describe "Add-DbaAgReplica" -Tag "UnitTests" { Context "Parameter validation" { BeforeAll { $command = Get-Command Add-DbaAgReplica - $expectedParameters = $TestConfig.CommonParameters - - $expectedParameters += @( + $expected = $TestConfig.CommonParameters + $expected += @( "SqlInstance", "SqlCredential", "Name", @@ -28,66 +29,67 @@ Describe "Add-DbaAgReplica" -Tag "UnitTests" { "ConfigureXESession", "SessionTimeout", "InputObject", - "EnableException" + "EnableException", + "Confirm", + "WhatIf" ) } - It "Should have exactly the expected parameters" { - $actualParameters = $command.Parameters.Keys | Where-Object { $PSItem -notin "WhatIf", "Confirm" } - Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $actualParameters | Should -BeNullOrEmpty + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem } - It "Has parameter: <_>" -ForEach $expectedParameters { - $command | Should -HaveParameter $PSItem + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } Describe "Add-DbaAgReplica" -Tag "IntegrationTests" { BeforeAll { - $agname = "dbatoolsci_agroup" + $primaryAgName = "dbatoolsci_agroup" $splatPrimary = @{ - Primary = $TestConfig.instance3 - Name = $agname - ClusterType = "None" + Primary = $TestConfig.instance3 + Name = $primaryAgName + ClusterType = "None" FailoverMode = "Manual" - Certificate = "dbatoolsci_AGCert" - Confirm = $false + Certificate = "dbatoolsci_AGCert" + Confirm = $false } - $ag = New-DbaAvailabilityGroup @splatPrimary - $replicaName = $ag.PrimaryReplica + $primaryAg = New-DbaAvailabilityGroup @splatPrimary + $replicaName = $primaryAg.PrimaryReplica } AfterAll { - $null = Remove-DbaAvailabilityGroup -SqlInstance $TestConfig.instance3 -AvailabilityGroup $agname -Confirm:$false + $null = Remove-DbaAvailabilityGroup -SqlInstance $TestConfig.instance3 -AvailabilityGroup $primaryAgName -Confirm:$false } Context "When adding AG replicas" { BeforeAll { - $agname = "dbatoolsci_add_replicagroup" - $splatNewAg = @{ - Primary = $TestConfig.instance3 - Name = $agname - ClusterType = "None" + $replicaAgName = "dbatoolsci_add_replicagroup" + $splatRepAg = @{ + Primary = $TestConfig.instance3 + Name = $replicaAgName + ClusterType = "None" FailoverMode = "Manual" - Certificate = "dbatoolsci_AGCert" - Confirm = $false + Certificate = "dbatoolsci_AGCert" + Confirm = $false } - $ag = New-DbaAvailabilityGroup @splatNewAg - $replicaName = $ag.PrimaryReplica + $replicaAg = New-DbaAvailabilityGroup @splatRepAg } It "Returns results with proper data" { $results = Get-DbaAgReplica -SqlInstance $TestConfig.instance3 - $results.AvailabilityGroup | Should -Contain $agname + $results.AvailabilityGroup | Should -Contain $replicaAgName $results.Role | Should -Contain 'Primary' $results.AvailabilityMode | Should -Contain 'SynchronousCommit' $results.FailoverMode | Should -Contain 'Manual' } - It "Returns just one result" { - $results = Get-DbaAgReplica -SqlInstance $TestConfig.instance3 -Replica $replicaName -AvailabilityGroup $agname - $results.AvailabilityGroup | Should -Be $agname + It "Returns just one result for a specific replica" { + $results = Get-DbaAgReplica -SqlInstance $TestConfig.instance3 -Replica $replicaName -AvailabilityGroup $replicaAgName + $results.AvailabilityGroup | Should -Be $replicaAgName $results.Role | Should -Be 'Primary' $results.AvailabilityMode | Should -Be 'SynchronousCommit' $results.FailoverMode | Should -Be 'Manual' diff --git a/tests/Add-DbaComputerCertificate.Tests.ps1 b/tests/Add-DbaComputerCertificate.Tests.ps1 index f0875493f6..9d29be9fcf 100644 --- a/tests/Add-DbaComputerCertificate.Tests.ps1 +++ b/tests/Add-DbaComputerCertificate.Tests.ps1 @@ -1,14 +1,15 @@ #Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} -param($ModuleName = "dbatools") -$global:TestConfig = Get-TestConfig +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) Describe "Add-DbaComputerCertificate" -Tag "UnitTests" { Context "Parameter validation" { BeforeAll { $command = Get-Command Add-DbaComputerCertificate - $expectedParameters = $TestConfig.CommonParameters - - $expectedParameters += @( + $expected = $TestConfig.CommonParameters + $expected += @( "ComputerName", "Credential", "SecurePassword", @@ -17,17 +18,19 @@ Describe "Add-DbaComputerCertificate" -Tag "UnitTests" { "Store", "Folder", "Flag", - "EnableException" + "EnableException", + "Confirm", + "WhatIf" ) } - It "Should have exactly the expected parameters" { - $actualParameters = $command.Parameters.Keys | Where-Object { $PSItem -notin "WhatIf", "Confirm" } - Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $actualParameters | Should -BeNullOrEmpty + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem } - It "Has parameter: <_>" -ForEach $expectedParameters { - $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 } } } @@ -35,11 +38,8 @@ Describe "Add-DbaComputerCertificate" -Tag "UnitTests" { Describe "Add-DbaComputerCertificate" -Tag "IntegrationTests" { Context "Certificate is added properly" { BeforeAll { - $results = Add-DbaComputerCertificate -Path "$($TestConfig.appveyorlabrepo)\certificates\localhost.crt" -Confirm:$false - } - - AfterAll { - Remove-DbaComputerCertificate -Thumbprint 29C469578D6C6211076A09CEE5C5797EEA0C2713 -Confirm:$false + $certPath = "$($TestConfig.appveyorlabrepo)\certificates\localhost.crt" + $results = Add-DbaComputerCertificate -Path $certPath -Confirm:$false } It "Should show the proper thumbprint has been added" { @@ -49,5 +49,9 @@ Describe "Add-DbaComputerCertificate" -Tag "IntegrationTests" { It "Should be in LocalMachine\My Cert Store" { $results.PSParentPath | Should -Be "Microsoft.PowerShell.Security\Certificate::LocalMachine\My" } + + AfterAll { + Remove-DbaComputerCertificate -Thumbprint 29C469578D6C6211076A09CEE5C5797EEA0C2713 -Confirm:$false + } } } diff --git a/tests/Add-DbaDbMirrorMonitor.Tests.ps1 b/tests/Add-DbaDbMirrorMonitor.Tests.ps1 index 3f3ef63d76..f78e90b2a6 100644 --- a/tests/Add-DbaDbMirrorMonitor.Tests.ps1 +++ b/tests/Add-DbaDbMirrorMonitor.Tests.ps1 @@ -1,19 +1,35 @@ -$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", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) -Describe "$CommandName Unit Tests" -Tags "UnitTests" { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe "Add-DbaDbMirrorMonitor" -Tag "UnitTests" { + Context "Parameter validation" { + BeforeAll { + $command = Get-Command Add-DbaDbMirrorMonitor + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "EnableException", + "Confirm", + "WhatIf" + ) + } + + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tag "IntegrationTests" { +Describe "Add-DbaDbMirrorMonitor" -Tag "IntegrationTests" { BeforeAll { $null = Remove-DbaDbMirrorMonitor -SqlInstance $TestConfig.instance2 -WarningAction SilentlyContinue } @@ -21,8 +37,13 @@ Describe "$commandname Integration Tests" -Tag "IntegrationTests" { $null = Remove-DbaDbMirrorMonitor -SqlInstance $TestConfig.instance2 -WarningAction SilentlyContinue } - It "adds the mirror monitor" { - $results = Add-DbaDbMirrorMonitor -SqlInstance $TestConfig.instance2 -WarningAction SilentlyContinue - $results.MonitorStatus | Should -Be 'Added' + Context "When adding mirror monitor" { + BeforeAll { + $results = Add-DbaDbMirrorMonitor -SqlInstance $TestConfig.instance2 -WarningAction SilentlyContinue + } + + It "Adds the mirror monitor" { + $results.MonitorStatus | Should -Be 'Added' + } } } diff --git a/tests/Add-DbaDbRoleMember.Tests.ps1 b/tests/Add-DbaDbRoleMember.Tests.ps1 index 956e9226b0..ec58154baa 100644 --- a/tests/Add-DbaDbRoleMember.Tests.ps1 +++ b/tests/Add-DbaDbRoleMember.Tests.ps1 @@ -1,19 +1,39 @@ -$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", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) -Describe "$CommandName Unit Tests" -Tags "UnitTests" { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'Role', 'Member', 'InputObject', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe "Add-DbaDbRoleMember" -Tag "UnitTests" { + Context "Parameter validation" { + BeforeAll { + $command = Get-Command Add-DbaDbRoleMember + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "Database", + "Role", + "Member", + "InputObject", + "EnableException", + "Confirm", + "WhatIf" + ) + } + + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { +Describe "Add-DbaDbRoleMember" -Tag "IntegrationTests" { BeforeAll { $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 $user1 = "dbatoolssci_user1_$(Get-Random)" @@ -29,58 +49,75 @@ Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { $null = New-DbaDbUser -SqlInstance $TestConfig.instance2 -Database msdb -Login $user2 -Username $user2 -IncludeSystem $null = $server.Query("CREATE ROLE $role", $dbname) } + AfterAll { $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 $null = $server.Query("DROP USER $user1", 'msdb') $null = $server.Query("DROP USER $user2", 'msdb') - $null = Remove-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname -confirm:$false - $null = Remove-DbaLogin -SqlInstance $TestConfig.instance2 -Login $user1, $user2 -confirm:$false + $null = Remove-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname -Confirm:$false + $null = Remove-DbaLogin -SqlInstance $TestConfig.instance2 -Login $user1, $user2 -Confirm:$false } - Context "Functionality" { - It 'Adds User to Role' { - Add-DbaDbRoleMember -SqlInstance $TestConfig.instance2 -Role $role -Member $user1 -Database $dbname -confirm:$false + Context "When adding a user to a role" { + BeforeAll { + $result = Add-DbaDbRoleMember -SqlInstance $TestConfig.instance2 -Role $role -Member $user1 -Database $dbname -Confirm:$false $roleDBAfter = Get-DbaDbRoleMember -SqlInstance $server -Database $dbname -Role $role + } - $roleDBAfter.Role | Should Be $role - $roleDBAfter.Login | Should Be $user1 - $roleDBAfter.UserName | Should Be $user1 + It "Adds the user to the role" { + $roleDBAfter.Role | Should -Be $role + $roleDBAfter.Login | Should -Be $user1 + $roleDBAfter.UserName | Should -Be $user1 } + } - It 'Adds User to Multiple Roles' { + Context "When adding a user to multiple roles" { + BeforeAll { $roleDB = Get-DbaDbRoleMember -SqlInstance $server -Database msdb -Role db_datareader, SQLAgentReaderRole - Add-DbaDbRoleMember -SqlInstance $TestConfig.instance2 -Role db_datareader, SQLAgentReaderRole -Member $user1 -Database msdb -confirm:$false - + $result = Add-DbaDbRoleMember -SqlInstance $TestConfig.instance2 -Role db_datareader, SQLAgentReaderRole -Member $user1 -Database msdb -Confirm:$false $roleDBAfter = Get-DbaDbRoleMember -SqlInstance $server -Database msdb -Role db_datareader, SQLAgentReaderRole - $roleDBAfter.Count | Should BeGreaterThan $roleDB.Count - $roleDB.UserName -contains $user1 | Should Be $false - $roleDBAfter.UserName -contains $user1 | Should Be $true + } + It "Adds the user to multiple roles" { + $roleDBAfter.Count | Should -BeGreaterThan $roleDB.Count + $roleDB.UserName | Should -Not -Contain $user1 + $roleDBAfter.UserName | Should -Contain $user1 } + } - It 'Adds User to Roles via piped input from Get-DbaDbRole' { + Context "When adding a user to roles via piped input from Get-DbaDbRole" { + BeforeAll { $roleInput = Get-DbaDbRole -SqlInstance $server -Database msdb -Role db_datareader, SQLAgentReaderRole $roleDB = Get-DbaDbRoleMember -SqlInstance $server -Database msdb -Role db_datareader, SQLAgentReaderRole - $roleInput | Add-DbaDbRoleMember -User $user2 -confirm:$false - + $result = $roleInput | Add-DbaDbRoleMember -User $user2 -Confirm:$false $roleDBAfter = Get-DbaDbRoleMember -SqlInstance $server -Database msdb -Role db_datareader, SQLAgentReaderRole - $roleDB.UserName -contains $user2 | Should Be $false - $roleDBAfter.UserName -contains $user2 | Should Be $true } - It 'Skip adding user to role if already a member' { - $messages = Add-DbaDbRoleMember -SqlInstance $TestConfig.instance2 -Role $role -Member $user1 -Database $dbname -confirm:$false -Verbose 4>&1 - $messageCount = ($messages -match 'Adding user').Count + It "Adds the user to roles via piped input" { + $roleDB.UserName | Should -Not -Contain $user2 + $roleDBAfter.UserName | Should -Contain $user2 + } + } + + Context "When adding a user to a role they are already a member of" { + BeforeAll { + $messages = Add-DbaDbRoleMember -SqlInstance $TestConfig.instance2 -Role $role -Member $user1 -Database $dbname -Confirm:$false -Verbose 4>&1 + } - $messageCount | Should Be 0 + It "Skips adding the user and outputs appropriate message" { + $messageCount = ($messages -match 'Adding user').Count + $messageCount | Should -Be 0 } + } - It 'Adds Role to Role' { - Add-DbaDbRoleMember -SqlInstance $TestConfig.instance2 -Role db_datawriter -Member $role -Database $dbname -confirm:$false + Context "When adding a role to another role" { + BeforeAll { + $result = Add-DbaDbRoleMember -SqlInstance $TestConfig.instance2 -Role db_datawriter -Member $role -Database $dbname -Confirm:$false $roleDBAfter = Get-DbaDbRoleMember -SqlInstance $server -Database $dbname -Role db_datawriter + } - $roleDBAfter.MemberRole | Should Contain $role + It "Adds the role to another role" { + $roleDBAfter.MemberRole | Should -Contain $role } } } - diff --git a/tests/Add-DbaExtendedProperty.Tests.ps1 b/tests/Add-DbaExtendedProperty.Tests.ps1 index ba4339484b..1ca2c17d6e 100644 --- a/tests/Add-DbaExtendedProperty.Tests.ps1 +++ b/tests/Add-DbaExtendedProperty.Tests.ps1 @@ -1,19 +1,39 @@ -$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", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [array]$params = ([Management.Automation.CommandMetaData]$ExecutionContext.SessionState.InvokeCommand.GetCommand($CommandName, 'Function')).Parameters.Keys - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'Name', 'InputObject', 'EnableException', 'Value' - It "Should only contain our specific parameters" { - Compare-Object -ReferenceObject $knownParameters -DifferenceObject $params | Should -BeNullOrEmpty +Describe "Add-DbaExtendedProperty" -Tag "UnitTests" { + Context "Parameter validation" { + BeforeAll { + $command = Get-Command Add-DbaExtendedProperty + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "Database", + "Name", + "Value", + "InputObject", + "EnableException", + "Confirm", + "WhatIf" + ) + } + + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { - +Describe "Add-DbaExtendedProperty" -Tag "IntegrationTests" { BeforeAll { $random = Get-Random $server2 = Connect-DbaInstance -SqlInstance $TestConfig.instance2 @@ -26,9 +46,13 @@ Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { $null = $db | Remove-DbaDatabase -Confirm:$false } - Context "commands work as expected" { - It "works" { - $ep = $db | Add-DbaExtendedProperty -Name "Test_Database_Name" -Value "Sup" + Context "When adding extended properties" { + It "Adds an extended property to the database" { + $splatExtendedProperty = @{ + Name = "Test_Database_Name" + Value = "Sup" + } + $ep = $db | Add-DbaExtendedProperty @splatExtendedProperty $ep.Name | Should -Be "Test_Database_Name" $ep.ParentName | Should -Be $db.Name $ep.Value | Should -Be "Sup" diff --git a/tests/Add-DbaPfDataCollectorCounter.Tests.ps1 b/tests/Add-DbaPfDataCollectorCounter.Tests.ps1 index 3d7b0a2213..bbbee53ba7 100644 --- a/tests/Add-DbaPfDataCollectorCounter.Tests.ps1 +++ b/tests/Add-DbaPfDataCollectorCounter.Tests.ps1 @@ -1,31 +1,66 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig - -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'ComputerName', 'Credential', 'CollectorSet', 'Collector', 'Counter', 'InputObject', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + +Describe "Add-DbaPfDataCollectorCounter" -Tag "UnitTests" { + Context "Parameter validation" { + BeforeAll { + $command = Get-Command Add-DbaPfDataCollectorCounter + $expected = $TestConfig.CommonParameters + $expected += @( + "ComputerName", + "Credential", + "CollectorSet", + "Collector", + "Counter", + "InputObject", + "EnableException", + "Confirm", + "WhatIf" + ) + } + + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { +Describe "Add-DbaPfDataCollectorCounter" -Tag "IntegrationTests" { + BeforeAll { + $PSDefaultParameterValues['*:Confirm'] = $false + } + BeforeEach { - $null = Get-DbaPfDataCollectorSetTemplate -Template 'Long Running Queries' | Import-DbaPfDataCollectorSetTemplate | - Get-DbaPfDataCollector | Get-DbaPfDataCollectorCounter -Counter '\LogicalDisk(*)\Avg. Disk Queue Length' | Remove-DbaPfDataCollectorCounter -Confirm:$false + $null = Get-DbaPfDataCollectorSetTemplate -Template 'Long Running Queries' | + Import-DbaPfDataCollectorSetTemplate | + Get-DbaPfDataCollector | + Get-DbaPfDataCollectorCounter -Counter '\LogicalDisk(*)\Avg. Disk Queue Length' | + Remove-DbaPfDataCollectorCounter + + $results = Get-DbaPfDataCollectorSet -CollectorSet 'Long Running Queries' | Get-DbaPfDataCollector | + Add-DbaPfDataCollectorCounter -Counter '\LogicalDisk(*)\Avg. Disk Queue Length' } + AfterAll { - $null = Get-DbaPfDataCollectorSet -CollectorSet 'Long Running Queries' | Remove-DbaPfDataCollectorSet -Confirm:$false + $null = Get-DbaPfDataCollectorSet -CollectorSet 'Long Running Queries' | + Remove-DbaPfDataCollectorSet } - Context "Verifying command returns all the required results" { - It "returns the correct values" { - $results = Get-DbaPfDataCollectorSet -CollectorSet 'Long Running Queries' | Get-DbaPfDataCollector | Add-DbaPfDataCollectorCounter -Counter '\LogicalDisk(*)\Avg. Disk Queue Length' - $results.DataCollectorSet | Should Be 'Long Running Queries' - $results.Name | Should Be '\LogicalDisk(*)\Avg. Disk Queue Length' + + Context "When adding a counter to a data collector" { + It "Returns the correct DataCollectorSet" { + $results.DataCollectorSet | Should -Be 'Long Running Queries' + } + + It "Returns the correct counter name" { + $results.Name | Should -Be '\LogicalDisk(*)\Avg. Disk Queue Length' } } -} \ No newline at end of file +} diff --git a/tests/Add-DbaRegServer.Tests.ps1 b/tests/Add-DbaRegServer.Tests.ps1 index 76bacdcd5b..e0db506d16 100644 --- a/tests/Add-DbaRegServer.Tests.ps1 +++ b/tests/Add-DbaRegServer.Tests.ps1 @@ -1,44 +1,103 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig - -Describe "$CommandName Unit Tests" -Tags "UnitTests" { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'ServerName', 'Name', 'Description', 'Group', 'ActiveDirectoryTenant', 'ActiveDirectoryUserId', 'ConnectionString', 'OtherParams', 'InputObject', 'ServerObject', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + +Describe "Add-DbaRegServer" -Tag "UnitTests" { + Context "Parameter validation" { + BeforeAll { + $command = Get-Command Add-DbaRegServer + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "ServerName", + "Name", + "Description", + "Group", + "ActiveDirectoryTenant", + "ActiveDirectoryUserId", + "ConnectionString", + "OtherParams", + "InputObject", + "ServerObject", + "EnableException", + "Confirm", + "WhatIf" + ) + } + + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { - Context "Setup" { +Describe "Add-DbaRegServer" -Tag "IntegrationTests" { + BeforeAll { + $srvName = "dbatoolsci-server1" + $group = "dbatoolsci-group1" + $regSrvName = "dbatoolsci-server12" + $regSrvDesc = "dbatoolsci-server123" + $groupobject = Add-DbaRegServerGroup -SqlInstance $TestConfig.instance1 -Name $group + } + + AfterAll { + Get-DbaRegServer -SqlInstance $TestConfig.instance1, $TestConfig.instance2 | Where-Object Name -match dbatoolsci | Remove-DbaRegServer -Confirm:$false + Get-DbaRegServerGroup -SqlInstance $TestConfig.instance1, $TestConfig.instance2 | Where-Object Name -match dbatoolsci | Remove-DbaRegServerGroup -Confirm:$false + } + + Context "When adding a registered server" { BeforeAll { - $srvName = "dbatoolsci-server1" - $group = "dbatoolsci-group1" - $regSrvName = "dbatoolsci-server12" - $regSrvDesc = "dbatoolsci-server123" - $groupobject = Add-DbaRegServerGroup -SqlInstance $TestConfig.instance1 -Name $group - } - AfterAll { - Get-DbaRegServer -SqlInstance $TestConfig.instance1, $TestConfig.instance2 | Where-Object Name -match dbatoolsci | Remove-DbaRegServer -Confirm:$false - Get-DbaRegServerGroup -SqlInstance $TestConfig.instance1, $TestConfig.instance2 | Where-Object Name -match dbatoolsci | Remove-DbaRegServerGroup -Confirm:$false + $results1 = Add-DbaRegServer -SqlInstance $TestConfig.instance1 -ServerName $srvName } - It "adds a registered server" { - $results1 = Add-DbaRegServer -SqlInstance $TestConfig.instance1 -ServerName $srvName + It "Adds a registered server with correct name" { $results1.Name | Should -Be $srvName + } + + It "Adds a registered server with correct server name" { $results1.ServerName | Should -Be $srvName - $results1.SqlInstance | Should -Not -Be $null } - It "adds a registered server with extended properties" { - $results2 = Add-DbaRegServer -SqlInstance $TestConfig.instance1 -ServerName $RegsrvName -Name $srvName -Group $groupobject -Description $regSrvDesc + + It "Adds a registered server with non-null SqlInstance" { + $results1.SqlInstance | Should -Not -BeNullOrEmpty + } + } + + Context "When adding a registered server with extended properties" { + BeforeAll { + $splat = @{ + SqlInstance = $TestConfig.instance1 + ServerName = $regSrvName + Name = $srvName + Group = $groupobject + Description = $regSrvDesc + } + + $results2 = Add-DbaRegServer @splat + } + + It "Adds a registered server with correct server name" { $results2.ServerName | Should -Be $regSrvName + } + + It "Adds a registered server with correct description" { $results2.Description | Should -Be $regSrvDesc + } + + It "Adds a registered server with correct name" { $results2.Name | Should -Be $srvName - $results2.SqlInstance | Should -Not -Be $null + } + + It "Adds a registered server with non-null SqlInstance" { + $results2.SqlInstance | Should -Not -BeNullOrEmpty } } } diff --git a/tests/Add-DbaRegServerGroup.Tests.ps1 b/tests/Add-DbaRegServerGroup.Tests.ps1 index 14df3ef2b0..7ab260ea0b 100644 --- a/tests/Add-DbaRegServerGroup.Tests.ps1 +++ b/tests/Add-DbaRegServerGroup.Tests.ps1 @@ -1,55 +1,87 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig - -Describe "$CommandName Unit Tests" -Tags "UnitTests" { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Name', 'Description', 'Group', 'InputObject', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 - } - } -} +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) -Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { - Context "Setup" { +Describe "Add-DbaRegServerGroup" -Tag "UnitTests" { + Context "Parameter validation" { BeforeAll { - $group = "dbatoolsci-group1" - $group2 = "dbatoolsci-group2" - $description = "group description" - $descriptionUpdated = "group description updated" + $command = Get-Command Add-DbaRegServerGroup + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "Name", + "Description", + "Group", + "InputObject", + "EnableException", + "Confirm", + "WhatIf" + ) } - AfterAll { - Get-DbaRegServerGroup -SqlInstance $TestConfig.instance1 | Where-Object Name -match dbatoolsci | Remove-DbaRegServerGroup -Confirm:$false + + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem } + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty + } + } +} + +Describe "Add-DbaRegServerGroup" -Tag "IntegrationTests" { + BeforeAll { + $group = "dbatoolsci-group1" + $group2 = "dbatoolsci-group2" + $description = "group description" + $descriptionUpdated = "group description updated" + } + AfterAll { + Get-DbaRegServerGroup -SqlInstance $TestConfig.instance1 | Where-Object Name -match dbatoolsci | Remove-DbaRegServerGroup -Confirm:$false + } + + Context "When adding a registered server group" { It "adds a registered server group" { $results = Add-DbaRegServerGroup -SqlInstance $TestConfig.instance1 -Name $group $results.Name | Should -Be $group - $results.SqlInstance | Should -Not -Be $null + $results.SqlInstance | Should -Not -BeNullOrEmpty } + It "adds a registered server group with extended properties" { $results = Add-DbaRegServerGroup -SqlInstance $TestConfig.instance1 -Name $group2 -Description $description $results.Name | Should -Be $group2 $results.Description | Should -Be $description - $results.SqlInstance | Should -Not -Be $null + $results.SqlInstance | Should -Not -BeNullOrEmpty } - It "supports hella pipe" { - $results = Get-DbaRegServerGroup -SqlInstance $TestConfig.instance1 -Id 1 | Add-DbaRegServerGroup -Name dbatoolsci-first | Add-DbaRegServerGroup -Name dbatoolsci-second | Add-DbaRegServerGroup -Name dbatoolsci-third | Add-DbaRegServer -ServerName dbatoolsci-test -Description ridiculous + } + + Context "When using pipeline input" { + It "supports pipeline input" { + $results = Get-DbaRegServerGroup -SqlInstance $TestConfig.instance1 -Id 1 | + Add-DbaRegServerGroup -Name dbatoolsci-first | + Add-DbaRegServerGroup -Name dbatoolsci-second | + Add-DbaRegServerGroup -Name dbatoolsci-third | + Add-DbaRegServer -ServerName dbatoolsci-test -Description ridiculous $results.Group | Should -Be 'dbatoolsci-first\dbatoolsci-second\dbatoolsci-third' } + } + + Context "When adding nested groups" { It "adds a registered server group and sub-group when not exists" { $results = Add-DbaRegServerGroup -SqlInstance $TestConfig.instance1 -Name "$group\$group2" -Description $description $results.Name | Should -Be $group2 - $results.SqlInstance | Should -Not -Be $null + $results.SqlInstance | Should -Not -BeNullOrEmpty } + It "updates description of sub-group when it already exists" { $results = Add-DbaRegServerGroup -SqlInstance $TestConfig.instance1 -Name "$group\$group2" -Description $descriptionUpdated $results.Name | Should -Be $group2 $results.Description | Should -Be $descriptionUpdated - $results.SqlInstance | Should -Not -Be $null + $results.SqlInstance | Should -Not -BeNullOrEmpty } } } diff --git a/tests/Add-DbaReplArticle.Tests.ps1 b/tests/Add-DbaReplArticle.Tests.ps1 index aed3185e0f..3da2149402 100644 --- a/tests/Add-DbaReplArticle.Tests.ps1 +++ b/tests/Add-DbaReplArticle.Tests.ps1 @@ -1,17 +1,40 @@ -$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", + $PSDefaultParameterValues = ($TestConfig = Get-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', 'Publication', 'Schema', 'Name', 'Filter', 'CreationScriptOptions', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe "Add-DbaReplArticle" -Tag "UnitTests" { + Context "Parameter validation" { + BeforeAll { + $command = Get-Command Add-DbaReplArticle + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "Database", + "Publication", + "Schema", + "Name", + "Filter", + "CreationScriptOptions", + "EnableException", + "WhatIf", + "Confirm" + ) + } + + 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 } } } + <# Integration tests for replication are in GitHub Actions and run from \tests\gh-actions-repl-*.ps1.ps1 -#> \ No newline at end of file +#> diff --git a/tests/Add-DbaServerRoleMember.Tests.ps1 b/tests/Add-DbaServerRoleMember.Tests.ps1 index aac1596439..145cdbe47b 100644 --- a/tests/Add-DbaServerRoleMember.Tests.ps1 +++ b/tests/Add-DbaServerRoleMember.Tests.ps1 @@ -1,59 +1,107 @@ -$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", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) -Describe "$CommandName Unit Tests" -Tags "UnitTests" { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('WhatIf', 'Confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'ServerRole', 'Login', 'Role', 'InputObject', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should -Be 0 +Describe "Add-DbaServerRoleMember" -Tag "UnitTests" { + Context "Parameter validation" { + BeforeAll { + $command = Get-Command Add-DbaServerRoleMember + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "ServerRole", + "Login", + "Role", + "InputObject", + "EnableException", + "Confirm", + "WhatIf" + ) + } + + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { +Describe "Add-DbaServerRoleMember" -Tag "IntegrationTests" { BeforeAll { $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 $login1 = "dbatoolsci_login1_$(Get-Random)" $login2 = "dbatoolsci_login2_$(Get-Random)" $customServerRole = "dbatoolsci_customrole_$(Get-Random)" - $fixedServerRoles = 'dbcreator','processadmin' - $null = New-DbaLogin -SqlInstance $TestConfig.instance2 -Login $login1 -Password ('Password1234!' | ConvertTo-SecureString -asPlainText -Force) - $null = New-DbaLogin -SqlInstance $TestConfig.instance2 -Login $login2 -Password ('Password1234!' | ConvertTo-SecureString -asPlainText -Force) + $fixedServerRoles = @( + "dbcreator", + "processadmin" + ) + $splatNewLogin = @{ + SqlInstance = $TestConfig.instance2 + Password = ('Password1234!' | ConvertTo-SecureString -asPlainText -Force) + } + $null = New-DbaLogin @splatNewLogin -Login $login1 + $null = New-DbaLogin @splatNewLogin -Login $login2 $null = New-DbaServerRole -SqlInstance $TestConfig.instance2 -ServerRole $customServerRole -Owner sa } AfterAll { - $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 - $null = Remove-DbaLogin -SqlInstance $TestConfig.instance2 -Login $login1, $login2 -Confirm:$false + $splatRemoveLogin = @{ + SqlInstance = $TestConfig.instance2 + Login = $login1, $login2 + Confirm = $false + } + $null = Remove-DbaLogin @splatRemoveLogin } Context "Functionality" { It 'Adds Login to Role' { - Add-DbaServerRoleMember -SqlInstance $TestConfig.instance2 -ServerRole $fixedServerRoles[0] -Login $login1 -Confirm:$false + $splatAddRole = @{ + SqlInstance = $TestConfig.instance2 + ServerRole = $fixedServerRoles[0] + Login = $login1 + Confirm = $false + } + Add-DbaServerRoleMember @splatAddRole $roleAfter = Get-DbaServerRole -SqlInstance $server -ServerRole $fixedServerRoles[0] $roleAfter.Role | Should -Be $fixedServerRoles[0] - $roleAfter.EnumMemberNames().Contains($login1) | Should -Be $true + $roleAfter.EnumMemberNames() | Should -Contain $login1 } It 'Adds Login to Multiple Roles' { $serverRoles = Get-DbaServerRole -SqlInstance $server -ServerRole $fixedServerRoles - Add-DbaServerRoleMember -SqlInstance $TestConfig.instance2 -ServerRole $serverRoles -Login $login1 -Confirm:$false + $splatAddRoles = @{ + SqlInstance = $TestConfig.instance2 + ServerRole = $serverRoles + Login = $login1 + Confirm = $false + } + Add-DbaServerRoleMember @splatAddRoles $roleDBAfter = Get-DbaServerRole -SqlInstance $server -ServerRole $fixedServerRoles $roleDBAfter.Count | Should -Be $serverRoles.Count - $roleDBAfter.Login -contains $login1 | Should -Be $true - + $roleDBAfter.Login | Should -Contain $login1 } It 'Adds Customer Server-Level Role Membership' { - Add-DbaServerRoleMember -SqlInstance $TestConfig.instance2 -ServerRole $customServerRole -Role $fixedServerRoles[-1] -Confirm:$false + $splatAddCustomRole = @{ + SqlInstance = $TestConfig.instance2 + ServerRole = $customServerRole + Role = $fixedServerRoles[-1] + Confirm = $false + } + Add-DbaServerRoleMember @splatAddCustomRole $roleAfter = Get-DbaServerRole -SqlInstance $server -ServerRole $fixedServerRoles[-1] $roleAfter.Role | Should -Be $fixedServerRoles[-1] - $roleAfter.EnumMemberNames().Contains($customServerRole) | Should -Be $true + $roleAfter.EnumMemberNames() | Should -Contain $customServerRole } It 'Adds Login to Roles via piped input from Get-DbaServerRole' { @@ -61,7 +109,7 @@ Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { $serverRole | Add-DbaServerRoleMember -Login $login2 -Confirm:$false $roleAfter = Get-DbaServerRole -SqlInstance $server -ServerRole $fixedServerRoles[0] - $roleAfter.EnumMemberNames().Contains($login2) | Should -Be $true + $roleAfter.EnumMemberNames() | Should -Contain $login2 } } } diff --git a/tests/Backup-DbaComputerCertificate.Tests.ps1 b/tests/Backup-DbaComputerCertificate.Tests.ps1 index a1064dccfe..9b49077d08 100644 --- a/tests/Backup-DbaComputerCertificate.Tests.ps1 +++ b/tests/Backup-DbaComputerCertificate.Tests.ps1 @@ -1,25 +1,50 @@ -$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", + $PSDefaultParameterValues = ($TestConfig = Get-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 = 'SecurePassword', 'InputObject', 'Path', 'FilePath', 'Type', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 +Describe "Backup-DbaComputerCertificate" -Tag "UnitTests" { + Context "Parameter validation" { + BeforeAll { + $command = Get-Command Backup-DbaComputerCertificate + $expected = $TestConfig.CommonParameters + $expected += @( + "SecurePassword", + "InputObject", + "Path", + "FilePath", + "Type", + "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 } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { - Context "Certificate is added properly" { - $null = Add-DbaComputerCertificate -Path "$($TestConfig.appveyorlabrepo)\certificates\localhost.crt" -Confirm:$false - It "returns the proper results" { - $result = Get-DbaComputerCertificate -Thumbprint 29C469578D6C6211076A09CEE5C5797EEA0C2713 | Backup-DbaComputerCertificate -Path C:\temp - $result.Name -match '29C469578D6C6211076A09CEE5C5797EEA0C2713.cer' +Describe "Backup-DbaComputerCertificate" -Tag "IntegrationTests" { + Context "Certificate is added and backed up properly" { + BeforeAll { + $null = Add-DbaComputerCertificate -Path "$($TestConfig.appveyorlabrepo)\certificates\localhost.crt" -Confirm:$false + $certThumbprint = "29C469578D6C6211076A09CEE5C5797EEA0C2713" + $backupPath = "C:\temp" + } + + It "Returns the proper results" { + $result = Get-DbaComputerCertificate -Thumbprint $certThumbprint | Backup-DbaComputerCertificate -Path $backupPath + $result.Name | Should -Match "$certThumbprint.cer" + } + + AfterAll { + $null = Remove-DbaComputerCertificate -Thumbprint $certThumbprint -Confirm:$false } - $null = Remove-DbaComputerCertificate -Thumbprint 29C469578D6C6211076A09CEE5C5797EEA0C2713 -Confirm:$false } } diff --git a/tests/Backup-DbaDbCertificate.Tests.ps1 b/tests/Backup-DbaDbCertificate.Tests.ps1 index d6d04b86db..3957909fdd 100644 --- a/tests/Backup-DbaDbCertificate.Tests.ps1 +++ b/tests/Backup-DbaDbCertificate.Tests.ps1 @@ -1,19 +1,43 @@ -$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", + $PSDefaultParameterValues = ($TestConfig = Get-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', 'Certificate', 'Database', 'ExcludeDatabase', 'EncryptionPassword', 'DecryptionPassword', 'Path', 'Suffix', 'InputObject', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 +Describe "Backup-DbaDbCertificate" -Tag "UnitTests" { + Context "Parameter validation" { + BeforeAll { + $command = Get-Command Backup-DbaDbCertificate + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "Certificate", + "Database", + "ExcludeDatabase", + "EncryptionPassword", + "DecryptionPassword", + "Path", + "Suffix", + "InputObject", + "EnableException", + "Confirm", + "WhatIf" + ) + } + + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tag "IntegrationTests" { +Describe "Backup-DbaDbCertificate" -Tag "IntegrationTests" { BeforeAll { $random = Get-Random $db1Name = "dbatoolscli_$random" @@ -31,12 +55,11 @@ Describe "$commandname Integration Tests" -Tag "IntegrationTests" { } Context "Can create and backup a database certificate" { - It "backs up the db cert" { $results = Backup-DbaDbCertificate -SqlInstance $TestConfig.instance1 -Certificate $cert.Name -Database $db1Name -EncryptionPassword $pw -DecryptionPassword $pw $null = Get-ChildItem -Path $results.Path -ErrorAction Ignore | Remove-Item -Confirm:$false -ErrorAction Ignore $results.Certificate | Should -Be $cert.Name - $results.Status -match "Success" + $results.Status | Should -Match "Success" $results.DatabaseID | Should -Be (Get-DbaDatabase -SqlInstance $TestConfig.instance1 -Database $db1Name).ID } @@ -45,23 +68,19 @@ Describe "$commandname Integration Tests" -Tag "IntegrationTests" { $invalidDBCertName2 = "dbatoolscli_invalidCertName2" $results = Backup-DbaDbCertificate -SqlInstance $TestConfig.instance1 -Certificate $invalidDBCertName, $invalidDBCertName2, $cert2.Name -Database $db1Name -EncryptionPassword $pw -DecryptionPassword $pw -WarningVariable warnVariable 3> $null $null = Get-ChildItem -Path $results.Path -ErrorAction Ignore | Remove-Item -Confirm:$false -ErrorAction Ignore - #$results.Certificate | Should -Be $cert2.Name $warnVariable | Should -BeLike "*Database certificate(s) * not found*" } - # works locally, gah - It -Skip "backs up all db certs for a database" { + It "backs up all db certs for a database" -Skip { $results = Backup-DbaDbCertificate -SqlInstance $TestConfig.instance1 -Database $db1Name -EncryptionPassword $pw -DecryptionPassword $pw $null = Get-ChildItem -Path $results.Path -ErrorAction Ignore | Remove-Item -Confirm:$false -ErrorAction Ignore $results.length | Should -Be 2 $results.Certificate | Should -Be $cert.Name, $cert2.Name } - # Skip this test as there's a mix of certs, some require a password and some don't and i'll fix later - It -Skip "backs up all db certs for an instance" { + It "backs up all db certs for an instance" -Skip { $results = Backup-DbaDbCertificate -SqlInstance $TestConfig.instance1 -EncryptionPassword $pw $null = Get-ChildItem -Path $results.Path -ErrorAction Ignore | Remove-Item -Confirm:$false -ErrorAction Ignore - # $results.length | Should -BeGreaterOrEqual 2 } } } diff --git a/tests/Backup-DbaDbMasterKey.Tests.ps1 b/tests/Backup-DbaDbMasterKey.Tests.ps1 index 5c1a0366b6..28a23ddbb9 100644 --- a/tests/Backup-DbaDbMasterKey.Tests.ps1 +++ b/tests/Backup-DbaDbMasterKey.Tests.ps1 @@ -1,39 +1,71 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig - -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Credential', 'Database', 'ExcludeDatabase', 'SecurePassword', 'Path', 'InputObject', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + +Describe "Backup-DbaDbMasterKey" -Tag "UnitTests" { + Context "Parameter validation" { + BeforeAll { + $command = Get-Command Backup-DbaDbMasterKey + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "Credential", + "Database", + "ExcludeDatabase", + "SecurePassword", + "Path", + "InputObject", + "EnableException", + "WhatIf", + "Confirm" + ) + } + + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { - Context "Can create a database certificate" { +Describe "Backup-DbaDbMasterKey" -Tag "IntegrationTests" { + Context "Can backup a database master key" { BeforeAll { - if (-not (Get-DbaDbMasterKey -SqlInstance $TestConfig.instance1 -Database tempdb)) { - $masterkey = New-DbaDbMasterKey -SqlInstance $TestConfig.instance1 -Database tempdb -Password $(ConvertTo-SecureString -String "GoodPass1234!" -AsPlainText -Force) -Confirm:$false + $instance = $TestConfig.instance1 + $database = "tempdb" + $password = ConvertTo-SecureString -String "GoodPass1234!" -AsPlainText -Force + + if (-not (Get-DbaDbMasterKey -SqlInstance $instance -Database $database)) { + $null = New-DbaDbMasterKey -SqlInstance $instance -Database $database -Password $password -Confirm:$false + } + + $splatBackup = @{ + SqlInstance = $instance + Database = $database + SecurePassword = $password + Confirm = $false } } + AfterAll { - (Get-DbaDbMasterKey -SqlInstance $TestConfig.instance1 -Database tempdb) | Remove-DbaDbMasterKey -Confirm:$false + Get-DbaDbMasterKey -SqlInstance $instance -Database $database | Remove-DbaDbMasterKey -Confirm:$false } - $results = Backup-DbaDbMasterKey -SqlInstance $TestConfig.instance1 -Confirm:$false -Database tempdb -Password $(ConvertTo-SecureString -String "GoodPass1234!" -AsPlainText -Force) - $null = Remove-Item -Path $results.Path -ErrorAction SilentlyContinue -Confirm:$false - - It "backs up the db cert" { - $results.Database -eq 'tempdb' - $results.Status -eq "Success" - } + It "Backs up the database master key" { + $results = Backup-DbaDbMasterKey @splatBackup + $results | Should -Not -BeNullOrEmpty + $results.Database | Should -Be $database + $results.Status | Should -Be "Success" + $results.DatabaseID | Should -Be (Get-DbaDatabase -SqlInstance $instance -Database $database).ID - It "Database ID should be returned" { - $results.DatabaseID | Should -Be (Get-DbaDatabase -SqlInstance $TestConfig.instance1 -Database tempdb).ID + $null = Remove-Item -Path $results.Path -ErrorAction SilentlyContinue -Confirm:$false } } } diff --git a/tests/Backup-DbaServiceMasterKey.Tests.ps1 b/tests/Backup-DbaServiceMasterKey.Tests.ps1 index c04b886400..c81c81b578 100644 --- a/tests/Backup-DbaServiceMasterKey.Tests.ps1 +++ b/tests/Backup-DbaServiceMasterKey.Tests.ps1 @@ -1,25 +1,50 @@ -$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", + $PSDefaultParameterValues = ($TestConfig = Get-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', 'KeyCredential', 'SecurePassword', 'Path', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 +Describe "Backup-DbaServiceMasterKey" -Tag "UnitTests" { + Context "Parameter validation" { + BeforeAll { + $command = Get-Command Backup-DbaServiceMasterKey + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "KeyCredential", + "SecurePassword", + "Path", + "EnableException", + "Confirm", + "WhatIf" + ) + } + + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { +Describe "Backup-DbaServiceMasterKey" -Tag "IntegrationTests" { Context "Can backup a service master key" { - $results = Backup-DbaServiceMasterKey -SqlInstance $TestConfig.instance1 -Confirm:$false -Password $(ConvertTo-SecureString -String "GoodPass1234!" -AsPlainText -Force) - $null = Remove-Item -Path $results.Path -ErrorAction SilentlyContinue -Confirm:$false + BeforeAll { + $securePassword = ConvertTo-SecureString -String "GoodPass1234!" -AsPlainText -Force + $results = Backup-DbaServiceMasterKey -SqlInstance $TestConfig.instance1 -SecurePassword $securePassword -Confirm:$false + } + + AfterAll { + $null = Remove-Item -Path $results.Path -ErrorAction SilentlyContinue -Confirm:$false + } It "backs up the SMK" { - $results.Status -eq "Success" + $results.Status | Should -Be "Success" } } } diff --git a/tests/Clear-DbaConnectionPool.Tests.ps1 b/tests/Clear-DbaConnectionPool.Tests.ps1 index 53bb663354..cd92862fd7 100644 --- a/tests/Clear-DbaConnectionPool.Tests.ps1 +++ b/tests/Clear-DbaConnectionPool.Tests.ps1 @@ -1,20 +1,36 @@ -$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", + $PSDefaultParameterValues = ($TestConfig = Get-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 = 'ComputerName', 'Credential', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe "Clear-DbaConnectionPool" -Tag "UnitTests" { + Context "Parameter validation" { + BeforeAll { + $command = Get-Command Clear-DbaConnectionPool + $expected = $TestConfig.CommonParameters + $expected += @( + "ComputerName", + "Credential", + "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 } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { - It "doesn't throw" { - { Clear-DbaConnectionPool } | Should Not Throw +Describe "Clear-DbaConnectionPool" -Tag "IntegrationTests" { + Context "When clearing connection pool" { + It "Doesn't throw" { + { Clear-DbaConnectionPool } | Should -Not -Throw + } } -} \ No newline at end of file +} diff --git a/tests/Clear-DbaLatchStatistics.Tests.ps1 b/tests/Clear-DbaLatchStatistics.Tests.ps1 index 634451dfff..77d72e213c 100644 --- a/tests/Clear-DbaLatchStatistics.Tests.ps1 +++ b/tests/Clear-DbaLatchStatistics.Tests.ps1 @@ -1,24 +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", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) -Describe "$CommandName Unit Tests" -Tags "UnitTests" { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe "Clear-DbaLatchStatistics" -Tag "UnitTests" { + Context "Parameter validation" { + BeforeAll { + $command = Get-Command Clear-DbaLatchStatistics + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "EnableException", + "Confirm", + "WhatIf" + ) + } + + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { +Describe "Clear-DbaLatchStatistics" -Tag "IntegrationTests" { Context "Command executes properly and returns proper info" { - $results = Clear-DbaLatchStatistics -SqlInstance $TestConfig.instance1 -Confirm:$false + BeforeAll { + $splatClearLatch = @{ + SqlInstance = $TestConfig.instance1 + Confirm = $false + } + $results = Clear-DbaLatchStatistics @splatClearLatch + } - It "returns success" { - $results.Status -eq 'Success' | Should Be $true + It "Returns success" { + $results.Status | Should -Be 'Success' } } } diff --git a/tests/Clear-DbaPlanCache.Tests.ps1 b/tests/Clear-DbaPlanCache.Tests.ps1 index c33d5476d3..de7e1ef729 100644 --- a/tests/Clear-DbaPlanCache.Tests.ps1 +++ b/tests/Clear-DbaPlanCache.Tests.ps1 @@ -1,31 +1,53 @@ -$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", + $PSDefaultParameterValues = ($TestConfig = Get-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', 'Threshold', 'InputObject', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe "Clear-DbaPlanCache" -Tag "UnitTests" { + Context "Parameter validation" { + BeforeAll { + $command = Get-Command Clear-DbaPlanCache + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "Threshold", + "InputObject", + "EnableException", + "Confirm", + "WhatIf" + ) + } + + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tag "IntegrationTests" { - Context "doesn't clear plan cache" { - It "returns correct datatypes" { +Describe "Clear-DbaPlanCache" -Tag "IntegrationTests" { + Context "When not clearing plan cache" { + BeforeAll { # Make plan cache way higher than likely for a test rig - $results = Clear-DbaPlanCache -SqlInstance $TestConfig.instance1 -Threshold 10240 - $results.Size -is [dbasize] | Should -Be $true - $results.Status -match 'below' | Should -Be $true + $threshold = 10240 } - It "supports piping" { - # Make plan cache way higher than likely for a test rig - $results = Get-DbaPlanCache -SqlInstance $TestConfig.instance1 | Clear-DbaPlanCache -Threshold 10240 - $results.Size -is [dbasize] | Should -Be $true - $results.Status -match 'below' | Should -Be $true + + It "Returns correct datatypes" { + $results = Clear-DbaPlanCache -SqlInstance $TestConfig.instance1 -Threshold $threshold + $results.Size | Should -BeOfType [dbasize] + $results.Status | Should -Match 'below' + } + + It "Supports piping" { + $results = Get-DbaPlanCache -SqlInstance $TestConfig.instance1 | Clear-DbaPlanCache -Threshold $threshold + $results.Size | Should -BeOfType [dbasize] + $results.Status | Should -Match 'below' } } } diff --git a/tests/Clear-DbaWaitStatistics.Tests.ps1 b/tests/Clear-DbaWaitStatistics.Tests.ps1 index 120ce455e6..4014ee4a8e 100644 --- a/tests/Clear-DbaWaitStatistics.Tests.ps1 +++ b/tests/Clear-DbaWaitStatistics.Tests.ps1 @@ -1,24 +1,42 @@ -$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", + $PSDefaultParameterValues = ($TestConfig = Get-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', '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 "Clear-DbaWaitStatistics" -Tag "UnitTests" { + Context "Parameter validation" { + BeforeAll { + $command = Get-Command Clear-DbaWaitStatistics + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "EnableException", + "Confirm", + "WhatIf" + ) + } + + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { +Describe "Clear-DbaWaitStatistics" -Tag "IntegrationTests" { Context "Command executes properly and returns proper info" { - $results = Clear-DbaWaitStatistics -SqlInstance $TestConfig.instance1 -Confirm:$false + BeforeAll { + $results = Clear-DbaWaitStatistics -SqlInstance $TestConfig.instance1 -Confirm:$false + } - It "returns success" { - $results.Status -eq 'Success' | Should Be $true + It "Returns success" { + $results.Status | Should -Be 'Success' } } } diff --git a/tests/Convert-DbaLsn.Tests.ps1 b/tests/Convert-DbaLsn.Tests.ps1 index 226c2bfc87..65108cbf28 100644 --- a/tests/Convert-DbaLsn.Tests.ps1 +++ b/tests/Convert-DbaLsn.Tests.ps1 @@ -1,46 +1,66 @@ -$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" { - $paramCount = 2 - $defaultParamCount = 11 - [object[]]$params = (Get-ChildItem function:\Convert-DbaLSN).Parameters.Keys - $knownParameters = 'LSN', 'EnableException' - It "Should contain our specific parameters" { - ( (Compare-Object -ReferenceObject $knownParameters -DifferenceObject $params -IncludeEqual | Where-Object SideIndicator -eq "==").Count ) | Should Be $paramCount - } - It "Should only contain $paramCount parameters" { - $params.Count - $defaultParamCount | Should Be $paramCount +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + +Describe "Convert-DbaLSN" -Tag "UnitTests" { + Context "Parameter validation" { + BeforeAll { + $command = Get-Command Convert-DbaLSN + $expected = $TestConfig.CommonParameters + $expected += @( + "LSN", + "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 } } Context "Converts Numeric LSN to Hex" { - $LSN = '00000000020000000024300001' + BeforeAll { + $LSN = '00000000020000000024300001' + $result = Convert-DbaLSN -Lsn $LSN + } + It "Should convert to 00000014:000000f3:0001" { - (Convert-DbaLSN -Lsn $Lsn).Hexadecimal | Should -Be '00000014:000000f3:0001' + $result.Hexadecimal | Should -Be '00000014:000000f3:0001' } } Context "Converts Numeric LSN to Hex without leading 0s" { - $LSN = '20000000024300001' + BeforeAll { + $LSN = '20000000024300001' + $result = Convert-DbaLSN -Lsn $LSN + } + It "Should convert to 00000014:000000f3:0001" { - (Convert-DbaLSN -Lsn $Lsn).Hexadecimal | Should -Be '00000014:000000f3:0001' + $result.Hexadecimal | Should -Be '00000014:000000f3:0001' } } Context "Converts Hex LSN to Numeric" { - $LSN = '00000014:000000f3:0001' + BeforeAll { + $LSN = '00000014:000000f3:0001' + $result = Convert-DbaLSN -Lsn $LSN + } + It "Should convert to 20000000024300001" { - (Convert-DbaLSN -Lsn $Lsn).Numeric | Should -Be 20000000024300001 + $result.Numeric | Should -Be 20000000024300001 } } - - } + <# Integration test should appear below and are custom to the command you are writing. Read https://github.com/dataplat/dbatools/blob/development/contributing.md#tests - for more guidence. -#> \ No newline at end of file + for more guidance. +#> diff --git a/tests/Convert-DbaMaskingValue.Tests.ps1 b/tests/Convert-DbaMaskingValue.Tests.ps1 index bed662ab4a..f21519aed2 100644 --- a/tests/Convert-DbaMaskingValue.Tests.ps1 +++ b/tests/Convert-DbaMaskingValue.Tests.ps1 @@ -1,21 +1,34 @@ -$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", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + +Describe "Convert-DbaMaskingValue" -Tag "UnitTests" { + Context "Parameter validation" { + BeforeAll { + $command = Get-Command Convert-DbaMaskingValue + $expected = $TestConfig.CommonParameters + $expected += @( + "Value", + "DataType", + "Nullable", + "EnableException" + ) + } -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'Value', 'DataType', 'Nullable', 'EnableException' + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } - $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 + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { - +Describe "Convert-DbaMaskingValue" -Tag "IntegrationTests" { Context "Null values" { It "Should return a single 'NULL' value" { $value = $null @@ -25,38 +38,38 @@ Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { It "Should return multiple 'NULL' values" { $value = @($null, $null) - [array]$convertedValues = Convert-DbaMaskingValue -Value $value -Nullable:$true + $convertedValues = Convert-DbaMaskingValue -Value $value -Nullable:$true $convertedValues[0].NewValue | Should -Be 'NULL' $convertedValues[1].NewValue | Should -Be 'NULL' } } Context "Text data types" { - It "Should return a text value" { + It "Should return a text value for char data type" { $value = "this is just text" $convertedValue = Convert-DbaMaskingValue -Value $value -DataType char $convertedValue.NewValue | Should -Be "'this is just text'" } - It "Should return a text value" { + It "Should return a text value for nchar data type" { $value = "this is just text" $convertedValue = Convert-DbaMaskingValue -Value $value -DataType nchar $convertedValue.NewValue | Should -Be "'this is just text'" } - It "Should return a text value" { + It "Should return a text value for nvarchar data type" { $value = "this is just text" $convertedValue = Convert-DbaMaskingValue -Value $value -DataType nvarchar $convertedValue.NewValue | Should -Be "'this is just text'" } - It "Should return a text value" { + It "Should return a text value for varchar data type" { $value = "this is just text" $convertedValue = Convert-DbaMaskingValue -Value $value -DataType varchar $convertedValue.NewValue | Should -Be "'this is just text'" } - It "Should return a text value" { + It "Should return a text value for numeric string" { $value = "2.13" $convertedValue = Convert-DbaMaskingValue -Value $value -DataType varchar $convertedValue.NewValue | Should -Be "'2.13'" @@ -70,41 +83,41 @@ Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { } Context "Date and time data types" { - It "Should return a text value" { + It "Should return a date value" { $value = "2020-10-05 10:10:10.1234567" $convertedValue = Convert-DbaMaskingValue -Value $value -DataType date $convertedValue.NewValue | Should -Be "'2020-10-05'" } - It "Should return a text value" { + It "Should return a time value" { $value = "2020-10-05 10:10:10.1234567" $convertedValue = Convert-DbaMaskingValue -Value $value -DataType time $convertedValue.NewValue | Should -Be "'10:10:10.1234567'" } - It "Should return a text value" { + It "Should return a datetime value" { $value = "2020-10-05 10:10:10.1234567" $convertedValue = Convert-DbaMaskingValue -Value $value -DataType datetime $convertedValue.NewValue | Should -Be "'2020-10-05 10:10:10.123'" - } #> + } } Context "Handling multiple values" { - It "It should return a NULL value and text value" { + It "Should return a NULL value and text value" { $value = @($null, "this is just text") - [array]$convertedValues = Convert-DbaMaskingValue -Value $value -Nullable:$true + $convertedValues = Convert-DbaMaskingValue -Value $value -Nullable:$true $convertedValues[0].NewValue | Should -Be 'NULL' $convertedValues[1].NewValue | Should -Be "'this is just text'" } } Context "Error handling" { - It "It should return the value missing error" { + It "Should throw an error when value is missing" { { Convert-DbaMaskingValue -Value $null -DataType datetime -EnableException } | Should -Throw "Please enter a value" } - It "It should return the data type missing error" { + + It "Should throw an error when data type is missing" { { Convert-DbaMaskingValue -Value "whatever" -EnableException } | Should -Throw "Please enter a data type" } } - -} \ No newline at end of file +} diff --git a/tests/ConvertTo-DbaTimeline.Tests.ps1 b/tests/ConvertTo-DbaTimeline.Tests.ps1 index cf7f8d4f87..b2feda3395 100644 --- a/tests/ConvertTo-DbaTimeline.Tests.ps1 +++ b/tests/ConvertTo-DbaTimeline.Tests.ps1 @@ -1,19 +1,34 @@ -$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", + $PSDefaultParameterValues = ($TestConfig = Get-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 = 'InputObject', 'ExcludeRowLabel', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe "ConvertTo-DbaTimeline" -Tag "UnitTests" { + Context "Parameter validation" { + BeforeAll { + $command = Get-Command ConvertTo-DbaTimeline + $expected = $TestConfig.CommonParameters + $expected += @( + "InputObject", + "ExcludeRowLabel", + "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 } } } + <# Integration test should appear below and are custom to the command you are writing. Read https://github.com/dataplat/dbatools/blob/development/contributing.md#tests - for more guidence. -#> \ No newline at end of file + for more guidance. +#> diff --git a/tests/ConvertTo-DbaXESession.Tests.ps1 b/tests/ConvertTo-DbaXESession.Tests.ps1 index c675a40aa0..29227043b2 100644 --- a/tests/ConvertTo-DbaXESession.Tests.ps1 +++ b/tests/ConvertTo-DbaXESession.Tests.ps1 @@ -1,112 +1,138 @@ -$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", + $PSDefaultParameterValues = ($TestConfig = Get-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 = 'InputObject', 'Name', 'OutputScriptOnly', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe "ConvertTo-DbaXESession" -Tag "UnitTests" { + Context "Parameter validation" { + BeforeAll { + $command = Get-Command ConvertTo-DbaXESession + $expected = $TestConfig.CommonParameters + $expected += @( + "InputObject", + "Name", + "OutputScriptOnly", + "EnableException", + "Confirm", + "WhatIf" + ) + } + + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { +Describe "ConvertTo-DbaXESession" -Tag "IntegrationTests" { BeforeAll { - $sql = "-- Create a Queue - declare @rc int - declare @TraceID int - declare @maxfilesize bigint - set @maxfilesize = 5 - exec @rc = sp_trace_create @TraceID output, 0, N'C:\windows\temp\temptrace', @maxfilesize, NULL + $sql = @" +-- Create a Queue +declare @rc int +declare @TraceID int +declare @maxfilesize bigint +set @maxfilesize = 5 +exec @rc = sp_trace_create @TraceID output, 0, N'C:\windows\temp\temptrace', @maxfilesize, NULL - -- Set the events - declare @on bit - set @on = 1 - exec sp_trace_setevent @TraceID, 14, 1, @on - exec sp_trace_setevent @TraceID, 14, 9, @on - exec sp_trace_setevent @TraceID, 14, 10, @on - exec sp_trace_setevent @TraceID, 14, 11, @on - exec sp_trace_setevent @TraceID, 14, 6, @on - exec sp_trace_setevent @TraceID, 14, 12, @on - exec sp_trace_setevent @TraceID, 14, 14, @on - exec sp_trace_setevent @TraceID, 15, 11, @on - exec sp_trace_setevent @TraceID, 15, 6, @on - exec sp_trace_setevent @TraceID, 15, 9, @on - exec sp_trace_setevent @TraceID, 15, 10, @on - exec sp_trace_setevent @TraceID, 15, 12, @on - exec sp_trace_setevent @TraceID, 15, 13, @on - exec sp_trace_setevent @TraceID, 15, 14, @on - exec sp_trace_setevent @TraceID, 15, 15, @on - exec sp_trace_setevent @TraceID, 15, 16, @on - exec sp_trace_setevent @TraceID, 15, 17, @on - exec sp_trace_setevent @TraceID, 15, 18, @on - exec sp_trace_setevent @TraceID, 17, 1, @on - exec sp_trace_setevent @TraceID, 17, 9, @on - exec sp_trace_setevent @TraceID, 17, 10, @on - exec sp_trace_setevent @TraceID, 17, 11, @on - exec sp_trace_setevent @TraceID, 17, 6, @on - exec sp_trace_setevent @TraceID, 17, 12, @on - exec sp_trace_setevent @TraceID, 17, 14, @on - exec sp_trace_setevent @TraceID, 10, 9, @on - exec sp_trace_setevent @TraceID, 10, 2, @on - exec sp_trace_setevent @TraceID, 10, 10, @on - exec sp_trace_setevent @TraceID, 10, 6, @on - exec sp_trace_setevent @TraceID, 10, 11, @on - exec sp_trace_setevent @TraceID, 10, 12, @on - exec sp_trace_setevent @TraceID, 10, 13, @on - exec sp_trace_setevent @TraceID, 10, 14, @on - exec sp_trace_setevent @TraceID, 10, 15, @on - exec sp_trace_setevent @TraceID, 10, 16, @on - exec sp_trace_setevent @TraceID, 10, 17, @on - exec sp_trace_setevent @TraceID, 10, 18, @on - exec sp_trace_setevent @TraceID, 12, 1, @on - exec sp_trace_setevent @TraceID, 12, 9, @on - exec sp_trace_setevent @TraceID, 12, 11, @on - exec sp_trace_setevent @TraceID, 12, 6, @on - exec sp_trace_setevent @TraceID, 12, 10, @on - exec sp_trace_setevent @TraceID, 12, 12, @on - exec sp_trace_setevent @TraceID, 12, 13, @on - exec sp_trace_setevent @TraceID, 12, 14, @on - exec sp_trace_setevent @TraceID, 12, 15, @on - exec sp_trace_setevent @TraceID, 12, 16, @on - exec sp_trace_setevent @TraceID, 12, 17, @on - exec sp_trace_setevent @TraceID, 12, 18, @on - exec sp_trace_setevent @TraceID, 13, 1, @on - exec sp_trace_setevent @TraceID, 13, 9, @on - exec sp_trace_setevent @TraceID, 13, 11, @on - exec sp_trace_setevent @TraceID, 13, 6, @on - exec sp_trace_setevent @TraceID, 13, 10, @on - exec sp_trace_setevent @TraceID, 13, 12, @on - exec sp_trace_setevent @TraceID, 13, 14, @on +-- Set the events +declare @on bit +set @on = 1 +exec sp_trace_setevent @TraceID, 14, 1, @on +exec sp_trace_setevent @TraceID, 14, 9, @on +exec sp_trace_setevent @TraceID, 14, 10, @on +exec sp_trace_setevent @TraceID, 14, 11, @on +exec sp_trace_setevent @TraceID, 14, 6, @on +exec sp_trace_setevent @TraceID, 14, 12, @on +exec sp_trace_setevent @TraceID, 14, 14, @on +exec sp_trace_setevent @TraceID, 15, 11, @on +exec sp_trace_setevent @TraceID, 15, 6, @on +exec sp_trace_setevent @TraceID, 15, 9, @on +exec sp_trace_setevent @TraceID, 15, 10, @on +exec sp_trace_setevent @TraceID, 15, 12, @on +exec sp_trace_setevent @TraceID, 15, 13, @on +exec sp_trace_setevent @TraceID, 15, 14, @on +exec sp_trace_setevent @TraceID, 15, 15, @on +exec sp_trace_setevent @TraceID, 15, 16, @on +exec sp_trace_setevent @TraceID, 15, 17, @on +exec sp_trace_setevent @TraceID, 15, 18, @on +exec sp_trace_setevent @TraceID, 17, 1, @on +exec sp_trace_setevent @TraceID, 17, 9, @on +exec sp_trace_setevent @TraceID, 17, 10, @on +exec sp_trace_setevent @TraceID, 17, 11, @on +exec sp_trace_setevent @TraceID, 17, 6, @on +exec sp_trace_setevent @TraceID, 17, 12, @on +exec sp_trace_setevent @TraceID, 17, 14, @on +exec sp_trace_setevent @TraceID, 10, 9, @on +exec sp_trace_setevent @TraceID, 10, 2, @on +exec sp_trace_setevent @TraceID, 10, 10, @on +exec sp_trace_setevent @TraceID, 10, 6, @on +exec sp_trace_setevent @TraceID, 10, 11, @on +exec sp_trace_setevent @TraceID, 10, 12, @on +exec sp_trace_setevent @TraceID, 10, 13, @on +exec sp_trace_setevent @TraceID, 10, 14, @on +exec sp_trace_setevent @TraceID, 10, 15, @on +exec sp_trace_setevent @TraceID, 10, 16, @on +exec sp_trace_setevent @TraceID, 10, 17, @on +exec sp_trace_setevent @TraceID, 10, 18, @on +exec sp_trace_setevent @TraceID, 12, 1, @on +exec sp_trace_setevent @TraceID, 12, 9, @on +exec sp_trace_setevent @TraceID, 12, 11, @on +exec sp_trace_setevent @TraceID, 12, 6, @on +exec sp_trace_setevent @TraceID, 12, 10, @on +exec sp_trace_setevent @TraceID, 12, 12, @on +exec sp_trace_setevent @TraceID, 12, 13, @on +exec sp_trace_setevent @TraceID, 12, 14, @on +exec sp_trace_setevent @TraceID, 12, 15, @on +exec sp_trace_setevent @TraceID, 12, 16, @on +exec sp_trace_setevent @TraceID, 12, 17, @on +exec sp_trace_setevent @TraceID, 12, 18, @on +exec sp_trace_setevent @TraceID, 13, 1, @on +exec sp_trace_setevent @TraceID, 13, 9, @on +exec sp_trace_setevent @TraceID, 13, 11, @on +exec sp_trace_setevent @TraceID, 13, 6, @on +exec sp_trace_setevent @TraceID, 13, 10, @on +exec sp_trace_setevent @TraceID, 13, 12, @on +exec sp_trace_setevent @TraceID, 13, 14, @on - -- Set the Filters - declare @intfilter int - declare @bigintfilter bigint +-- Set the Filters +declare @intfilter int +declare @bigintfilter bigint - exec sp_trace_setfilter @TraceID, 10, 0, 7, N'SQL Server Profiler - 934a8575-0dc1-4937-bde1-edac1cb9691f' - -- Set the trace status to start - exec sp_trace_setstatus @TraceID, 1 +exec sp_trace_setfilter @TraceID, 10, 0, 7, N'SQL Server Profiler - 934a8575-0dc1-4937-bde1-edac1cb9691f' +-- Set the trace status to start +exec sp_trace_setstatus @TraceID, 1 - -- display trace id for future references - select TraceID=@TraceID" +-- display trace id for future references +select TraceID=@TraceID +"@ $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 $traceid = ($server.Query($sql)).TraceID $TestConfig.name = "dbatoolsci-session" } + AfterAll { $null = Remove-DbaXESession -SqlInstance $TestConfig.instance2 -Session $TestConfig.name $null = Remove-DbaTrace -SqlInstance $TestConfig.instance2 -Id $traceid Remove-Item C:\windows\temp\temptrace.trc -ErrorAction SilentlyContinue } + Context "Test Trace Conversion" { - $results = Get-DbaTrace -SqlInstance $TestConfig.instance2 -Id $traceid | ConvertTo-DbaXESession -Name $TestConfig.name | Start-DbaXESession - It "returns the right results" { - $results.Name | Should Be $TestConfig.name - $results.Status | Should Be "Running" - $results.Targets.Name | Should Be "package0.event_file" + BeforeAll { + $results = Get-DbaTrace -SqlInstance $TestConfig.instance2 -Id $traceid | + ConvertTo-DbaXESession -Name $TestConfig.name | + Start-DbaXESession + } + + It "Returns the right results" { + $results.Name | Should -Be $TestConfig.name + $results.Status | Should -Be "Running" + $results.Targets.Name | Should -Be "package0.event_file" } } } diff --git a/tests/Copy-DbaAgentAlert.Tests.ps1 b/tests/Copy-DbaAgentAlert.Tests.ps1 index e40e27fe13..075cfffb58 100644 --- a/tests/Copy-DbaAgentAlert.Tests.ps1 +++ b/tests/Copy-DbaAgentAlert.Tests.ps1 @@ -1,19 +1,41 @@ -$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", + $PSDefaultParameterValues = ($TestConfig = Get-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 = 'Source', 'SourceSqlCredential', 'Destination', 'DestinationSqlCredential', 'Alert', 'ExcludeAlert', 'IncludeDefaults', 'Force', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe "Copy-DbaAgentAlert" -Tag "UnitTests" { + Context "Parameter validation" { + BeforeAll { + $command = Get-Command Copy-DbaAgentAlert + $expected = $TestConfig.CommonParameters + $expected += @( + "Source", + "SourceSqlCredential", + "Destination", + "DestinationSqlCredential", + "Alert", + "ExcludeAlert", + "IncludeDefaults", + "Force", + "EnableException", + "Confirm", + "WhatIf" + ) + } + + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tag "IntegrationTests" { +Describe "Copy-DbaAgentAlert" -Tag "IntegrationTests" { BeforeAll { $alert1 = 'dbatoolsci test alert' $alert2 = 'dbatoolsci test alert 2' @@ -46,6 +68,7 @@ Describe "$commandname Integration Tests" -Tag "IntegrationTests" { @operator_name = N'$operatorName', @notification_method = 1 ;") } + AfterAll { $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 -Database master $server.Query("EXEC msdb.dbo.sp_delete_alert @name=N'$($alert1)'") @@ -56,25 +79,45 @@ Describe "$commandname Integration Tests" -Tag "IntegrationTests" { $server.Query("EXEC msdb.dbo.sp_delete_alert @name=N'$($alert1)'") } - It "Copies the sample alert" { - $results = Copy-DbaAgentAlert -Source $TestConfig.instance2 -Destination $TestConfig.instance3 -Alert $alert1 - $results.Name -eq 'dbatoolsci test alert', 'dbatoolsci test alert' - $results.Status -eq 'Successful', 'Successful' - } + Context "When copying alerts" { + It "Copies the sample alert" { + $splat = @{ + Source = $TestConfig.instance2 + Destination = $TestConfig.instance3 + Alert = $alert1 + } + $results = Copy-DbaAgentAlert @splat + $results.Name | Should -Be 'dbatoolsci test alert', 'dbatoolsci test alert' + $results.Type | Should -Be 'Agent Alert', 'Agent Alert Notification' + $results.Status | Should -Be 'Successful', 'Successful' + } - It "Skips alerts where destination is missing the operator" { - $results = Copy-DbaAgentAlert -Source $TestConfig.instance2 -Destination $TestConfig.instance3 -Alert $alert2 -WarningAction SilentlyContinue - $results.Status -eq 'Skipped', 'Skipped' - } + It "Skips alerts where destination is missing the operator" { + $splatDupe = @{ + Source = $TestConfig.instance2 + Destination = $TestConfig.instance3 + Alert = $alert2 + WarningAction = 'SilentlyContinue' + } + $results = Copy-DbaAgentAlert @splatDupe + $results.Status | Should -Be Skipped + $results.Type | Should -Be 'Agent Alert' + } - It "Doesn't overwrite existing alerts" { - $results = Copy-DbaAgentAlert -Source $TestConfig.instance2 -Destination $TestConfig.instance3 -Alert $alert1 - $results.Name -eq 'dbatoolsci test alert' - $results.Status -eq 'Skipped' - } + It "Doesn't overwrite existing alerts" { + $splat = @{ + Source = $TestConfig.instance2 + Destination = $TestConfig.instance3 + Alert = $alert1 + } + $results = Copy-DbaAgentAlert @splat + $results.Name | Should -Be 'dbatoolsci test alert' + $results.Status | Should -Be 'Skipped' + } - It "The newly copied alert exists" { - $results = Get-DbaAgentAlert -SqlInstance $TestConfig.instance2 - $results.Name -contains 'dbatoolsci test alert' + It "The newly copied alert exists" { + $results = Get-DbaAgentAlert -SqlInstance $TestConfig.instance2 + $results.Name | Should -Contain 'dbatoolsci test alert' + } } } diff --git a/tests/Copy-DbaAgentJob.Tests.ps1 b/tests/Copy-DbaAgentJob.Tests.ps1 index 81151184f7..9e466da013 100644 --- a/tests/Copy-DbaAgentJob.Tests.ps1 +++ b/tests/Copy-DbaAgentJob.Tests.ps1 @@ -1,19 +1,10 @@ -$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 = 'Source', 'SourceSqlCredential', 'Destination', 'DestinationSqlCredential', 'Job', 'ExcludeJob', 'DisableOnSource', 'DisableOnDestination', 'Force', 'EnableException', 'InputObject' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 - } - } -} +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) -Describe "$commandname Integration Tests" -Tag "IntegrationTests" { +Describe "Copy-DbaAgentJob" -Tag "IntegrationTests" { BeforeAll { $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_copyjob $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_copyjob_disabled @@ -25,8 +16,41 @@ Describe "$commandname Integration Tests" -Tag "IntegrationTests" { $null = Remove-DbaAgentJob -SqlInstance $TestConfig.instance3 -Job dbatoolsci_copyjob, dbatoolsci_copyjob_disabled -Confirm:$false } + Context "Parameter validation" { + BeforeAll { + $command = Get-Command Copy-DbaAgentJob + $expected = $TestConfig.CommonParameters + $expected += @( + "Source", + "SourceSqlCredential", + "Destination", + "DestinationSqlCredential", + "Job", + "ExcludeJob", + "DisableOnSource", + "DisableOnDestination", + "Force", + "InputObject", + "EnableException", + "Confirm", + "WhatIf" + ) + } + + 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 + } + } + Context "Command copies jobs properly" { - $results = Copy-DbaAgentJob -Source $TestConfig.instance2 -Destination $TestConfig.instance3 -Job dbatoolsci_copyjob + BeforeAll { + $results = Copy-DbaAgentJob -Source $TestConfig.instance2 -Destination $TestConfig.instance3 -Job dbatoolsci_copyjob + } It "returns one success" { $results.Name | Should -Be "dbatoolsci_copyjob" @@ -34,16 +58,24 @@ Describe "$commandname Integration Tests" -Tag "IntegrationTests" { } It "did not copy dbatoolsci_copyjob_disabled" { - Get-DbaAgentJob -SqlInstance $TestConfig.instance3 -Job dbatoolsci_copyjob_disabled | Should -Be $null + Get-DbaAgentJob -SqlInstance $TestConfig.instance3 -Job dbatoolsci_copyjob_disabled | Should -BeNullOrEmpty } It "disables jobs when requested" { - (Get-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_copyjob_disabled).Enabled - $results = Copy-DbaAgentJob -Source $TestConfig.instance2 -Destination $TestConfig.instance3 -Job dbatoolsci_copyjob_disabled -DisableOnSource -DisableOnDestination -Force + $splatCopyJob = @{ + Source = $TestConfig.instance2 + Destination = $TestConfig.instance3 + Job = "dbatoolsci_copyjob_disabled" + DisableOnSource = $true + DisableOnDestination = $true + Force = $true + } + $results = Copy-DbaAgentJob @splatCopyJob + $results.Name | Should -Be "dbatoolsci_copyjob_disabled" $results.Status | Should -Be "Successful" - (Get-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_copyjob_disabled).Enabled | Should -Be $false - (Get-DbaAgentJob -SqlInstance $TestConfig.instance3 -Job dbatoolsci_copyjob_disabled).Enabled | Should -Be $false + (Get-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_copyjob_disabled).Enabled | Should -BeFalse + (Get-DbaAgentJob -SqlInstance $TestConfig.instance3 -Job dbatoolsci_copyjob_disabled).Enabled | Should -BeFalse } } } diff --git a/tests/Copy-DbaAgentJobCategory.Tests.ps1 b/tests/Copy-DbaAgentJobCategory.Tests.ps1 index 943c31d943..79ef6ca357 100644 --- a/tests/Copy-DbaAgentJobCategory.Tests.ps1 +++ b/tests/Copy-DbaAgentJobCategory.Tests.ps1 @@ -1,19 +1,10 @@ -$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 = 'Source', 'SourceSqlCredential', 'Destination', 'DestinationSqlCredential', 'CategoryType', 'JobCategory', 'AgentCategory', 'OperatorCategory', 'Force', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 - } - } -} +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) -Describe "$commandname Integration Tests" -Tag "IntegrationTests" { +Describe "Copy-DbaAgentJobCategory" -Tag "IntegrationTests" { BeforeAll { $null = New-DbaAgentJobCategory -SqlInstance $TestConfig.instance2 -Category 'dbatoolsci test category' } @@ -21,17 +12,60 @@ Describe "$commandname Integration Tests" -Tag "IntegrationTests" { $null = Remove-DbaAgentJobCategory -SqlInstance $TestConfig.instance2 -Category 'dbatoolsci test category' -Confirm:$false } - Context "Command copies jobs properly" { - It "returns one success" { - $results = Copy-DbaAgentJobCategory -Source $TestConfig.instance2 -Destination $TestConfig.instance3 -JobCategory 'dbatoolsci test category' - $results.Name -eq "dbatoolsci test category" - $results.Status -eq "Successful" + Context "Parameter validation" { + BeforeAll { + $command = Get-Command Copy-DbaAgentJobCategory + + $expected = $TestConfig.CommonParameters + $expected += @( + "Source", + "SourceSqlCredential", + "Destination", + "DestinationSqlCredential", + "CategoryType", + "JobCategory", + "AgentCategory", + "OperatorCategory", + "Force", + "EnableException", + "Confirm", + "WhatIf" + ) } - It "does not overwrite" { - $results = Copy-DbaAgentJobCategory -Source $TestConfig.instance2 -Destination $TestConfig.instance3 -JobCategory 'dbatoolsci test category' - $results.Name -eq "dbatoolsci test category" - $results.Status -eq "Skipped" + 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 + } + } + + Context "When copying job categories" { + It "Returns successful results" { + $splat = @{ + Source = $TestConfig.instance2 + Destination = $TestConfig.instance3 + JobCategory = "dbatoolsci test category" + } + + $results = Copy-DbaAgentJobCategory @splat + $results.Name | Should -Be "dbatoolsci test category" + $results.Status | Should -Be "Successful" + } + + It "Does not overwrite existing categories" { + $splatSecondCopy = @{ + Source = $TestConfig.instance2 + Destination = $TestConfig.instance3 + JobCategory = "dbatoolsci test category" + } + + $secondCopyResults = Copy-DbaAgentJobCategory @splatSecondCopy + $secondCopyResults.Name | Should -Be "dbatoolsci test category" + $secondCopyResults.Status | Should -Be "Skipped" } } } diff --git a/tests/Copy-DbaAgentOperator.Tests.ps1 b/tests/Copy-DbaAgentOperator.Tests.ps1 index 361ebf9a1d..846e46d8b1 100644 --- a/tests/Copy-DbaAgentOperator.Tests.ps1 +++ b/tests/Copy-DbaAgentOperator.Tests.ps1 @@ -1,19 +1,40 @@ -$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 = 'Source', 'SourceSqlCredential', 'Destination', 'DestinationSqlCredential', 'Operator', 'ExcludeOperator', 'Force', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + +Describe "Copy-DbaAgentOperator" -Tag "UnitTests" { + Context "Parameter validation" { + BeforeAll { + $command = Get-Command Copy-DbaAgentOperator + $expected = $TestConfig.CommonParameters + $expected += @( + "Source", + "SourceSqlCredential", + "Destination", + "DestinationSqlCredential", + "Operator", + "ExcludeOperator", + "Force", + "EnableException", + "Confirm", + "WhatIf" + ) + } + + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tag "IntegrationTests" { +Describe "Copy-DbaAgentOperator" -Tag "IntegrationTests" { BeforeAll { $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 $sql = "EXEC msdb.dbo.sp_add_operator @name=N'dbatoolsci_operator', @enabled=1, @pager_days=0" @@ -21,6 +42,7 @@ Describe "$commandname Integration Tests" -Tag "IntegrationTests" { $sql = "EXEC msdb.dbo.sp_add_operator @name=N'dbatoolsci_operator2', @enabled=1, @pager_days=0" $server.Query($sql) } + AfterAll { $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 $sql = "EXEC msdb.dbo.sp_delete_operator @name=N'dbatoolsci_operator'" @@ -35,17 +57,25 @@ Describe "$commandname Integration Tests" -Tag "IntegrationTests" { $server.Query($sql) } - Context "Copies operators" { - $results = Copy-DbaAgentOperator -Source $TestConfig.instance2 -Destination $TestConfig.instance3 -Operator dbatoolsci_operator, dbatoolsci_operator2 - - It "returns two results" { - $results.Count -eq 2 - $results.Status -eq "Successful", "Successful" + Context "When copying operators" { + It "Returns two copied operators" { + $splat = @{ + Source = $TestConfig.instance2 + Destination = $TestConfig.instance3 + Operator = 'dbatoolsci_operator', 'dbatoolsci_operator2' + } + $results = Copy-DbaAgentOperator @splat + $results.Status.Count | Should -Be 2 + $results.Status | Should -Be "Successful", "Successful" } - It "return one result that's skipped" { - $results = Copy-DbaAgentOperator -Source $TestConfig.instance2 -Destination $TestConfig.instance3 -Operator dbatoolsci_operator - $results.Status -eq "Skipped" + It "Returns one result that's skipped when copying an existing operator" { + $splet = @{ + Source = $TestConfig.instance2 + Destination = $TestConfig.instance3 + Operator = 'dbatoolsci_operator' + } + (Copy-DbaAgentOperator @splet).Status | Should -Be "Skipped" } } } diff --git a/tests/Invoke-DbaQuery.Tests.ps1 b/tests/Invoke-DbaQuery.Tests.ps1 index 640b561857..3aa9c6e774 100644 --- a/tests/Invoke-DbaQuery.Tests.ps1 +++ b/tests/Invoke-DbaQuery.Tests.ps1 @@ -13,7 +13,7 @@ Describe "$CommandName Unit Tests" -Tag 'UnitTests' { $command = Get-Command Invoke-DbaQuery } It "Should only contain our specific parameters" { - [object[]]$params = $command.Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } + [object[]]$params = $command.Parameters.Values.Name | Where-Object { $_ -notin ('whatif', 'confirm') } [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'Query', 'QueryTimeout', 'File', 'SqlObject', 'As', 'SqlParameter', 'AppendServerInstance', 'MessagesToOutput', 'InputObject', 'ReadOnly', 'EnableException', 'CommandType', 'NoExec' $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should -Be 0 diff --git a/tests/constants.local.ps1.example b/tests/constants.local.ps1.example index ad19576648..cb622f2858 100644 --- a/tests/constants.local.ps1.example +++ b/tests/constants.local.ps1.example @@ -50,10 +50,3 @@ $config['bigDatabaseBackup'] = "C:\path\to\yourdatabase.bak" # Replace with # URL to download the large database backup file $config['bigDatabaseBackupSourceUrl'] = "https://yoururl.com/yourdatabase.bak" # Replace with the actual URL - -# Handle appveyor environment if needed -if ($env:appveyor) { - $config['PSDefaultParameterValues'] = @{ - '*:WarningAction' = 'SilentlyContinue' - } -}