diff --git a/.aitools/module/Repair-PullRequestTest.ps1 b/.aitools/module/Repair-PullRequestTest.ps1 index 9b796a51768..9cdb2ea316b 100644 --- a/.aitools/module/Repair-PullRequestTest.ps1 +++ b/.aitools/module/Repair-PullRequestTest.ps1 @@ -26,6 +26,10 @@ function Repair-PullRequestTest { from the development branch to the current branch, without running Update-PesterTest or committing any changes. + .PARAMETER Pattern + Pattern to filter test files. Only files matching this pattern will be processed. + Supports wildcards (e.g., "*Login*" to match files containing "Login"). + .NOTES Tags: Testing, Pester, PullRequest, CI Author: dbatools team @@ -53,7 +57,8 @@ function Repair-PullRequestTest { [switch]$AutoCommit, [int]$MaxPRs = 5, [int]$BuildNumber, - [switch]$CopyOnly + [switch]$CopyOnly, + [string]$Pattern ) begin { @@ -269,7 +274,14 @@ function Repair-PullRequestTest { $fileErrorPath = @() $testdirectory = Join-Path $script:ModulePath "tests" - foreach ($test in $allFailedTestsAcrossPRs) { + # Apply Pattern filter first if specified + $filteredTests = if ($Pattern) { + $allFailedTestsAcrossPRs | Where-Object { [System.IO.Path]::GetFileName($_.TestFile) -match $Pattern } + } else { + $allFailedTestsAcrossPRs + } + + foreach ($test in $filteredTests) { $fileName = [System.IO.Path]::GetFileName($test.TestFile) # ONLY include files that are actually in the PR changes if ($allRelevantTestFiles.Count -eq 0 -or $fileName -in $allRelevantTestFiles) { @@ -284,7 +296,11 @@ function Repair-PullRequestTest { } } $fileErrorPath = $fileErrorPath | Sort-Object -Unique - Write-Verbose "Found failures in $($fileErrorMap.Keys.Count) unique test files (filtered to PR changes only)" + $filterMessage = "filtered to PR changes only" + if ($Pattern) { + $filterMessage += " and pattern '$Pattern'" + } + Write-Verbose "Found failures in $($fileErrorMap.Keys.Count) unique test files ($filterMessage)" foreach ($fileName in $fileErrorMap.Keys) { Write-Verbose " ${fileName} - $($fileErrorMap[$fileName].Count) failures" Write-Verbose " Paths: $fileErrorPath" diff --git a/tests/Get-DbaClientAlias.Tests.ps1 b/tests/Get-DbaClientAlias.Tests.ps1 index 551ef159061..21b2e06382f 100644 --- a/tests/Get-DbaClientAlias.Tests.ps1 +++ b/tests/Get-DbaClientAlias.Tests.ps1 @@ -1,30 +1,47 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaClientAlias", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { +Describe $CommandName -Tag UnitTests { Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'ComputerName', 'Credential', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "ComputerName", + "Credential", + "EnableException" + ) + } + It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { - $newalias = New-DbaClientAlias -ServerName sql2016 -Alias dbatoolscialias -Verbose:$false + $newAlias = New-DbaClientAlias -ServerName sql2016 -Alias dbatoolscialias -Verbose:$false } + AfterAll { - $newalias | Remove-DbaClientAlias + $newAlias | Remove-DbaClientAlias -ErrorAction SilentlyContinue } Context "gets the alias" { - $results = Get-DbaClientAlias + BeforeAll { + $results = Get-DbaClientAlias + } + It "returns accurate information" { - $results.AliasName -contains 'dbatoolscialias' | Should Be $true + $results.AliasName -contains "dbatoolscialias" | Should -Be $true } } } \ No newline at end of file diff --git a/tests/Get-DbaClientProtocol.Tests.ps1 b/tests/Get-DbaClientProtocol.Tests.ps1 index 967f4fbe6f0..a2565e8615f 100644 --- a/tests/Get-DbaClientProtocol.Tests.ps1 +++ b/tests/Get-DbaClientProtocol.Tests.ps1 @@ -1,24 +1,40 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaClientProtocol", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'ComputerName', 'Credential', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "ComputerName", + "Credential", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { Context "Get some client protocols" { - $results = Get-DbaClientProtocol + BeforeAll { + $results = @(Get-DbaClientProtocol) + } + It "Should return some protocols" { - $results.Count | Should BeGreaterThan 1 - $results | Where-Object { $_.ProtocolDisplayName -eq 'TCP/IP' } | Should Not Be $null + $results.Status.Count | Should -BeGreaterThan 1 + $results | Where-Object ProtocolDisplayName -eq "TCP/IP" | Should -Not -BeNullOrEmpty } } } \ No newline at end of file diff --git a/tests/Get-DbaCmConnection.Tests.ps1 b/tests/Get-DbaCmConnection.Tests.ps1 index 5d0b25740d7..fe5ffb12b00 100644 --- a/tests/Get-DbaCmConnection.Tests.ps1 +++ b/tests/Get-DbaCmConnection.Tests.ps1 @@ -1,35 +1,54 @@ -$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', 'UserName', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaCmConnection", + $PSDefaultParameterValues = $TestConfig.Defaults +) + +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "ComputerName", + "UserName", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { New-DbaCmConnection -ComputerName $env:COMPUTERNAME } + AfterAll { - Remove-DbaCmConnection -ComputerName $env:COMPUTERNAME -Confirm:$False + Remove-DbaCmConnection -ComputerName $env:COMPUTERNAME -Confirm:$false } + Context "Returns DbaCmConnection" { - $Results = Get-DbaCMConnection -ComputerName $env:COMPUTERNAME + BeforeAll { + $cmConnectionResults = Get-DbaCmConnection -ComputerName $env:COMPUTERNAME + } + It "Results are not Empty" { - $Results | should not be $null + $cmConnectionResults | Should -Not -BeNullOrEmpty } } + Context "Returns DbaCmConnection for User" { - $Results = Get-DbaCMConnection -ComputerName $env:COMPUTERNAME -UserName * + BeforeAll { + $userConnectionResults = Get-DbaCmConnection -ComputerName $env:COMPUTERNAME -UserName * + } + It "Results are not Empty" { - $Results | should not be $null + $userConnectionResults | Should -Not -BeNullOrEmpty } } } \ No newline at end of file diff --git a/tests/Get-DbaCmObject.Tests.ps1 b/tests/Get-DbaCmObject.Tests.ps1 index 23bbd04a63c..79208dfb71c 100644 --- a/tests/Get-DbaCmObject.Tests.ps1 +++ b/tests/Get-DbaCmObject.Tests.ps1 @@ -1,22 +1,41 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaCmObject", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'ClassName', 'Query', 'ComputerName', 'Credential', 'Namespace', 'DoNotUse', 'Force', 'SilentlyContinue', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "ClassName", + "Query", + "ComputerName", + "Credential", + "Namespace", + "DoNotUse", + "Force", + "SilentlyContinue", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { - Context "returns proper information" { - It "returns a bias that's an int" { - (Get-DbaCmObject -ClassName Win32_TimeZone).Bias -is [int] +Describe $CommandName -Tag IntegrationTests { + Context "Returns proper information" { + It "Returns a bias that's an int" { + (Get-DbaCmObject -ClassName Win32_TimeZone).Bias | Should -BeOfType [int] } } } \ No newline at end of file diff --git a/tests/Get-DbaComputerCertificate.Tests.ps1 b/tests/Get-DbaComputerCertificate.Tests.ps1 index 94918a99107..a476d7d0444 100644 --- a/tests/Get-DbaComputerCertificate.Tests.ps1 +++ b/tests/Get-DbaComputerCertificate.Tests.ps1 @@ -1,41 +1,61 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaComputerCertificate", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'ComputerName', 'Credential', 'Store', 'Folder', 'Path', 'Thumbprint', 'EnableException', 'Type' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "ComputerName", + "Credential", + "Store", + "Folder", + "Path", + "Thumbprint", + "EnableException", + "Type" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { Context "Can get a certificate" { BeforeAll { $null = Add-DbaComputerCertificate -Path "$($TestConfig.appveyorlabrepo)\certificates\localhost.crt" -Confirm:$false $thumbprint = "29C469578D6C6211076A09CEE5C5797EEA0C2713" + + # Get all certificates once for testing + $allCertificates = Get-DbaComputerCertificate + $specificCertificate = Get-DbaComputerCertificate -Thumbprint $thumbprint } + AfterAll { - Remove-DbaComputerCertificate -Thumbprint $thumbprint -Confirm:$false + Remove-DbaComputerCertificate -Thumbprint $thumbprint -Confirm:$false -ErrorAction SilentlyContinue } - $cert = Get-DbaComputerCertificate -Thumbprint $thumbprint - It "returns a single certificate with a specific thumbprint" { - $cert.Thumbprint | Should Be $thumbprint + $specificCertificate.Thumbprint | Should -Be $thumbprint } - $cert = Get-DbaComputerCertificate - It "returns all certificates and at least one has the specified thumbprint" { - "$($cert.Thumbprint)" -match $thumbprint | Should Be $true + "$($allCertificates.Thumbprint)" -match $thumbprint | Should -Be $true } + It "returns all certificates and at least one has the specified EnhancedKeyUsageList" { - "$($cert.EnhancedKeyUsageList)" -match '1\.3\.6\.1\.5\.5\.7\.3\.1' | Should Be $true + "$($allCertificates.EnhancedKeyUsageList)" -match "1\.3\.6\.1\.5\.5\.7\.3\.1" | Should -Be $true } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaComputerSystem.Tests.ps1 b/tests/Get-DbaComputerSystem.Tests.ps1 index 082c04ff639..e8e50d6d7bc 100644 --- a/tests/Get-DbaComputerSystem.Tests.ps1 +++ b/tests/Get-DbaComputerSystem.Tests.ps1 @@ -1,35 +1,65 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaComputerSystem", # Static command name for dbatools + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "Get-DbaComputerSystem Unit Tests" -Tag "UnitTests" { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'ComputerName', 'Credential', 'IncludeAws', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "ComputerName", + "Credential", + "IncludeAws", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } Context "Validate input" { - it "Cannot resolve hostname of computer" { - mock Resolve-DbaNetworkName {$null} - {Get-DbaComputerSystem -ComputerName 'DoesNotExist142' -WarningAction Stop 3> $null} | Should Throw + It "Cannot resolve hostname of computer" { + Mock Resolve-DbaNetworkName { $null } + { Get-DbaComputerSystem -ComputerName "DoesNotExist142" -WarningAction Stop 3> $null } | Should -Throw } } } -Describe "Get-DbaComputerSystem Integration Test" -Tag "IntegrationTests" { - $result = Get-DbaComputerSystem -ComputerName $TestConfig.instance1 +Describe $CommandName -Tag IntegrationTests { + BeforeAll { + $result = Get-DbaComputerSystem -ComputerName $TestConfig.instance1 - $props = 'ComputerName', 'Domain', 'IsDaylightSavingsTime', 'Manufacturer', 'Model', 'NumberLogicalProcessors' - , 'NumberProcessors', 'IsHyperThreading', 'SystemFamily', 'SystemSkuNumber', 'SystemType', 'IsSystemManagedPageFile', 'TotalPhysicalMemory' + $props = @( + "ComputerName", + "Domain", + "IsDaylightSavingsTime", + "Manufacturer", + "Model", + "NumberLogicalProcessors", + "NumberProcessors", + "IsHyperThreading", + "SystemFamily", + "SystemSkuNumber", + "SystemType", + "IsSystemManagedPageFile", + "TotalPhysicalMemory" + ) + } Context "Validate output" { - foreach ($prop in $props) { - $p = $result.PSObject.Properties[$prop] - it "Should return property: $prop" { - $p.Name | Should Be $prop + It "Should return all expected properties" { + $result | Should -Not -BeNullOrEmpty + foreach ($prop in $props) { + $p = $result.PSObject.Properties[$prop] + $p.Name | Should -Be $prop } } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaConnectedInstance.Tests.ps1 b/tests/Get-DbaConnectedInstance.Tests.ps1 index 4246ba145f2..a70ef5397a3 100644 --- a/tests/Get-DbaConnectedInstance.Tests.ps1 +++ b/tests/Get-DbaConnectedInstance.Tests.ps1 @@ -1,8 +1,14 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaConnectedInstance", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag "UnitTests" { +Describe $CommandName -Tag UnitTests { Context "Validate parameters" { # fake tests, no parameters to validate It "Should only contain our specific parameters" { @@ -11,14 +17,15 @@ Describe "$CommandName Unit Tests" -Tag "UnitTests" { } } -Describe "$commandname Integration Tests" -Tag "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { $null = Get-DbaDatabase -SqlInstance $TestConfig.instance1 } + Context "gets connected objects" { It "returns some results" { $results = Get-DbaConnectedInstance $results | Should -Not -BeNullOrEmpty } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaConnection.Tests.ps1 b/tests/Get-DbaConnection.Tests.ps1 index a4d42339ffa..b2cf52c0e70 100644 --- a/tests/Get-DbaConnection.Tests.ps1 +++ b/tests/Get-DbaConnection.Tests.ps1 @@ -1,19 +1,19 @@ #Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } param( $ModuleName = "dbatools", - $CommandName = [System.IO.Path]::GetFileName($PSCommandPath.Replace('.Tests.ps1', '')), + $CommandName = "Get-DbaConnection", $PSDefaultParameterValues = $TestConfig.Defaults ) -Describe $CommandName -Tag "UnitTests" { +Describe $CommandName -Tag UnitTests { Context "Parameter validation" { BeforeAll { - $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $_ -notin ('WhatIf', 'Confirm') } + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } $expectedParameters = $TestConfig.CommonParameters $expectedParameters += @( - 'SqlInstance', - 'SqlCredential', - 'EnableException' + "SqlInstance", + "SqlCredential", + "EnableException" ) } It "Should have the expected parameters" { @@ -22,7 +22,7 @@ Describe $CommandName -Tag "UnitTests" { } } -Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { Context "returns the proper transport" { BeforeAll { $results = Get-DbaConnection -SqlInstance $TestConfig.instance1 @@ -30,8 +30,8 @@ Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { It "returns a valid AuthScheme" { foreach ($result in $results) { - $result.AuthScheme | Should -BeIn 'NTLM', 'Kerberos', 'SQL' + $result.AuthScheme | Should -BeIn "NTLM", "Kerberos", "SQL" } } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaCpuRingBuffer.Tests.ps1 b/tests/Get-DbaCpuRingBuffer.Tests.ps1 index 420b9859635..0a926b8c1e8 100644 --- a/tests/Get-DbaCpuRingBuffer.Tests.ps1 +++ b/tests/Get-DbaCpuRingBuffer.Tests.ps1 @@ -1,24 +1,40 @@ -$commandname = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaCpuRingBuffer", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tags "UnitTests" { +Describe $CommandName -Tag UnitTests { Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'CollectionMinutes', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "CollectionMinutes", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { Context "Command returns proper info" { - $results = Get-DbaCpuRingBuffer -SqlInstance $TestConfig.instance2 -CollectionMinutes 100 + BeforeAll { + $results = @(Get-DbaCpuRingBuffer -SqlInstance $TestConfig.instance2 -CollectionMinutes 100) + } It "returns results" { - $results.Count -gt 0 | Should Be $true + $results.Count | Should -BeGreaterThan 0 } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaCpuUsage.Tests.ps1 b/tests/Get-DbaCpuUsage.Tests.ps1 index c723f5f90dc..dd95db12e27 100644 --- a/tests/Get-DbaCpuUsage.Tests.ps1 +++ b/tests/Get-DbaCpuUsage.Tests.ps1 @@ -1,23 +1,38 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaCpuUsage", + $PSDefaultParameterValues = $TestConfig.Defaults +) -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Credential', 'Threshold', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Credential", + "Threshold", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { Context "Gets the CPU Usage" { - $results = Get-DbaCPUUsage -SqlInstance $TestConfig.instance2 + BeforeAll { + $results = Get-DbaCpuUsage -SqlInstance $TestConfig.instance2 + } + It "Results are not empty" { - $results | Should Not Be $Null + $results | Should -Not -BeNullOrEmpty } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaCredential.Tests.ps1 b/tests/Get-DbaCredential.Tests.ps1 index 12566e5447e..04ce5f3eebb 100644 --- a/tests/Get-DbaCredential.Tests.ps1 +++ b/tests/Get-DbaCredential.Tests.ps1 @@ -1,22 +1,42 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaCredential", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig . "$PSScriptRoot\..\private\functions\Invoke-Command2.ps1" -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', 'ExcludeCredential', 'Identity', 'ExcludeIdentity', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Credential", + "ExcludeCredential", + "Identity", + "ExcludeIdentity", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + $logins = "thor", "thorsmomma" $plaintext = "BigOlPassword!" $password = ConvertTo-SecureString $plaintext -AsPlainText -Force @@ -26,33 +46,63 @@ Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { $null = Invoke-Command2 -ScriptBlock { net user $args[0] $args[1] /add *>&1 } -ArgumentList $login, $plaintext -ComputerName $TestConfig.instance2 } - $null = New-DbaCredential -SqlInstance $TestConfig.instance2 -Name thorcred -Identity thor -Password $password - $null = New-DbaCredential -SqlInstance $TestConfig.instance2 -Identity thorsmomma -Password $password + $splatThorCred = @{ + SqlInstance = $TestConfig.instance2 + Name = "thorcred" + Identity = "thor" + Password = $password + } + $null = New-DbaCredential @splatThorCred + + $splatThorsmormmaCred = @{ + SqlInstance = $TestConfig.instance2 + Identity = "thorsmomma" + Password = $password + } + $null = New-DbaCredential @splatThorsmormmaCred + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } AfterAll { + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + try { - (Get-DbaCredential -SqlInstance $TestConfig.instance2 -Identity thor, thorsmomma -ErrorAction Stop -WarningAction SilentlyContinue).Drop() + $splatGetCred = @{ + SqlInstance = $TestConfig.instance2 + Identity = "thor", "thorsmomma" + ErrorAction = "Stop" + WarningAction = "SilentlyContinue" + } + (Get-DbaCredential @splatGetCred).Drop() } catch { } foreach ($login in $logins) { $null = Invoke-Command2 -ScriptBlock { net user $args /delete *>&1 } -ArgumentList $login -ComputerName $TestConfig.instance2 } + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } Context "Get credentials" { It "Should get just one credential with the proper properties when using Identity" { - $results = Get-DbaCredential -SqlInstance $TestConfig.instance2 -Identity thorsmomma - $results.Name | Should Be "thorsmomma" - $results.Identity | Should Be "thorsmomma" + $results = Get-DbaCredential -SqlInstance $TestConfig.instance2 -Identity "thorsmomma" + $results.Name | Should -Be "thorsmomma" + $results.Identity | Should -Be "thorsmomma" } It "Should get just one credential with the proper properties when using Name" { - $results = Get-DbaCredential -SqlInstance $TestConfig.instance2 -Name thorsmomma - $results.Name | Should Be "thorsmomma" - $results.Identity | Should Be "thorsmomma" + $results = Get-DbaCredential -SqlInstance $TestConfig.instance2 -Name "thorsmomma" + $results.Name | Should -Be "thorsmomma" + $results.Identity | Should -Be "thorsmomma" } It "gets more than one credential" { - $results = Get-DbaCredential -SqlInstance $TestConfig.instance2 -Identity thor, thorsmomma - $results.count -gt 1 + $splatMultipleCreds = @{ + SqlInstance = $TestConfig.instance2 + Identity = "thor", "thorsmomma" + } + $results = Get-DbaCredential @splatMultipleCreds + $results.Count | Should -BeGreaterThan 1 } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaCustomError.Tests.ps1 b/tests/Get-DbaCustomError.Tests.ps1 index 1c0f84a25ac..f2074b3e953 100644 --- a/tests/Get-DbaCustomError.Tests.ps1 +++ b/tests/Get-DbaCustomError.Tests.ps1 @@ -1,43 +1,83 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaCustomError", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { +Describe $CommandName -Tag UnitTests { Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true + + # Explain what needs to be set up for the test: + # We need to create a custom error message to test retrieval. + + # Set variables. They are available in all the It blocks. + $customErrorId = 54321 + $customErrorText = "Dbatools is Awesome!" + + # Create the custom error. $server = Connect-DbaInstance -SqlInstance $TestConfig.instance1 - $sql = "EXEC msdb.dbo.sp_addmessage 54321, 9, N'Dbatools is Awesome!';" + $sql = "EXEC msdb.dbo.sp_addmessage $customErrorId, 9, N'$customErrorText';" $server.Query($sql) + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove("*-Dba*:EnableException") } - Afterall { + + AfterAll { + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true + + # Cleanup all created objects. $server = Connect-DbaInstance -SqlInstance $TestConfig.instance1 $sql = "EXEC msdb.dbo.sp_dropmessage 54321;" $server.Query($sql) + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } - Context "Gets the backup devices" { - $results = Get-DbaCustomError -SqlInstance $TestConfig.instance1 + Context "Gets the custom errors" { + BeforeAll { + $results = Get-DbaCustomError -SqlInstance $TestConfig.instance1 + } + It "Results are not empty" { - $results | Should Not Be $Null + $results | Should -Not -BeNullOrEmpty } + It "Should have the name Custom Error Text" { - $results.Text | Should Be "Dbatools is Awesome!" + $results.Text | Should -Be "Dbatools is Awesome!" } + It "Should have a LanguageID" { - $results.LanguageID | Should Be 1033 + $results.LanguageID | Should -Be 1033 } + It "Should have a Custom Error ID" { - $results.ID | Should Be 54321 + $results.ID | Should -Be 54321 } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaDBFileGroup.Tests.ps1 b/tests/Get-DbaDBFileGroup.Tests.ps1 index 6dca8ed26e2..7504cda7822 100644 --- a/tests/Get-DbaDBFileGroup.Tests.ps1 +++ b/tests/Get-DbaDBFileGroup.Tests.ps1 @@ -1,65 +1,113 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaDbFileGroup", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'InputObject', 'FileGroup', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Database", + "InputObject", + "FileGroup", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # For all the backups that we want to clean up after the test, we create a directory that we can delete at the end. + # Other files can be written there as well, maybe we change the name of that variable later. But for now we focus on backups. + $backupPath = "$($TestConfig.Temp)\$CommandName-$(Get-Random)" + $null = New-Item -Path $backupPath -ItemType Directory + + # Set variables. They are available in all the It blocks. $random = Get-Random $multifgdb = "dbatoolsci_multifgdb$random" + + # Remove any existing database before creating Remove-DbaDatabase -Confirm:$false -SqlInstance $TestConfig.instance2 -Database $multifgdb + # Create the test database with multiple filegroups $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 $server.Query("CREATE DATABASE $multifgdb; ALTER DATABASE $multifgdb ADD FILEGROUP [Test1]; ALTER DATABASE $multifgdb ADD FILEGROUP [Test2];") + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } + AfterAll { - Remove-DbaDatabase -Confirm:$false -SqlInstance $TestConfig.instance2 -Database $multifgdb + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # Cleanup all created objects. + Remove-DbaDatabase -Confirm:$false -SqlInstance $TestConfig.instance2 -Database $multifgdb -ErrorAction SilentlyContinue + + # Remove the backup directory. + Remove-Item -Path $backupPath -Recurse -ErrorAction SilentlyContinue + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } Context "Returns values for Instance" { - $results = Get-DbaDbFileGroup -SqlInstance $TestConfig.instance2 + BeforeAll { + $results = Get-DbaDbFileGroup -SqlInstance $TestConfig.instance2 + } + It "Results are not empty" { - $results | Should Not Be $Null + $results | Should -Not -BeNullOrEmpty } + It "Returns the correct object" { - $results[0].GetType().ToString() | Should Be "Microsoft.SqlServer.Management.Smo.FileGroup" + $results[0].GetType().ToString() | Should -Be "Microsoft.SqlServer.Management.Smo.FileGroup" } } Context "Accepts database and filegroup input" { - $results = Get-DbaDbFileGroup -SqlInstance $TestConfig.instance2 -Database $multifgdb - - It "Reports the right number of filegroups" { - $results.Count | Should Be 3 + BeforeAll { + $allFileGroupResults = Get-DbaDbFileGroup -SqlInstance $TestConfig.instance2 -Database $multifgdb + $singleFileGroupResult = Get-DbaDbFileGroup -SqlInstance $TestConfig.instance2 -Database $multifgdb -FileGroup Test1 } - $results = Get-DbaDbFileGroup -SqlInstance $TestConfig.instance2 -Database $multifgdb -FileGroup Test1 + It "Reports the right number of filegroups for database" { + $allFileGroupResults.Count | Should -BeExactly 3 + } - It "Reports the right number of filegroups" { - $results.Count | Should Be 1 + It "Reports the right number of filegroups for specific filegroup" { + $singleFileGroupResult.Count | Should -BeExactly 1 } } Context "Accepts piped input" { - $results = Get-DbaDatabase -SqlInstance $TestConfig.instance2 -ExcludeUser | Get-DbaDbFileGroup + BeforeAll { + $pipedResults = Get-DbaDatabase -SqlInstance $TestConfig.instance2 -ExcludeUser | Get-DbaDbFileGroup + } It "Reports the right number of filegroups" { - $results.Count | Should Be 4 + $pipedResults.Count | Should -BeExactly 4 } It "Excludes User Databases" { - $results.Parent.Name | Should -Not -Contain $multifgdb - $results.Parent.Name | Should -Contain 'msdb' + $pipedResults.Parent.Name | Should -Not -Contain $multifgdb + $pipedResults.Parent.Name | Should -Contain "msdb" } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbAssembly.Tests.ps1 b/tests/Get-DbaDbAssembly.Tests.ps1 index 6da90505989..07d6f8d6f54 100644 --- a/tests/Get-DbaDbAssembly.Tests.ps1 +++ b/tests/Get-DbaDbAssembly.Tests.ps1 @@ -1,34 +1,55 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaDbAssembly", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'EnableException', 'Name', 'Database' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Database", + "Name", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { - Context "Gets the Db Assembly" { - $results = Get-DbaDbAssembly -SqlInstance $TestConfig.instance2 | Where-Object { $_.parent.name -eq 'master' } - $masterDb = Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database master - It "Gets results" { - $results | Should Not Be $Null - $results.DatabaseId | Should -Be $masterDb.Id +Describe $CommandName -Tag IntegrationTests { + Context "When getting database assemblies" { + BeforeAll { + $assemblyResults = Get-DbaDbAssembly -SqlInstance $TestConfig.instance2 | Where-Object { $PSItem.parent.name -eq "master" } + $masterDatabase = Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database master } - It "Should have a name of Microsoft.SqlServer.Types" { - $results.name | Should Be "Microsoft.SqlServer.Types" + + It "Returns assembly objects" { + $assemblyResults | Should -Not -BeNullOrEmpty + $assemblyResults.DatabaseId | Should -BeExactly $masterDatabase.Id } - It "Should have an owner of sys" { - $results.owner | Should Be "sys" + + It "Has the correct assembly name" { + $assemblyResults.name | Should -BeExactly "Microsoft.SqlServer.Types" } - It "Should have a version matching the instance" { - $results.Version | Should -Be $masterDb.assemblies.Version + + It "Has the correct owner" { + $assemblyResults.owner | Should -BeExactly "sys" + } + + It "Has a version matching the instance" { + $assemblyResults.Version | Should -BeExactly $masterDatabase.assemblies.Version } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbAsymmetricKey.Tests.ps1 b/tests/Get-DbaDbAsymmetricKey.Tests.ps1 index 0b90c4b4f39..c7c8e04a6e2 100644 --- a/tests/Get-DbaDbAsymmetricKey.Tests.ps1 +++ b/tests/Get-DbaDbAsymmetricKey.Tests.ps1 @@ -1,57 +1,119 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaDbAsymmetricKey", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Name', 'Database', 'InputObject', 'EnableException', 'ExcludeDatabase' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Database", + "ExcludeDatabase", + "Name", + "InputObject", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { Context "Gets a certificate" { - $keyname = 'test4' - $keyname2 = 'test5' - $algorithm = 'Rsa4096' - $dbuser = 'keyowner' - $database = 'GetAsKey' - $newDB = New-DbaDatabase -SqlInstance $TestConfig.instance2 -Name $database - $tPassword = ConvertTo-SecureString "ThisIsThePassword1" -AsPlainText -Force - New-DbaDbMasterKey -SqlInstance $TestConfig.instance2 -Database $database -SecurePassword $tPassword -confirm:$false - New-DbaDbUser -SqlInstance $TestConfig.instance2 -Database $database -UserName $dbuser - $null = New-DbaDbAsymmetricKey -SqlInstance $TestConfig.instance2 -Database $database -Name $keyname -Owner keyowner -Algorithm $algorithm -WarningVariable warnvar - $results = Get-DbaDbAsymmetricKey -SqlInstance $TestConfig.instance2 -Name $keyname -Database $database - It "Should Create new key in $database called $keyname" { - $warnvar | Should -BeNullOrEmpty - $results.database | Should -Be $database - $results.DatabaseId | Should -Be $newDB.ID - $results.name | Should -Be $keyname - $results.Owner | Should -Be $dbuser + BeforeAll { + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # Set variables. They are available in all the It blocks. + $keyName = "test4" + $keyName2 = "test5" + $algorithm = "Rsa4096" + $dbUser = "keyowner" + $databaseName = "GetAsKey" + + # Create the objects. + $newDatabase = New-DbaDatabase -SqlInstance $TestConfig.instance2 -Name $databaseName + $tPassword = ConvertTo-SecureString "ThisIsThePassword1" -AsPlainText -Force + + $splatMasterKey = @{ + SqlInstance = $TestConfig.instance2 + Database = $databaseName + SecurePassword = $tPassword + Confirm = $false + } + $null = New-DbaDbMasterKey @splatMasterKey + + $null = New-DbaDbUser -SqlInstance $TestConfig.instance2 -Database $databaseName -UserName $dbUser + + $splatFirstKey = @{ + SqlInstance = $TestConfig.instance2 + Database = $databaseName + Name = $keyName + Owner = "keyowner" + Algorithm = $algorithm + WarningVariable = "warnvar" + } + $null = New-DbaDbAsymmetricKey @splatFirstKey + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') + } + + AfterAll { + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # Cleanup all created objects. + $null = Remove-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $databaseName -Confirm:$false + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. + } + + It "Should Create new key in GetAsKey called test4" { + $results = Get-DbaDbAsymmetricKey -SqlInstance $TestConfig.instance2 -Name $keyName -Database $databaseName + $results.Database | Should -Be $databaseName + $results.DatabaseId | Should -Be $newDatabase.ID + $results.Name | Should -Be $keyName + $results.Owner | Should -Be $dbUser $results | Should -HaveCount 1 } - $pipeResults = Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $database | Get-DbaDbAsymmetricKey + It "Should work with a piped database" { - $pipeResults.database | Should -Be $database - $pipeResults.name | Should -Be $keyname - $pipeResults.Owner | Should -Be $dbuser + $pipeResults = Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $databaseName | Get-DbaDbAsymmetricKey + $pipeResults.Database | Should -Be $databaseName + $pipeResults.Name | Should -Be $keyName + $pipeResults.Owner | Should -Be $dbUser $pipeResults | Should -HaveCount 1 } - $null = New-DbaDbAsymmetricKey -SqlInstance $TestConfig.instance2 -Database $database -Name $keyname2 -Owner keyowner -Algorithm $algorithm -WarningVariable warnvar - $multiResults = Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $database | Get-DbaDbAsymmetricKey It "Should return 2 keys" { + # Create second key for this test + $splatSecondKey = @{ + SqlInstance = $TestConfig.instance2 + Database = $databaseName + Name = $keyName2 + Owner = "keyowner" + Algorithm = $algorithm + WarningVariable = "warnvar" + } + $null = New-DbaDbAsymmetricKey @splatSecondKey + + $multiResults = Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $databaseName | Get-DbaDbAsymmetricKey $multiResults | Should -HaveCount 2 - $multiresults.name | Should -Contain $keyname - $multiresults.name | Should -Contain $keyname2 - } - $drop = Remove-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $database -confirm:$false - It "Should drop database" { - $drop.Status | Should -Be 'Dropped' + $multiResults.Name | Should -Contain $keyName + $multiResults.Name | Should -Contain $keyName2 } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbBackupHistory.Tests.ps1 b/tests/Get-DbaDbBackupHistory.Tests.ps1 index badca8b4e1a..8ebf6d61efa 100644 --- a/tests/Get-DbaDbBackupHistory.Tests.ps1 +++ b/tests/Get-DbaDbBackupHistory.Tests.ps1 @@ -1,21 +1,55 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaDbBackupHistory", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'ExcludeDatabase', 'IncludeCopyOnly', 'Force', 'Since', 'RecoveryFork', 'Last', 'LastFull', 'LastDiff', 'LastLog', 'DeviceType', 'Raw', 'LastLsn', 'Type', 'EnableException', 'IncludeMirror', 'AgCheck', 'IgnoreDiffBackup', 'LsnSort' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Database", + "ExcludeDatabase", + "IncludeCopyOnly", + "Force", + "Since", + "RecoveryFork", + "Last", + "LastFull", + "LastDiff", + "LastLog", + "DeviceType", + "Raw", + "LastLsn", + "Type", + "EnableException", + "IncludeMirror", + "AgCheck", + "IgnoreDiffBackup", + "LsnSort" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { - $DestBackupDir = 'C:\Temp\backups' + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true + + $DestBackupDir = "C:\Temp\backups" if (-Not (Test-Path $DestBackupDir)) { New-Item -ItemType Container -Path $DestBackupDir } @@ -25,7 +59,7 @@ Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { $null = Get-DbaDatabase -SqlInstance $TestConfig.instance1 -Database $dbname, $dbnameForked | Remove-DbaDatabase -Confirm:$false $null = Restore-DbaDatabase -SqlInstance $TestConfig.instance1 -Path "$($TestConfig.appveyorlabrepo)\singlerestore\singlerestore.bak" -DatabaseName $dbname -DestinationFilePrefix $dbname $server = Connect-DbaInstance -SqlInstance $TestConfig.instance1 - $server.Databases['master'].ExecuteNonQuery("CREATE DATABASE $dbnameForked; ALTER DATABASE $dbnameForked SET AUTO_CLOSE OFF WITH ROLLBACK IMMEDIATE") + $server.Databases["master"].ExecuteNonQuery("CREATE DATABASE $dbnameForked; ALTER DATABASE $dbnameForked SET AUTO_CLOSE OFF WITH ROLLBACK IMMEDIATE") $db = Get-DbaDatabase -SqlInstance $TestConfig.instance1 -Database $dbname $db | Backup-DbaDatabase -Type Full -BackupDirectory $DestBackupDir $db | Backup-DbaDatabase -Type Differential -BackupDirectory $DestBackupDir @@ -33,27 +67,42 @@ Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { $db | Backup-DbaDatabase -Type Log -BackupDirectory $DestBackupDir $null = Get-DbaDatabase -SqlInstance $TestConfig.instance1 -Database master | Backup-DbaDatabase -Type Full -BackupDirectory $DestBackupDir $db | Backup-DbaDatabase -Type Full -BackupDirectory $DestBackupDir -BackupFileName CopyOnly.bak -CopyOnly + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove("*-Dba*:EnableException") } AfterAll { + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true + $null = Get-DbaDatabase -SqlInstance $TestConfig.instance1 -Database $dbname, $dbnameForked | Remove-DbaDatabase -Confirm:$false - Remove-Item -Path $DestBackupDir -Recurse -Confirm:$false + Remove-Item -Path $DestBackupDir -Recurse -ErrorAction SilentlyContinue + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } Context "Get last history for single database" { - $results = Get-DbaDbBackupHistory -SqlInstance $TestConfig.instance1 -Database $dbname -Last + BeforeAll { + $results = Get-DbaDbBackupHistory -SqlInstance $TestConfig.instance1 -Database $dbname -Last + } + It "Should be 4 backups returned" { - $results.count | Should Be 4 + $results.count | Should -Be 4 } + It "First backup should be a Full Backup" { - $results[0].Type | Should be "Full" + $results[0].Type | Should -Be "Full" } + It "Duration should be meaningful" { - ($results[0].end - $results[0].start).TotalSeconds | Should Be $results[0].Duration.TotalSeconds + ($results[0].end - $results[0].start).TotalSeconds | Should -Be $results[0].Duration.TotalSeconds } + It "Last Backup Should be a log backup" { - $results[-1].Type | Should Be "Log" + $results[-1].Type | Should -Be "Log" } + It "DatabaseId is returned" { $results[0].Database | Should -Be $dbname $results[0].DatabaseId | Should -Be $db.Id @@ -61,46 +110,60 @@ Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { } Context "Get last history for all databases" { - $results = Get-DbaDbBackupHistory -SqlInstance $TestConfig.instance1 + BeforeAll { + $results = Get-DbaDbBackupHistory -SqlInstance $TestConfig.instance1 + } + It "Should be more than one database" { - ($results | Where-Object Database -match "master").Count | Should BeGreaterThan 0 + ($results | Where-Object Database -match "master").Count | Should -BeGreaterThan 0 } } Context "ExcludeDatabase is honored" { - $results = Get-DbaDbBackupHistory -SqlInstance $TestConfig.instance1 -ExcludeDatabase 'master' It "Should not report about excluded database master" { - ($results | Where-Object Database -match "master").Count | Should Be 0 + $results = Get-DbaDbBackupHistory -SqlInstance $TestConfig.instance1 -ExcludeDatabase "master" + ($results | Where-Object Database -match "master").Count | Should -Be 0 } - $results = Get-DbaDbBackupHistory -SqlInstance $TestConfig.instance1 -ExcludeDatabase 'master' -Type Full - It "Should not report about excluded database master" { - ($results | Where-Object Database -match "master").Count | Should Be 0 + + It "Should not report about excluded database master with Type Full" { + $results = Get-DbaDbBackupHistory -SqlInstance $TestConfig.instance1 -ExcludeDatabase "master" -Type Full + ($results | Where-Object Database -match "master").Count | Should -Be 0 } - $results = Get-DbaDbBackupHistory -SqlInstance $TestConfig.instance1 -ExcludeDatabase 'master' -LastFull - It "Should not report about excluded database master" { - ($results | Where-Object Database -match "master").Count | Should Be 0 + + It "Should not report about excluded database master with LastFull" { + $results = Get-DbaDbBackupHistory -SqlInstance $TestConfig.instance1 -ExcludeDatabase "master" -LastFull + ($results | Where-Object Database -match "master").Count | Should -Be 0 } } Context "LastFull should work with multiple databases" { - $results = Get-DbaDbBackupHistory -SqlInstance $TestConfig.instance1 -Database $dbname, master -lastfull + BeforeAll { + $results = Get-DbaDbBackupHistory -SqlInstance $TestConfig.instance1 -Database $dbname, master -lastfull + } + It "Should return 2 records" { - $results.count | Should Be 2 + $results.count | Should -Be 2 } } Context "Testing IncludeCopyOnly with LastFull" { - $results = Get-DbaDbBackupHistory -SqlInstance $TestConfig.instance1 -LastFull -Database $dbname - $resultsCo = Get-DbaDbBackupHistory -SqlInstance $TestConfig.instance1 -LastFull -IncludeCopyOnly -Database $dbname + BeforeAll { + $results = Get-DbaDbBackupHistory -SqlInstance $TestConfig.instance1 -LastFull -Database $dbname + $resultsCo = Get-DbaDbBackupHistory -SqlInstance $TestConfig.instance1 -LastFull -IncludeCopyOnly -Database $dbname + } + It "Should return the CopyOnly Backup" { - ($resultsCo.BackupSetID -ne $Results.BackupSetID) | Should Be $True + ($resultsCo.BackupSetID -ne $Results.BackupSetID) | Should -Be $True } } Context "Testing IncludeCopyOnly with Last" { - $resultsCo = Get-DbaDbBackupHistory -SqlInstance $TestConfig.instance1 -Last -IncludeCopyOnly -Database $dbname + BeforeAll { + $resultsCo = Get-DbaDbBackupHistory -SqlInstance $TestConfig.instance1 -Last -IncludeCopyOnly -Database $dbname + } + It "Should return just the CopyOnly Full Backup" { - ($resultsCo | Measure-Object).count | Should Be 1 + ($resultsCo | Measure-Object).count | Should -Be 1 } } @@ -108,7 +171,7 @@ Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { It "supports large numbers" { $historyObject = New-Object Dataplat.Dbatools.Database.BackupHistory $server = Connect-DbaInstance $TestConfig.instance1 - $cast = $server.Query('select cast(1000000000000000 as numeric(20,0)) AS TotalSize') + $cast = $server.Query("select cast(1000000000000000 as numeric(20,0)) AS TotalSize") $historyObject.TotalSize = $cast.TotalSize ($historyObject.TotalSize.Byte) | Should -Be 1000000000000000 } @@ -151,13 +214,17 @@ Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { } Context "Testing IgnoreDiff parameter for #6914" { - $noIgnore = Get-DbaDbBackupHistory -SqlInstance $TestConfig.instance1 -Database $dbname - $Ignore = Get-DbaDbBackupHistory -SqlInstance $TestConfig.instance1 -Database $dbname -IgnoreDiffBackup + BeforeAll { + $noIgnore = Get-DbaDbBackupHistory -SqlInstance $TestConfig.instance1 -Database $dbname + $Ignore = Get-DbaDbBackupHistory -SqlInstance $TestConfig.instance1 -Database $dbname -IgnoreDiffBackup + } + It "Should return one less backup" { $noIgnore.count - $Ignore.count | Should -Be 1 } + It "Should return no Diff backups" { - ($Ignore | Where-Object Type -like '*diff*').count | Should -Be 0 + ($Ignore | Where-Object Type -like "*diff*").count | Should -Be 0 } } @@ -178,4 +245,4 @@ Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { $warning | Should -BeLike "*-Since must be either a DateTime or TimeSpan object*" } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbCertificate.Tests.ps1 b/tests/Get-DbaDbCertificate.Tests.ps1 index e6b9ad36341..336289f57f5 100644 --- a/tests/Get-DbaDbCertificate.Tests.ps1 +++ b/tests/Get-DbaDbCertificate.Tests.ps1 @@ -1,54 +1,86 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaDbCertificate", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'ExcludeDatabase', 'Certificate', 'Subject', 'InputObject', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Database", + "ExcludeDatabase", + "Certificate", + "Subject", + "InputObject", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { Context "Can get a database certificate" { BeforeAll { + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # Check and create master key if needed if (-not (Get-DbaDbMasterKey -SqlInstance $TestConfig.instance1 -Database master)) { $masterkey = New-DbaDbMasterKey -SqlInstance $TestConfig.instance1 -Database master -Password $(ConvertTo-SecureString -String "GoodPass1234!" -AsPlainText -Force) -Confirm:$false } + # Create test objects $tempdbmasterkey = New-DbaDbMasterKey -SqlInstance $TestConfig.instance1 -Database tempdb -Password $(ConvertTo-SecureString -String "GoodPass1234!" -AsPlainText -Force) -Confirm:$false $certificateName1 = "Cert_$(Get-Random)" $certificateName2 = "Cert_$(Get-Random)" $cert1 = New-DbaDbCertificate -SqlInstance $TestConfig.instance1 -Name $certificateName1 -Confirm:$false - $cert2 = New-DbaDbCertificate -SqlInstance $TestConfig.instance1 -Name $certificateName2 -Database "tempdb" -Confirm:$false + $cert2 = New-DbaDbCertificate -SqlInstance $TestConfig.instance1 -Name $certificateName2 -Database tempdb -Confirm:$false + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } + AfterAll { + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # Cleanup all created objects $null = $cert1 | Remove-DbaDbCertificate -Confirm:$false $null = $cert2 | Remove-DbaDbCertificate -Confirm:$false if ($tempdbmasterkey) { $tempdbmasterkey | Remove-DbaDbMasterKey -Confirm:$false } if ($masterKey) { $masterkey | Remove-DbaDbMasterKey -Confirm:$false } + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } - $cert = Get-DbaDbCertificate -SqlInstance $TestConfig.instance1 -Certificate $certificateName1 - It "returns database certificate created in default, master database" { - "$($cert.Database)" -match 'master' | Should Be $true + It "Returns database certificate created in default, master database" { + $cert = Get-DbaDbCertificate -SqlInstance $TestConfig.instance1 -Certificate $certificateName1 + "$($cert.Database)" -match "master" | Should -BeTrue $cert.DatabaseId | Should -Be (Get-DbaDatabase -SqlInstance $TestConfig.instance1 -Database master).Id } - $cert = Get-DbaDbCertificate -SqlInstance $TestConfig.instance1 -Database tempdb - It "returns database certificate created in tempdb database, looked up by certificate name" { - "$($cert.Name)" -match $certificateName2 | Should Be $true + It "Returns database certificate created in tempdb database, looked up by certificate name" { + $cert = Get-DbaDbCertificate -SqlInstance $TestConfig.instance1 -Database tempdb + "$($cert.Name)" -match $certificateName2 | Should -BeTrue $cert.DatabaseId | Should -Be (Get-DbaDatabase -SqlInstance $TestConfig.instance1 -Database tempdb).Id } - $cert = Get-DbaDbCertificate -SqlInstance $TestConfig.instance1 -ExcludeDatabase master - It "returns database certificates excluding those in the master database" { - "$($cert.Database)" -notmatch 'master' | Should Be $true + It "Returns database certificates excluding those in the master database" { + $cert = Get-DbaDbCertificate -SqlInstance $TestConfig.instance1 -ExcludeDatabase master + "$($cert.Database)" -notmatch "master" | Should -BeTrue } - } -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbCheckConstraint.Tests.ps1 b/tests/Get-DbaDbCheckConstraint.Tests.ps1 index e3ee27d70e7..11445275ce6 100644 --- a/tests/Get-DbaDbCheckConstraint.Tests.ps1 +++ b/tests/Get-DbaDbCheckConstraint.Tests.ps1 @@ -1,53 +1,86 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaDbCheckConstraint", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'ExcludeDatabase', 'ExcludeSystemTable', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Database", + "ExcludeDatabase", + "ExcludeSystemTable", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { - $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 - $random = Get-Random - $tableName = "dbatools_getdbtbl1" - $tableName2 = "dbatools_getdbtbl2" - $ckName = "dbatools_getdbck" - $dbname = "dbatoolsci_getdbfk$random" - $server.Query("CREATE DATABASE $dbname") - $server.Query("CREATE TABLE $tableName (idTbl1 INT PRIMARY KEY)", $dbname) - $server.Query("CREATE TABLE $tableName2 (idTbl2 INT, idTbl1 INT, id3 INT)", $dbname) - $server.Query("ALTER TABLE $tableName2 ADD CONSTRAINT $ckName CHECK (id3 > 10)", $dbname) + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # Set up test database and tables for check constraint testing + $testServer = Connect-DbaInstance -SqlInstance $TestConfig.instance2 + $random = Get-Random + $testTableName1 = "dbatools_getdbtbl1" + $testTableName2 = "dbatools_getdbtbl2" + $testCkName = "dbatools_getdbck" + $testDbName = "dbatoolsci_getdbfk$random" + + $testServer.Query("CREATE DATABASE $testDbName") + $testServer.Query("CREATE TABLE $testTableName1 (idTbl1 INT PRIMARY KEY)", $testDbName) + $testServer.Query("CREATE TABLE $testTableName2 (idTbl2 INT, idTbl1 INT, id3 INT)", $testDbName) + $testServer.Query("ALTER TABLE $testTableName2 ADD CONSTRAINT $testCkName CHECK (id3 > 10)", $testDbName) + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } AfterAll { - $null = Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname | Remove-DbaDatabase -Confirm:$false + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # Cleanup test database + $null = Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $testDbName | Remove-DbaDatabase -Confirm:$false -ErrorAction SilentlyContinue + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } Context "Command actually works" { It "returns no check constraints from excluded DB with -ExcludeDatabase" { $results = Get-DbaDbCheckConstraint -SqlInstance $TestConfig.instance2 -ExcludeDatabase master - $results.where( { $_.Database -eq 'master' }).count | Should Be 0 + $results | Where-Object { $PSItem.Database -eq "master" } | Should -BeNullOrEmpty } + It "returns only check constraints from selected DB with -Database" { - $results = Get-DbaDbCheckConstraint -SqlInstance $TestConfig.instance2 -Database $dbname - $results.where( { $_.Database -ne 'master' }).count | Should Be 1 - $results.DatabaseId | Get-Unique | Should -Be (Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname).Id + $results = Get-DbaDbCheckConstraint -SqlInstance $TestConfig.instance2 -Database $testDbName + $results | Where-Object { $PSItem.Database -ne "master" } | Should -HaveCount 1 + $results.DatabaseId | Get-Unique | Should -Be (Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $testDbName).Id } - It "Should include test check constraint: $ckName" { - $results = Get-DbaDbCheckConstraint -SqlInstance $TestConfig.instance2 -Database $dbname -ExcludeSystemTable - ($results | Where-Object Name -eq $ckName).Name | Should Be $ckName + + It "Should include test check constraint: $testCkName" { + $results = Get-DbaDbCheckConstraint -SqlInstance $TestConfig.instance2 -Database $testDbName -ExcludeSystemTable + $results | Where-Object Name -eq $testCkName | Select-Object -ExpandProperty Name | Should -Be $testCkName } + It "Should exclude system tables" { $results = Get-DbaDbCheckConstraint -SqlInstance $TestConfig.instance2 -Database master -ExcludeSystemTable - ($results | Where-Object Name -eq 'spt_fallback_db') | Should Be $null + $results | Where-Object Name -eq "spt_fallback_db" | Should -BeNullOrEmpty } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbCompatibility.Tests.ps1 b/tests/Get-DbaDbCompatibility.Tests.ps1 index b8520b86924..371db396dde 100644 --- a/tests/Get-DbaDbCompatibility.Tests.ps1 +++ b/tests/Get-DbaDbCompatibility.Tests.ps1 @@ -1,47 +1,73 @@ -$commandname = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaDbCompatibility", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'InputObject', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Database", + "InputObject", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { $server = Connect-DbaInstance -SqlInstance $TestConfig.instance1 - $compatibilityLevel = $server.Databases['master'].CompatibilityLevel + $compatibilityLevel = $server.Databases["master"].CompatibilityLevel } + Context "Gets compatibility for multiple databases" { - $results = Get-DbaDbCompatibility -SqlInstance $TestConfig.instance1 + BeforeAll { + $results = Get-DbaDbCompatibility -SqlInstance $TestConfig.instance1 + } + It "Gets results" { - $results | Should Not Be $null + $results | Should -Not -BeNullOrEmpty } - Foreach ($row in $results) { - It "Should return correct compatibility level for $($row.database)" { + + It "Should return correct compatibility level for system databases" { + foreach ($row in $results) { # Only test system databases as there might be leftover databases from other tests if ($row.DatabaseId -le 4) { - $row.Compatibility | Should Be $compatibilityLevel + $row.Compatibility | Should -Be $compatibilityLevel } - $row.DatabaseId | Should -Be (Get-DbaDatabase -SqlInstance $TestConfig.instance1 -Database $row.Database).Id + $dbId = (Get-DbaDatabase -SqlInstance $TestConfig.instance1 -Database $row.Database).Id + $row.DatabaseId | Should -Be $dbId } } } + Context "Gets compatibility for one database" { - $results = Get-DbaDbCompatibility -SqlInstance $TestConfig.instance1 -database master + BeforeAll { + $results = Get-DbaDbCompatibility -SqlInstance $TestConfig.instance1 -Database master + } It "Gets results" { - $results | Should Not Be $null + $results | Should -Not -BeNullOrEmpty } - It "Should return correct compatibility level for $($results.database)" { - $results.Compatibility | Should Be $compatibilityLevel - $results.DatabaseId | Should -Be (Get-DbaDatabase -SqlInstance $TestConfig.instance1 -Database master).Id + + It "Should return correct compatibility level for master database" { + $results.Compatibility | Should -Be $compatibilityLevel + $masterDbId = (Get-DbaDatabase -SqlInstance $TestConfig.instance1 -Database master).Id + $results.DatabaseId | Should -Be $masterDbId } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbCompression.Tests.ps1 b/tests/Get-DbaDbCompression.Tests.ps1 index e6eb3bb58cd..b163d3ba3cf 100644 --- a/tests/Get-DbaDbCompression.Tests.ps1 +++ b/tests/Get-DbaDbCompression.Tests.ps1 @@ -1,20 +1,39 @@ -$commandname = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaDbCompression", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'ExcludeDatabase', 'Table', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Database", + "ExcludeDatabase", + "Table", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + $dbname = "dbatoolsci_test_$(Get-Random)" $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 $null = $server.Query("Create Database [$dbname]") @@ -22,39 +41,60 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { select * into sysallparams from sys.all_parameters create clustered index CL_sysallparams on sysallparams (object_id) create nonclustered index NC_syscols on syscols (precision) include (collation_name)", $dbname) + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } AfterAll { + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + Get-DbaProcess -SqlInstance $TestConfig.instance2 -Database $dbname | Stop-DbaProcess -WarningAction SilentlyContinue - Remove-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname -Confirm:$false - } - $results = Get-DbaDbCompression -SqlInstance $TestConfig.instance2 -Database $dbname + Remove-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname -ErrorAction SilentlyContinue + # As this is the last block we do not need to reset the $PSDefaultParameterValues. + } Context "Command handles heaps and clustered indexes" { + BeforeAll { + $results = Get-DbaDbCompression -SqlInstance $TestConfig.instance2 -Database $dbname + $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 + } It "Gets results" { - $results | Should Not Be $null + $results | Should -Not -BeNullOrEmpty $results.Database | Get-Unique | Should -Be $dbname $results.DatabaseId | Get-Unique | Should -Be $server.Query("SELECT database_id FROM sys.databases WHERE name = '$dbname'").database_id } - Foreach ($row in $results | Where-Object { $_.IndexId -le 1 }) { - It "Should return compression level for object $($row.TableName)" { - $row.DataCompression | Should BeIn ('None', 'Row', 'Page') + It "Should return compression level for heaps and clustered indexes" { + $heapAndClusteredResults = $results | Where-Object { $PSItem.IndexId -le 1 } + foreach ($row in $heapAndClusteredResults) { + $row.DataCompression | Should -BeIn @("None", "Row", "Page") } } } Context "Command handles nonclustered indexes" { + BeforeAll { + $ncResults = Get-DbaDbCompression -SqlInstance $TestConfig.instance2 -Database $dbname + } + It "Gets results" { - $results | Should Not Be $null + $ncResults | Should -Not -BeNullOrEmpty } - Foreach ($row in $results | Where-Object { $_.IndexId -gt 1 }) { - It "Should return compression level for nonclustered index $($row.IndexName)" { - $row.DataCompression | Should BeIn ('None', 'Row', 'Page') + + It "Should return compression level for nonclustered indexes" { + $nonclustered = $ncResults | Where-Object { $PSItem.IndexId -gt 1 } + foreach ($row in $nonclustered) { + $row.DataCompression | Should -BeIn @("None", "Row", "Page") } } } Context "Command excludes results for specified database" { + BeforeAll { + $excludeResults = Get-DbaDbCompression -SqlInstance $TestConfig.instance2 -Database $dbname -ExcludeDatabase $dbname + } + It "Shouldn't get any results for $dbname" { - $(Get-DbaDbCompression -SqlInstance $TestConfig.instance2 -Database $dbname -ExcludeDatabase $dbname) | Should not Match $dbname + $excludeResults.Database | Should -Not -Contain $dbname } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbDbccOpenTran.Tests.ps1 b/tests/Get-DbaDbDbccOpenTran.Tests.ps1 index 1f4fffeb4c2..c34e5a4057a 100644 --- a/tests/Get-DbaDbDbccOpenTran.Tests.ps1 +++ b/tests/Get-DbaDbDbccOpenTran.Tests.ps1 @@ -1,44 +1,71 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaDbDbccOpenTran", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Database", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Test" -Tag "IntegrationTests" { + +Describe $CommandName -Tag IntegrationTests { Context "Gets results for Open Transactions" { - $props = 'ComputerName', 'InstanceName', 'SqlInstance', 'Database', 'Cmd', 'Output', 'Field', 'Data' - $result = Get-DbaDbDbccOpenTran -SqlInstance $TestConfig.instance1 + BeforeAll { + $props = @( + "ComputerName", + "InstanceName", + "SqlInstance", + "Database", + "Cmd", + "Output", + "Field", + "Data" + ) + } It "returns results for DBCC OPENTRAN" { - $result | Should Not Be $null + $result = Get-DbaDbDbccOpenTran -SqlInstance $TestConfig.instance1 + $result | Should -Not -BeNullOrEmpty } It "returns multiple results" { - $result.Count -gt 0 | Should Be $true + $result = Get-DbaDbDbccOpenTran -SqlInstance $TestConfig.instance1 + $result.Count | Should -BeGreaterThan 0 } - foreach ($prop in $props) { - $p = $result[0].PSObject.Properties[$prop] - It "Should return property: $prop" { - $p.Name | Should Be $prop + It "Should return all expected properties" { + $result = Get-DbaDbDbccOpenTran -SqlInstance $TestConfig.instance1 + foreach ($prop in $props) { + $result[0].PSObject.Properties[$prop].Name | Should -Be $prop } } - $result = Get-DbaDbDbccOpenTran -SqlInstance $TestConfig.instance1 -Database tempDB - $tempDB = Get-DbaDatabase -SqlInstance $TestConfig.instance1 -Database tempDB + It "returns results for a specific database" { + $result = Get-DbaDbDbccOpenTran -SqlInstance $TestConfig.instance1 -Database tempDB + $tempDB = Get-DbaDatabase -SqlInstance $TestConfig.instance1 -Database tempDB - It "returns results for a database" { - $result | Should Not Be $null - $result.Database | Get-Unique | Should -Be tempDB + $result | Should -Not -BeNullOrEmpty + $result.Database | Get-Unique | Should -Be "tempDB" $result.DatabaseId | Get-Unique | Should -Be $tempDB.Id } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbDetachedFileInfo.Tests.ps1 b/tests/Get-DbaDbDetachedFileInfo.Tests.ps1 index e0fdbca14ce..e1db3416fb6 100644 --- a/tests/Get-DbaDbDetachedFileInfo.Tests.ps1 +++ b/tests/Get-DbaDbDetachedFileInfo.Tests.ps1 @@ -1,26 +1,40 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaDbDetachedFileInfo", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', '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 $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Path", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 $versionName = $server.GetSqlServerVersionName() $random = Get-Random $dbname = "dbatoolsci_detatch_$random" $server.Query("CREATE DATABASE $dbname") - $path = (Get-DbaDbFile -SqlInstance $TestConfig.instance2 -Database $dbname | Where-object {$_.PhysicalName -like '*.mdf'}).physicalname + $path = (Get-DbaDbFile -SqlInstance $TestConfig.instance2 -Database $dbname | Where-Object PhysicalName -like "*.mdf").PhysicalName Detach-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname -Force } @@ -32,21 +46,28 @@ Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { } Context "Command actually works" { - $results = Get-DbaDbDetachedFileInfo -SqlInstance $TestConfig.instance2 -Path $path - it "Gets Results" { - $results | Should Not Be $null + BeforeAll { + $results = Get-DbaDbDetachedFileInfo -SqlInstance $TestConfig.instance2 -Path $path + } + + It "Gets Results" { + $results | Should -Not -BeNullOrEmpty } + It "Should be created database" { - $results.name | Should Be $dbname + $results.Name | Should -Be $dbname } + It "Should be the correct version" { - $results.version | Should Be $versionName + $results.Version | Should -Be $versionName } + It "Should have Data files" { - $results.DataFiles | Should Not Be $null + $results.DataFiles | Should -Not -BeNullOrEmpty } + It "Should have Log files" { - $results.LogFiles | Should Not Be $null + $results.LogFiles | Should -Not -BeNullOrEmpty } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbEncryption.Tests.ps1 b/tests/Get-DbaDbEncryption.Tests.ps1 index 8644af134ab..f31cad0d31e 100644 --- a/tests/Get-DbaDbEncryption.Tests.ps1 +++ b/tests/Get-DbaDbEncryption.Tests.ps1 @@ -1,14 +1,30 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaDbEncryption", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'ExcludeDatabase', 'IncludeSystemDBs', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Database", + "ExcludeDatabase", + "IncludeSystemDBs", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } @@ -17,20 +33,34 @@ Describe "$CommandName Unit Tests" -Tag 'UnitTests' { Read https://github.com/dataplat/dbatools/blob/development/contributing.md#tests for more guidence. #> -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { Context "Test Retriving Certificate" { BeforeAll { $random = Get-Random $cert = "dbatoolsci_getcert$random" $password = ConvertTo-SecureString -String Get-Random -AsPlainText -Force - New-DbaDbCertificate -SqlInstance $TestConfig.instance1 -Name $cert -password $password + + $splatCertificate = @{ + SqlInstance = $TestConfig.instance1 + Name = $cert + Password = $password + } + New-DbaDbCertificate @splatCertificate + + $results = Get-DbaDbEncryption -SqlInstance $TestConfig.instance1 } + AfterAll { - Get-DbaDbCertificate -SqlInstance $TestConfig.instance1 -Certificate $cert | Remove-DbaDbCertificate -confirm:$false + $splatRemove = @{ + SqlInstance = $TestConfig.instance1 + Certificate = $cert + Confirm = $false + } + Get-DbaDbCertificate @splatRemove | Remove-DbaDbCertificate -Confirm:$false } - $results = Get-DbaDbEncryption -SqlInstance $TestConfig.instance1 + It "Should find a certificate named $cert" { - ($results.Name -match 'dbatoolsci').Count -gt 0 | Should Be $true + ($results.Name -match "dbatoolsci").Count -gt 0 | Should -Be $true } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbEncryptionKey.Tests.ps1 b/tests/Get-DbaDbEncryptionKey.Tests.ps1 index cc6915dbfe2..c2419ec8f8b 100644 --- a/tests/Get-DbaDbEncryptionKey.Tests.ps1 +++ b/tests/Get-DbaDbEncryptionKey.Tests.ps1 @@ -1,59 +1,105 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaDbEncryptionKey", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tags "UnitTests" { +Describe $CommandName -Tag UnitTests { Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'InputObject', 'EnableException', 'ExcludeDatabase' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Database", + "ExcludeDatabase", + "InputObject", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { - $PSDefaultParameterValues["*:Confirm"] = $false - $passwd = ConvertTo-SecureString "dbatools.IO" -AsPlainText -Force - $masterkey = Get-DbaDbMasterKey -SqlInstance $TestConfig.instance2 -Database master - if (-not $masterkey) { - $delmasterkey = $true - $masterkey = New-DbaServiceMasterKey -SqlInstance $TestConfig.instance2 -SecurePassword $passwd - } - $mastercert = Get-DbaDbCertificate -SqlInstance $TestConfig.instance2 -Database master | Where-Object Name -notmatch "##" | Select-Object -First 1 - if (-not $mastercert) { - $delmastercert = $true - $mastercert = New-DbaDbCertificate -SqlInstance $TestConfig.instance2 - } - - $db = New-DbaDatabase -SqlInstance $TestConfig.instance2 - $db | New-DbaDbMasterKey -SecurePassword $passwd - $db | New-DbaDbCertificate - $db | New-DbaDbEncryptionKey -Force + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # For all the backups that we want to clean up after the test, we create a directory that we can delete at the end. + # Other files can be written there as well, maybe we change the name of that variable later. But for now we focus on backups. + $backupPath = "$($TestConfig.Temp)\$CommandName-$(Get-Random)" + $null = New-Item -Path $backupPath -ItemType Directory + + # Explain what needs to be set up for the test: + # We need to create a database with encryption key which requires a service master key and certificate + + # Set variables. They are available in all the It blocks. + $encryptionPassword = ConvertTo-SecureString "dbatools.IO" -AsPlainText -Force + $shouldDeleteMasterKey = $false + $shouldDeleteMasterCert = $false + $testDbName = "dbatoolsci_encryptiontest_$(Get-Random)" + + # Create the objects. + $masterKey = Get-DbaDbMasterKey -SqlInstance $TestConfig.instance2 -Database master + if (-not $masterKey) { + $shouldDeleteMasterKey = $true + $masterKey = New-DbaServiceMasterKey -SqlInstance $TestConfig.instance2 -SecurePassword $encryptionPassword + } + + $masterCert = Get-DbaDbCertificate -SqlInstance $TestConfig.instance2 -Database master | Where-Object Name -notmatch "##" | Select-Object -First 1 + if (-not $masterCert) { + $shouldDeleteMasterCert = $true + $masterCert = New-DbaDbCertificate -SqlInstance $TestConfig.instance2 + } + + $testDb = New-DbaDatabase -SqlInstance $TestConfig.instance2 -Name $testDbName + $testDb | New-DbaDbMasterKey -SecurePassword $encryptionPassword + $testDb | New-DbaDbCertificate + $testDb | New-DbaDbEncryptionKey -Force + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } AfterAll { - if ($db) { - $db | Remove-DbaDatabase + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # Cleanup all created objects. + if ($testDb) { + $testDb | Remove-DbaDatabase } - if ($delmastercert) { - $mastercert | Remove-DbaDbCertificate + if ($shouldDeleteMasterCert) { + $masterCert | Remove-DbaDbCertificate } - if ($delmasterkey) { - $masterkey | Remove-DbaDbMasterKey + if ($shouldDeleteMasterKey) { + $masterKey | Remove-DbaDbMasterKey } + + # Remove the backup directory. + Remove-Item -Path $backupPath -Recurse -ErrorAction SilentlyContinue + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } Context "Command actually works" { It "should get an encryption key on a database using piping" { - $results = $db | Get-DbaDbEncryptionKey - $results.EncryptionType | Should -Be "ServerCertificate" + $encryptionKeyResults = $testDb | Get-DbaDbEncryptionKey + $encryptionKeyResults.EncryptionType | Should -Be "ServerCertificate" } + It "should get an encryption key on a database" { - $results = Get-DbaDbEncryptionKey -SqlInstance $TestConfig.instance2 -Database $db.Name - $results.EncryptionType | Should -Be "ServerCertificate" + $encryptionKeyResults = Get-DbaDbEncryptionKey -SqlInstance $TestConfig.instance2 -Database $testDbName + $encryptionKeyResults.EncryptionType | Should -Be "ServerCertificate" } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbExtentDiff.Tests.ps1 b/tests/Get-DbaDbExtentDiff.Tests.ps1 index f0e9e37f16f..aa87b6fae48 100644 --- a/tests/Get-DbaDbExtentDiff.Tests.ps1 +++ b/tests/Get-DbaDbExtentDiff.Tests.ps1 @@ -1,52 +1,96 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaDbExtentDiff", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'ExcludeDatabase', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Database", + "ExcludeDatabase", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { - $dbname = "dbatoolsci_test_$(get-random)" + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true + + # Set variables. They are available in all the It blocks. + $dbname = "dbatoolsci_test_$(Get-Random)" + + # Create the objects. $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 $server.Query("Create Database [$dbname]") + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove("*-Dba*:EnableException") } + AfterAll { - Remove-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname -Confirm:$false + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true + + # Cleanup all created object. + $null = Remove-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } Context "Gets Changed Extents for Multiple Databases" { - $results = Get-DbaDbExtentDiff -SqlInstance $TestConfig.instance2 + BeforeAll { + $multiDbResults = Get-DbaDbExtentDiff -SqlInstance $TestConfig.instance2 + } + It "Gets results" { - $results | Should Not Be $null + $multiDbResults | Should -Not -BeNullOrEmpty } - Foreach ($row in $results) { - It "Should have extents for $($row.DatabaseName)" { - $row.ExtentsTotal | Should BeGreaterThan 0 + + It "Should have extents for each database" { + foreach ($row in $multiDbResults) { + $row.ExtentsTotal | Should -BeGreaterThan 0 } - It "Should have extents changed for $($row.DatabaseName)" { - $row.ExtentsChanged | Should BeGreaterOrEqual 0 + } + + It "Should have extents changed for each database" { + foreach ($row in $multiDbResults) { + $row.ExtentsChanged | Should -BeGreaterOrEqual 0 } } } + Context "Gets Changed Extents for Single Database" { - $results = Get-DbaDbExtentDiff -SqlInstance $TestConfig.instance2 -Database $dbname + BeforeAll { + $singleDbResults = Get-DbaDbExtentDiff -SqlInstance $TestConfig.instance2 -Database $dbname + } + It "Gets results" { - $results | Should Not Be $null + $singleDbResults | Should -Not -BeNullOrEmpty } - It "Should have extents for $($results.DatabaseName)" { - $results.ExtentsTotal | Should BeGreaterThan 0 + + It "Should have extents for $dbname" { + $singleDbResults.ExtentsTotal | Should -BeGreaterThan 0 } - It "Should have extents changed for $($results.DatabaseName)" { - $results.ExtentsChanged | Should BeGreaterOrEqual 0 + + It "Should have extents changed for $dbname" { + $singleDbResults.ExtentsChanged | Should -BeGreaterOrEqual 0 } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbFeatureUsage.Tests.ps1 b/tests/Get-DbaDbFeatureUsage.Tests.ps1 index 8bedee400c7..5b451773733 100644 --- a/tests/Get-DbaDbFeatureUsage.Tests.ps1 +++ b/tests/Get-DbaDbFeatureUsage.Tests.ps1 @@ -1,21 +1,40 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaDbFeatureUsage", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'ExcludeDatabase', 'InputObject', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Database", + "ExcludeDatabase", + "InputObject", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { - $dbname = "dbatoolsci_test_$(get-random)" + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true + + $dbname = "dbatoolsci_test_$(Get-Random)" $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 $server.Query("Create Database [$dbname]") $server.Query("Create Table [$dbname].dbo.TestCompression @@ -23,29 +42,51 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { Column2 int PRIMARY KEY, Column3 nvarchar(18));") $server.Query("ALTER TABLE [$dbname].dbo.TestCompression REBUILD PARTITION = ALL WITH (DATA_COMPRESSION = ROW);") + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove("*-Dba*:EnableException") } + AfterAll { + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true + $server.Query("DROP Database [$dbname]") + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } + Context "Gets Feature Usage" { - $results = Get-DbaDbFeatureUsage -SqlInstance $TestConfig.instance2 + BeforeAll { + $results = Get-DbaDbFeatureUsage -SqlInstance $TestConfig.instance2 + } + It "Gets results" { - $results | Should Not Be $null + $results | Should -Not -BeNullOrEmpty } } + Context "Gets Feature Usage using -Database" { - $results = Get-DbaDbFeatureUsage -SqlInstance $TestConfig.instance2 -Database $dbname + BeforeAll { + $results = Get-DbaDbFeatureUsage -SqlInstance $TestConfig.instance2 -Database $dbname + } + It "Gets results" { - $results | Should Not Be $null + $results | Should -Not -BeNullOrEmpty } + It "Has the Feature Compression" { - $results.Feature | Should Be "Compression" + $results.Feature | Should -Be "Compression" } } + Context "Gets Feature Usage using -ExcludeDatabase" { - $results = Get-DbaDbFeatureUsage -SqlInstance $TestConfig.instance2 -ExcludeDatabase $dbname + BeforeAll { + $results = Get-DbaDbFeatureUsage -SqlInstance $TestConfig.instance2 -ExcludeDatabase $dbname + } + It "Gets results" { - $results.database | Should Not Contain $dbname + $results.database | Should -Not -Contain $dbname } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbFile.Tests.ps1 b/tests/Get-DbaDbFile.Tests.ps1 index e2da4da699f..e98919f23ec 100644 --- a/tests/Get-DbaDbFile.Tests.ps1 +++ b/tests/Get-DbaDbFile.Tests.ps1 @@ -1,48 +1,75 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaDbFile", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'ExcludeDatabase', 'FileGroup', 'InputObject', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Database", + "ExcludeDatabase", + "FileGroup", + "InputObject", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } -} -Describe "$CommandName Unit Tests" -Tag "Unit" { Context "Ensure array" { - $results = Get-Command -Name Get-DbaDbFile | Select-Object -ExpandProperty ScriptBlock - It "returns disks as an array" { + BeforeAll { + $results = Get-Command -Name Get-DbaDbFile | Select-Object -ExpandProperty ScriptBlock + } + + It "Returns disks as an array" { $results -match '\$disks \= \@\(' | Should -Be $true } } } -Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { Context "Should return file information" { - $results = Get-DbaDbFile -SqlInstance $TestConfig.instance1 - It "returns information about tempdb files" { + BeforeAll { + $results = Get-DbaDbFile -SqlInstance $TestConfig.instance1 + } + + It "Returns information about tempdb files" { $results.Database -contains "tempdb" | Should -Be $true } } Context "Should return file information for only tempdb" { - $results = Get-DbaDbFile -SqlInstance $TestConfig.instance1 -Database tempdb - foreach ($result in $results) { - It "returns only tempdb files" { + BeforeAll { + $results = Get-DbaDbFile -SqlInstance $TestConfig.instance1 -Database tempdb + } + + It "Returns only tempdb files" { + foreach ($result in $results) { $result.Database | Should -Be "tempdb" } } } Context "Should return file information for only tempdb primary filegroup" { - $results = Get-DbaDbFile -SqlInstance $TestConfig.instance1 -Database tempdb -FileGroup Primary - foreach ($result in $results) { - It "returns only tempdb files that are in Primary filegroup" { + BeforeAll { + $results = Get-DbaDbFile -SqlInstance $TestConfig.instance1 -Database tempdb -FileGroup Primary + } + + It "Returns only tempdb files that are in Primary filegroup" { + foreach ($result in $results) { $result.Database | Should -Be "tempdb" $result.FileGroupName | Should -Be "Primary" } @@ -50,24 +77,28 @@ Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { } Context "Physical name is populated" { - $results = Get-DbaDbFile -SqlInstance $TestConfig.instance1 -Database master - It "master returns proper results" { - $result = $results | Where-Object LogicalName -eq 'master' - $result.PhysicalName -match 'master.mdf' | Should -Be $true - $result = $results | Where-Object LogicalName -eq 'mastlog' - $result.PhysicalName -match 'mastlog.ldf' | Should -Be $true + BeforeAll { + $results = Get-DbaDbFile -SqlInstance $TestConfig.instance1 -Database master + } + + It "Master returns proper results" { + $result = $results | Where-Object LogicalName -eq "master" + $result.PhysicalName -match "master.mdf" | Should -Be $true + $result = $results | Where-Object LogicalName -eq "mastlog" + $result.PhysicalName -match "mastlog.ldf" | Should -Be $true } } Context "Database ID is populated" { - It "returns proper results for the master db" { + It "Returns proper results for the master db" { $results = Get-DbaDbFile -SqlInstance $TestConfig.instance1 -Database master $results.DatabaseID | Get-Unique | Should -Be (Get-DbaDatabase -SqlInstance $TestConfig.instance1 -Database master).ID } - It "uses a pipeline input and returns proper results for the tempdb" { + + It "Uses a pipeline input and returns proper results for the tempdb" { $tempDB = Get-DbaDatabase -SqlInstance $TestConfig.instance1 -Database tempdb $results = $tempDB | Get-DbaDbFile $results.DatabaseID | Get-Unique | Should -Be $tempDB.ID } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbFileGrowth.Tests.ps1 b/tests/Get-DbaDbFileGrowth.Tests.ps1 index 8ba1fe11cc9..dec45d787a7 100644 --- a/tests/Get-DbaDbFileGrowth.Tests.ps1 +++ b/tests/Get-DbaDbFileGrowth.Tests.ps1 @@ -1,30 +1,51 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaDbFileGrowth", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'InputObject', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Database", + "InputObject", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { Context "Should return file information" { - $result = Get-DbaDbFileGrowth -SqlInstance $TestConfig.instance2 + BeforeAll { + $result = Get-DbaDbFileGrowth -SqlInstance $TestConfig.instance2 + } + It "returns information about msdb files" { $result.Database -contains "msdb" | Should -Be $true } } Context "Should return file information for only msdb" { - $result = Get-DbaDbFileGrowth -SqlInstance $TestConfig.instance2 -Database msdb | Select-Object -First 1 + BeforeAll { + $result = Get-DbaDbFileGrowth -SqlInstance $TestConfig.instance2 -Database msdb | Select-Object -First 1 + } + It "returns only msdb files" { $result.Database | Should -Be "msdb" } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbFileMapping.Tests.ps1 b/tests/Get-DbaDbFileMapping.Tests.ps1 index b55c969c937..c9a9f529727 100644 --- a/tests/Get-DbaDbFileMapping.Tests.ps1 +++ b/tests/Get-DbaDbFileMapping.Tests.ps1 @@ -1,29 +1,53 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaDbFileMapping", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Context "Validate parameters" { - [array]$params = ([Management.Automation.CommandMetaData]$ExecutionContext.SessionState.InvokeCommand.GetCommand($CommandName, 'Function')).Parameters.Keys - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'InputObject', 'EnableException' +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Database", + "InputObject", + "EnableException" + ) + } - It "Should only contain our specific parameters" { - Compare-Object -ReferenceObject $knownParameters -DifferenceObject $params | Should -BeNullOrEmpty + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty + } } } -Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { Context "Should return file information" { - $results = Get-DbaDbFileMapping -SqlInstance $TestConfig.instance1 + BeforeAll { + $results = Get-DbaDbFileMapping -SqlInstance $TestConfig.instance1 + } + It "returns information about multiple databases" { $results.Database -contains "tempdb" | Should -Be $true $results.Database -contains "master" | Should -Be $true } } + Context "Should return file information for a single database" { - $results = Get-DbaDbFileMapping -SqlInstance $TestConfig.instance1 -Database tempdb + BeforeAll { + $results = Get-DbaDbFileMapping -SqlInstance $TestConfig.instance1 -Database tempdb + } + It "returns information about tempdb" { $results.Database -contains "tempdb" | Should -Be $true $results.Database -contains "master" | Should -Be $false } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbForeignKey.Tests.ps1 b/tests/Get-DbaDbForeignKey.Tests.ps1 index df30824ff26..cfbb81da904 100644 --- a/tests/Get-DbaDbForeignKey.Tests.ps1 +++ b/tests/Get-DbaDbForeignKey.Tests.ps1 @@ -1,20 +1,39 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaDbForeignKey", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'ExcludeDatabase', 'ExcludeSystemTable', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Database", + "ExcludeDatabase", + "ExcludeSystemTable", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 $random = Get-Random $tableName = "dbatools_getdbtbl1" @@ -25,40 +44,109 @@ Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { $server.Query("CREATE TABLE $tableName (idTbl1 INT PRIMARY KEY)", $dbname) $server.Query("CREATE TABLE $tableName2 (idTbl2 INT, idTbl1 INT)", $dbname) $server.Query("ALTER TABLE $tableName2 ADD CONSTRAINT $fkName FOREIGN KEY (idTbl1) REFERENCES $tableName (idTbl1) ON UPDATE NO ACTION ON DELETE NO ACTION ", $dbname) + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } AfterAll { + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + $null = Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname | Remove-DbaDatabase -Confirm:$false + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } Context "Command actually works" { It "returns no foreign keys from excluded DB with -ExcludeDatabase" { $results = Get-DbaDbForeignKey -SqlInstance $TestConfig.instance2 -ExcludeDatabase master - $results.where( { $_.Database -eq 'master' }).count | Should Be 0 + ($results | Where-Object Database -eq "master").Count | Should -BeExactly 0 } + It "returns only foreign keys from selected DB with -Database" { $results = Get-DbaDbForeignKey -SqlInstance $TestConfig.instance2 -Database $dbname - $results.where( { $_.Database -ne 'master' }).count | Should Be 1 + ($results | Where-Object Database -ne "master").Count | Should -BeExactly 1 } - It "Should include test foreign keys: $ckName" { + + It "Should include test foreign keys: $fkName" { $results = Get-DbaDbForeignKey -SqlInstance $TestConfig.instance2 -Database $dbname -ExcludeSystemTable - ($results | Where-Object Name -eq $ckName).Name | Should Be $ckName + ($results | Where-Object Name -eq $fkName).Name | Should -Be $fkName } + It "Should exclude system tables" { $results = Get-DbaDbForeignKey -SqlInstance $TestConfig.instance2 -Database master -ExcludeSystemTable - ($results | Where-Object Name -eq 'spt_fallback_db') | Should Be $null + ($results | Where-Object Name -eq "spt_fallback_db") | Should -BeNullOrEmpty } } Context "Parameters are returned correctly" { - $results = Get-DbaDbForeignKey -SqlInstance $TestConfig.instance2 -ExcludeDatabase master + BeforeAll { + $results = Get-DbaDbForeignKey -SqlInstance $TestConfig.instance2 -ExcludeDatabase master + } + It "Has the correct default properties" { - $expectedStdProps = 'ComputerName,CreateDate,Database,DateLastModified,ID,InstanceName,IsChecked,IsEnabled,Name,NotForReplication,ReferencedKey,ReferencedTable,ReferencedTableSchema,SqlInstance,Schema,Table'.split(',') - ($results[0].PSStandardMembers.DefaultDisplayPropertySet.ReferencedPropertyNames | Sort-Object) | Should Be ($ExpectedStdProps | Sort-Object) + $expectedStdProps = @( + "ComputerName", + "CreateDate", + "Database", + "DateLastModified", + "ID", + "InstanceName", + "IsChecked", + "IsEnabled", + "Name", + "NotForReplication", + "ReferencedKey", + "ReferencedTable", + "ReferencedTableSchema", + "SqlInstance", + "Schema", + "Table" + ) + ($results[0].PSStandardMembers.DefaultDisplayPropertySet.ReferencedPropertyNames | Sort-Object) | Should -Be ($expectedStdProps | Sort-Object) } + It "Has the correct properties" { - $ExpectedProps = "Columns,ComputerName,CreateDate,Database,DatabaseEngineEdition,DatabaseEngineType,DateLastModified,DeleteAction,ExecutionManager,ExtendedProperties,ID,InstanceName,IsChecked,IsDesignMode,IsEnabled,IsFileTableDefined,IsMemoryOptimized,IsSystemNamed,Name,NotForReplication,Parent,ParentCollection,Properties,ReferencedKey,ReferencedTable,ReferencedTableSchema,ScriptReferencedTable,ScriptReferencedTableSchema,ServerVersion,SqlInstance,State,Schema,Table,UpdateAction,Urn,UserData".split(',') - ($results[0].PsObject.Properties.Name | Sort-Object) | Should Be ($ExpectedProps | Sort-Object) + $expectedProps = @( + "Columns", + "ComputerName", + "CreateDate", + "Database", + "DatabaseEngineEdition", + "DatabaseEngineType", + "DateLastModified", + "DeleteAction", + "ExecutionManager", + "ExtendedProperties", + "ID", + "InstanceName", + "IsChecked", + "IsDesignMode", + "IsEnabled", + "IsFileTableDefined", + "IsMemoryOptimized", + "IsSystemNamed", + "Name", + "NotForReplication", + "Parent", + "ParentCollection", + "Properties", + "ReferencedKey", + "ReferencedTable", + "ReferencedTableSchema", + "ScriptReferencedTable", + "ScriptReferencedTableSchema", + "ServerVersion", + "SqlInstance", + "State", + "Schema", + "Table", + "UpdateAction", + "Urn", + "UserData" + ) + ($results[0].PsObject.Properties.Name | Sort-Object) | Should -Be ($expectedProps | Sort-Object) } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbIdentity.Tests.ps1 b/tests/Get-DbaDbIdentity.Tests.ps1 index 3f742cef2a0..abb8c807cb0 100644 --- a/tests/Get-DbaDbIdentity.Tests.ps1 +++ b/tests/Get-DbaDbIdentity.Tests.ps1 @@ -1,51 +1,81 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaDbIdentity", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command -Name $CommandName).Parameters.Keys - $knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'Table', 'EnableException' +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Database", + "Table", + "EnableException" + ) + } - It "Should contain our specific parameters" { - ( (Compare-Object -ReferenceObject $knownParameters -DifferenceObject $params -IncludeEqual | Where-Object SideIndicator -eq "==").Count ) | Should Be $knownParameters.Count + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Test" -Tag "IntegrationTests" { + +Describe $CommandName -Tag IntegrationTests { BeforeAll { + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + $db = Get-DbaDatabase -SqlInstance $TestConfig.instance1 -Database tempdb $null = $db.Query("CREATE TABLE dbo.dbatoolsci_example (Id int NOT NULL IDENTITY (125, 1), Value varchar(5)); INSERT INTO dbo.dbatoolsci_example(Value) Select 1; CREATE TABLE dbo.dbatoolsci_example2 (Id int NOT NULL IDENTITY (5, 1), Value varchar(5)); INSERT INTO dbo.dbatoolsci_example2(Value) Select 1;") + + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } + AfterAll { - try { - $null = $db.Query("DROP TABLE dbo.dbatoolsci_example; - DROP TABLE dbo.dbatoolsci_example2") - } catch { - $null = 1 - } + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + $null = $db.Query("DROP TABLE dbo.dbatoolsci_example; + DROP TABLE dbo.dbatoolsci_example2") -ErrorAction SilentlyContinue } - Context "Validate standard output " { - $props = 'ComputerName', 'InstanceName', 'SqlInstance', 'Database', 'Table', 'Cmd', 'IdentityValue', 'ColumnValue', 'Output' - $result = Get-DbaDbIdentity -SqlInstance $TestConfig.instance1 -Database tempdb -Table 'dbo.dbatoolsci_example', 'dbo.dbatoolsci_example2' + Context "Validate standard output" { + BeforeAll { + $props = @( + "ComputerName", + "InstanceName", + "SqlInstance", + "Database", + "Table", + "Cmd", + "IdentityValue", + "ColumnValue", + "Output" + ) + $result = Get-DbaDbIdentity -SqlInstance $TestConfig.instance1 -Database tempdb -Table "dbo.dbatoolsci_example", "dbo.dbatoolsci_example2" + } - foreach ($prop in $props) { - $p = $result[0].PSObject.Properties[$prop] - It "Should return property: $prop" { - $p.Name | Should Be $prop + It "Should return all expected properties" { + foreach ($prop in $props) { + $result[0].PSObject.Properties[$prop].Name | Should -Be $prop } } - It "returns results for each table" { - $result.Count -eq 2 | Should Be $true + It "Returns results for each table" { + $result.Count | Should -BeExactly 2 } - It "returns correct results" { - $result[0].IdentityValue -eq 125 | Should Be $true + It "Returns correct results" { + $result[0].IdentityValue | Should -BeExactly 125 } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbLogShipError.Tests.ps1 b/tests/Get-DbaDbLogShipError.Tests.ps1 index 708174bd270..f3e35b1231d 100644 --- a/tests/Get-DbaDbLogShipError.Tests.ps1 +++ b/tests/Get-DbaDbLogShipError.Tests.ps1 @@ -1,24 +1,51 @@ -$commandname = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaDbLogShipError", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'ExcludeDatabase', 'Action', 'DateTimeFrom', 'DateTimeTo', 'Primary', 'Secondary', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Database", + "ExcludeDatabase", + "Action", + "DateTimeFrom", + "DateTimeTo", + "Primary", + "Secondary", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { + BeforeAll { + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') + } + Context "Return values" { It "Get the log shipping errors" { - $Results = @() - $Results += Get-DbaDbLogShipError -SqlInstance $TestConfig.instance2 - $Results.Count | Should Be 0 + $results = @(Get-DbaDbLogShipError -SqlInstance $TestConfig.instance2) + $results.Status.Count | Should -BeExactly 0 } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbLogSpace.Tests.ps1 b/tests/Get-DbaDbLogSpace.Tests.ps1 index c238abc19a0..c61f4432ce3 100644 --- a/tests/Get-DbaDbLogSpace.Tests.ps1 +++ b/tests/Get-DbaDbLogSpace.Tests.ps1 @@ -1,77 +1,129 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaDbLogSpace", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'ExcludeDatabase', 'ExcludeSystemDatabase', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Database", + "ExcludeDatabase", + "ExcludeSystemDatabase", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { - $db1 = "dbatoolsci_{0}" -f $(Get-Random) - $dbCreate = ("CREATE DATABASE [{0}] + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # For all the backups that we want to clean up after the test, we create a directory that we can delete at the end. + # Other files can be written there as well, maybe we change the name of that variable later. But for now we focus on backups. + $backupPath = "$($TestConfig.Temp)\$CommandName-$(Get-Random)" + $null = New-Item -Path $backupPath -ItemType Directory + + # Explain what needs to be set up for the test: + # To test Get-DbaDbLogSpace, we need a database with a specific log file size configuration. + + # Set variables. They are available in all the It blocks. + $db1 = "dbatoolsci_$(Get-Random)" + $dbCreate = "CREATE DATABASE [$db1] GO - ALTER DATABASE [{0}] MODIFY FILE ( NAME = N'{0}_log', SIZE = 10MB )" -f $db1) + ALTER DATABASE [$db1] MODIFY FILE ( NAME = N'$($db1)_log', SIZE = 10MB )" $null = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Database master -Query $dbCreate + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } + AfterAll { - Remove-DbaDatabase -Confirm:$false -SqlInstance $TestConfig.instance2 -Database $db1 + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # Cleanup all created object. + $null = Remove-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $db1 + + # Remove the backup directory. + Remove-Item -Path $backupPath -Recurse -ErrorAction SilentlyContinue + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } Context "Command actually works" { - $results = Get-DbaDbLogSpace -SqlInstance $TestConfig.instance2 -Database $db1 + BeforeAll { + $results = Get-DbaDbLogSpace -SqlInstance $TestConfig.instance2 -Database $db1 + } + It "Should have correct properties" { - $results | Should Not BeNullOrEmpty + $results | Should -Not -BeNullOrEmpty } It "Should have database name of $db1" { - $results.Database | Should Contain $db1 + $results.Database | Should -Contain $db1 } It "Should show correct log file size for $db1" { - ($results | Where-Object { $_.Database -eq $db1 }).LogSize.Kilobyte | Should Be 10232 + ($results | Where-Object Database -eq $db1).LogSize.Kilobyte | Should -BeExactly 10232 } - if ((Connect-DbaInstance -SqlInstance $TestConfig.instance2 -SqlCredential $SqlCredential).versionMajor -lt 11) { - It "Calculation for space used should work for servers < 2012" { - $db1Result = $results | Where-Object { $_.Database -eq $db1 } - $db1Result.logspaceused | should be ($db1Result.logsize * ($db1Result.LogSpaceUsedPercent / 100)) - } + It "Calculation for space used should work for servers < 2012" -Skip:$((Connect-DbaInstance -SqlInstance $TestConfig.instance2).versionMajor -ge 11) { + $db1Result = $results | Where-Object Database -eq $db1 + $db1Result.LogSpaceUsed | Should -Be ($db1Result.LogSize * ($db1Result.LogSpaceUsedPercent / 100)) } } Context "System databases exclusions work" { - $results = Get-DbaDbLogSpace -SqlInstance $TestConfig.instance2 -ExcludeSystemDatabase + BeforeAll { + $results = Get-DbaDbLogSpace -SqlInstance $TestConfig.instance2 -ExcludeSystemDatabase + } + It "Should exclude system databases" { - $results.Database | Should Not Bein ('model', 'master', 'tempdb', 'msdb') + $results.Database | Should -Not -BeIn @("model", "master", "tempdb", "msdb") } + It "Should still contain $db1" { - $results.Database | Should Contain $db1 + $results.Database | Should -Contain $db1 } } Context "User databases exclusions work" { - $results = Get-DbaDbLogSpace -SqlInstance $TestConfig.instance2 -ExcludeDatabase db1 + BeforeAll { + $results = Get-DbaDbLogSpace -SqlInstance $TestConfig.instance2 -ExcludeDatabase $db1 + } + It "Should include system databases" { - ('model', 'master', 'tempdb', 'msdb') | Should Bein $results.Database + @("model", "master", "tempdb", "msdb") | Should -BeIn $results.Database } + It "Should not contain $db1" { - $results.Database | Should Contain $db1 + $results.Database | Should -Not -Contain $db1 } } Context "Piping servers works" { - $results = $TestConfig.instance2 | Get-DbaDbLogSpace + BeforeAll { + $results = $TestConfig.instance2 | Get-DbaDbLogSpace + } + It "Should have database name of $db1" { - $results.Database | Should Contain $db1 + $results.Database | Should -Contain $db1 } } - -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbccHelp.Tests.ps1 b/tests/Get-DbaDbccHelp.Tests.ps1 index dbb0f3bc2d5..7b54ab917cc 100644 --- a/tests/Get-DbaDbccHelp.Tests.ps1 +++ b/tests/Get-DbaDbccHelp.Tests.ps1 @@ -1,42 +1,65 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaDbccHelp", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { +Describe $CommandName -Tag UnitTests { Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Statement', 'IncludeUndocumented', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Statement", + "IncludeUndocumented", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Test" -Tag "IntegrationTests" { - $props = 'Operation', 'Cmd', 'Output' - $result = Get-DbaDbccHelp -SqlInstance $TestConfig.instance2 -Statement FREESYSTEMCACHE + +Describe $CommandName -Tag IntegrationTests { + BeforeAll { + $props = @("Operation", "Cmd", "Output") + $result = Get-DbaDbccHelp -SqlInstance $TestConfig.instance2 -Statement FREESYSTEMCACHE + } Context "Validate standard output" { - foreach ($prop in $props) { - $p = $result.PSObject.Properties[$prop] - It "Should return property: $prop" { - $p.Name | Should Be $prop - } + It "Should return property: Operation" { + $result.PSObject.Properties["Operation"].Name | Should -Be "Operation" + } + + It "Should return property: Cmd" { + $result.PSObject.Properties["Cmd"].Name | Should -Be "Cmd" + } + + It "Should return property: Output" { + $result.PSObject.Properties["Output"].Name | Should -Be "Output" } } Context "Works correctly" { It "returns the right results for FREESYSTEMCACHE" { - $result.Operation | Should Be 'FREESYSTEMCACHE' - $result.Cmd | Should Be 'DBCC HELP(FREESYSTEMCACHE)' - $result.Output | Should Not Be $null + $result.Operation | Should -Be "FREESYSTEMCACHE" + $result.Cmd | Should -Be "DBCC HELP(FREESYSTEMCACHE)" + $result.Output | Should -Not -BeNullOrEmpty } It "returns the right results for PAGE" { - $result = Get-DbaDbccHelp -SqlInstance $TestConfig.instance2 -Statement PAGE -IncludeUndocumented - $result.Operation | Should Be 'PAGE' - $result.Cmd | Should Be 'DBCC HELP(PAGE)' - $result.Output | Should Not Be $null + $pageResult = Get-DbaDbccHelp -SqlInstance $TestConfig.instance2 -Statement PAGE -IncludeUndocumented + $pageResult.Operation | Should -Be "PAGE" + $pageResult.Cmd | Should -Be "DBCC HELP(PAGE)" + $pageResult.Output | Should -Not -BeNullOrEmpty } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbccMemoryStatus.Tests.ps1 b/tests/Get-DbaDbccMemoryStatus.Tests.ps1 index e93cd511529..738c49ac71d 100644 --- a/tests/Get-DbaDbccMemoryStatus.Tests.ps1 +++ b/tests/Get-DbaDbccMemoryStatus.Tests.ps1 @@ -1,33 +1,75 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaDbccMemoryStatus", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Test" -Tag "IntegrationTests" { - $props = 'ComputerName', 'InstanceName', 'RecordSet', 'RowId', 'RecordSetId', 'Type', 'Name', 'Value', 'ValueType' - $result = Get-DbaDbccMemoryStatus -SqlInstance $TestConfig.instance2 + +Describe $CommandName -Tag IntegrationTests { + BeforeAll { + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true + + $expectedProps = @( + "ComputerName", + "InstanceName", + "RecordSet", + "RowId", + "RecordSetId", + "Type", + "Name", + "Value", + "ValueType" + ) + + $memoryStatusResults = Get-DbaDbccMemoryStatus -SqlInstance $TestConfig.instance2 + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove("*-Dba*:EnableException") + } + + AfterAll { + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true + + # No cleanup needed for this read-only command + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. + } Context "Validate standard output" { - foreach ($prop in $props) { - $p = $result[0].PSObject.Properties[$prop] - It "Should return property: $prop" { - $p.Name | Should Be $prop + It "Should return all expected properties" { + foreach ($prop in $expectedProps) { + $p = $memoryStatusResults[0].PSObject.Properties[$prop] + $p.Name | Should -Be $prop } } } Context "Command returns proper info" { It "returns results for DBCC MEMORYSTATUS" { - $result.Count -gt 0 | Should Be $true + $memoryStatusResults.Count | Should -BeGreaterThan 0 } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbccProcCache.Tests.ps1 b/tests/Get-DbaDbccProcCache.Tests.ps1 index 4a9a745ad00..c1898281a75 100644 --- a/tests/Get-DbaDbccProcCache.Tests.ps1 +++ b/tests/Get-DbaDbccProcCache.Tests.ps1 @@ -1,33 +1,55 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaDbccProcCache", + $PSDefaultParameterValues = $TestConfig.Defaults +) -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Test" -Tag "IntegrationTests" { - $props = 'ComputerName', 'InstanceName', 'SqlInstance', 'Count', 'Used', 'Active', 'CacheSize', 'CacheUsed', 'CacheActive' - $result = Get-DbaDbccProcCache -SqlInstance $TestConfig.instance2 + +Describe $CommandName -Tag IntegrationTests { + BeforeAll { + $props = @( + "ComputerName", + "InstanceName", + "SqlInstance", + "Count", + "Used", + "Active", + "CacheSize", + "CacheUsed", + "CacheActive" + ) + $result = Get-DbaDbccProcCache -SqlInstance $TestConfig.instance2 + } Context "Validate standard output" { - foreach ($prop in $props) { - $p = $result[0].PSObject.Properties[$prop] - It "Should return property: $prop" { - $p.Name | Should Be $prop + It "Should return all expected properties" { + foreach ($prop in $props) { + $result[0].PSObject.Properties[$prop].Name | Should -Be $prop } } } Context "Command returns proper info" { - It "returns results for DBCC PROCCACHE" { - $result | Should NOt Be $null + It "Returns results for DBCC PROCCACHE" { + $result | Should -Not -BeNullOrEmpty } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbccSessionBuffer.Tests.ps1 b/tests/Get-DbaDbccSessionBuffer.Tests.ps1 index 4d2cdb0b9e7..412a072fd0f 100644 --- a/tests/Get-DbaDbccSessionBuffer.Tests.ps1 +++ b/tests/Get-DbaDbccSessionBuffer.Tests.ps1 @@ -1,69 +1,104 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaDbccSessionBuffer", + $PSDefaultParameterValues = $TestConfig.Defaults +) -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Operation', 'SessionId', 'RequestId', 'All', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Operation", + "SessionId", + "RequestId", + "All", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Test" -Tag "IntegrationTests" { + +Describe $CommandName -Tag IntegrationTests { BeforeAll { + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + $db = Get-DbaDatabase -SqlInstance $TestConfig.instance1 -Database tempdb - $queryResult = $db.Query('SELECT top 10 object_id, @@Spid as MySpid FROM sys.objects') + $queryResult = $db.Query("SELECT top 10 object_id, @@Spid as MySpid FROM sys.objects") + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } + AfterAll { - } + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true - Context "Validate standard output for all databases " { - $props = 'ComputerName', 'InstanceName', 'SqlInstance', 'SessionId', 'EventType', 'Parameters', 'EventInfo' - $result = Get-DbaDbccSessionBuffer -SqlInstance $TestConfig.instance1 -Operation InputBuffer -All + # As this is the last block we do not need to reset the $PSDefaultParameterValues. + } - It "returns results" { - $result.Count -gt 0 | Should Be $true + Context "Validate standard output for all databases" { + BeforeAll { + $propsInputBuffer = @( + "ComputerName", + "InstanceName", + "SqlInstance", + "SessionId", + "EventType", + "Parameters", + "EventInfo" + ) + $propsOutputBuffer = @( + "ComputerName", + "InstanceName", + "SqlInstance", + "SessionId", + "Buffer", + "HexBuffer" + ) + $resultInputBuffer = Get-DbaDbccSessionBuffer -SqlInstance $TestConfig.instance1 -Operation InputBuffer -All + $resultOutputBuffer = Get-DbaDbccSessionBuffer -SqlInstance $TestConfig.instance1 -Operation OutputBuffer -All } - foreach ($prop in $props) { - $p = $result[0].PSObject.Properties[$prop] - It "Should return property: $prop" { - $p.Name | Should Be $prop - } + It "Returns results for InputBuffer" { + $resultInputBuffer.Count | Should -BeGreaterThan 0 } - $props = 'ComputerName', 'InstanceName', 'SqlInstance', 'SessionId', 'Buffer', 'HexBuffer' - $result = Get-DbaDbccSessionBuffer -SqlInstance $TestConfig.instance1 -Operation OutputBuffer -All - - It "returns results" { - $result.Count -gt 0 | Should Be $true + It "Returns results for OutputBuffer" { + $resultOutputBuffer.Count | Should -BeGreaterThan 0 } - foreach ($prop in $props) { - $p = $result[0].PSObject.Properties[$prop] - It "Should return property: $prop" { - $p.Name | Should Be $prop - } + It "Should return property: <_> for InputBuffer" -ForEach $propsInputBuffer { + $resultInputBuffer[0].PSObject.Properties[$PSItem].Name | Should -Be $PSItem + } + It "Should return property: <_> for OutputBuffer" -ForEach $propsOutputBuffer { + $resultOutputBuffer[0].PSObject.Properties[$PSItem].Name | Should -Be $PSItem } } - Context "Validate returns results for SessionId " { - $spid = $queryResult[0].MySpid - $result = Get-DbaDbccSessionBuffer -SqlInstance $TestConfig.instance1 -Operation InputBuffer -SessionId $spid - - It "returns results for InputBuffer" { - $result.SessionId -eq $spid | Should Be $true + Context "Validate returns results for SessionId" { + BeforeAll { + $spid = $queryResult[0].MySpid + $resultInputBuffer = Get-DbaDbccSessionBuffer -SqlInstance $TestConfig.instance1 -Operation InputBuffer -SessionId $spid + $resultOutputBuffer = Get-DbaDbccSessionBuffer -SqlInstance $TestConfig.instance1 -Operation OutputBuffer -SessionId $spid } - $result = Get-DbaDbccSessionBuffer -SqlInstance $TestConfig.instance1 -Operation OutputBuffer -SessionId $spid + It "Returns results for InputBuffer with correct SessionId" { + $resultInputBuffer.SessionId | Should -Be $spid + } - It "returns results for OutputBuffer" { - $result.SessionId -eq $spid | Should Be $true + It "Returns results for OutputBuffer with correct SessionId" { + $resultOutputBuffer.SessionId | Should -Be $spid } } - -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbccStatistic.Tests.ps1 b/tests/Get-DbaDbccStatistic.Tests.ps1 index fbae851e1d1..3fe9662ddd6 100644 --- a/tests/Get-DbaDbccStatistic.Tests.ps1 +++ b/tests/Get-DbaDbccStatistic.Tests.ps1 @@ -1,19 +1,41 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaDbccStatistic", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'Object', 'Target', 'Option', 'NoInformationalMessages', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Database", + "Object", + "Target", + "Option", + "NoInformationalMessages", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Test" -Tag "IntegrationTests" { + +Describe $CommandName -Tag IntegrationTests { BeforeAll { + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 $random = Get-Random $tableName = "dbatools_getdbtbl1" @@ -30,91 +52,159 @@ Describe "$commandname Integration Test" -Tag "IntegrationTests" { $null = $server.Query("CREATE STATISTICS [TestStat1] ON $tableName2([idTbl2], [idTbl1], [id3])", $dbname) $null = $server.Query("CREATE STATISTICS [TestStat2] ON $tableName2([idTbl1], [idTbl2])", $dbname) $null = $server.Query("UPDATE STATISTICS $tableName", $dbname) + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } + AfterAll { + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + $null = Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname | Remove-DbaDatabase -Confirm:$false + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } - Context "Validate standard output for StatHeader option " { - $props = 'ComputerName', 'InstanceName', 'SqlInstance', 'Database', 'Object', 'Target', 'Cmd', 'Name', 'Updated', 'Rows', 'RowsSampled', 'Steps', 'Density', 'AverageKeyLength', 'StringIndex', 'FilterExpression', 'UnfilteredRows', 'PersistedSamplePercent' - $result = Get-DbaDbccStatistic -SqlInstance $TestConfig.instance2 -Database $dbname -Option StatHeader + Context "Validate standard output for StatHeader option" { + BeforeAll { + $props = @( + "ComputerName", + "InstanceName", + "SqlInstance", + "Database", + "Object", + "Target", + "Cmd", + "Name", + "Updated", + "Rows", + "RowsSampled", + "Steps", + "Density", + "AverageKeyLength", + "StringIndex", + "FilterExpression", + "UnfilteredRows", + "PersistedSamplePercent" + ) + $result = Get-DbaDbccStatistic -SqlInstance $TestConfig.instance2 -Database $dbname -Option StatHeader + } It "returns correct results" { - $result.Count -eq 3 | Should Be $true + $result.Count | Should -BeExactly 3 } - foreach ($prop in $props) { - $p = $result[0].PSObject.Properties[$prop] - It "Should return property: $prop" { - $p.Name | Should Be $prop + It "Should return all expected properties" { + foreach ($prop in $props) { + $result[0].PSObject.Properties[$prop].Name | Should -Be $prop } } } - Context "Validate standard output for DensityVector option " { - $props = 'ComputerName', 'InstanceName', 'SqlInstance', 'Database', 'Object', 'Target', 'Cmd', 'AllDensity', 'AverageLength', 'Columns' - $result = Get-DbaDbccStatistic -SqlInstance $TestConfig.instance2 -Database $dbname -Option DensityVector + Context "Validate standard output for DensityVector option" { + BeforeAll { + $props = @( + "ComputerName", + "InstanceName", + "SqlInstance", + "Database", + "Object", + "Target", + "Cmd", + "AllDensity", + "AverageLength", + "Columns" + ) + $result = Get-DbaDbccStatistic -SqlInstance $TestConfig.instance2 -Database $dbname -Option DensityVector + } It "returns results" { - $result.Count -gt 0 | Should Be $true + $result.Count | Should -BeGreaterThan 0 } - foreach ($prop in $props) { - $p = $result[0].PSObject.Properties[$prop] - It "Should return property: $prop" { - $p.Name | Should Be $prop + It "Should return all expected properties" { + foreach ($prop in $props) { + $result[0].PSObject.Properties[$prop].Name | Should -Be $prop } - } } - Context "Validate standard output for Histogram option " { - $props = 'ComputerName', 'InstanceName', 'SqlInstance', 'Database', 'Object', 'Target', 'Cmd', 'RangeHiKey', 'RangeRows', 'EqualRows', 'DistinctRangeRows', 'AverageRangeRows' - $result = Get-DbaDbccStatistic -SqlInstance $TestConfig.instance2 -Database $dbname -Option Histogram + Context "Validate standard output for Histogram option" { + BeforeAll { + $props = @( + "ComputerName", + "InstanceName", + "SqlInstance", + "Database", + "Object", + "Target", + "Cmd", + "RangeHiKey", + "RangeRows", + "EqualRows", + "DistinctRangeRows", + "AverageRangeRows" + ) + $result = Get-DbaDbccStatistic -SqlInstance $TestConfig.instance2 -Database $dbname -Option Histogram + } It "returns results" { - $result.Count -gt 0 | Should Be $true + $result.Count | Should -BeGreaterThan 0 } - foreach ($prop in $props) { - $p = $result[0].PSObject.Properties[$prop] - It "Should return property: $prop" { - $p.Name | Should Be $prop + It "Should return all expected properties" { + foreach ($prop in $props) { + $result[0].PSObject.Properties[$prop].Name | Should -Be $prop } - } } - Context "Validate standard output for StatsStream option " { - $props = 'ComputerName', 'InstanceName', 'SqlInstance', 'Database', 'Object', 'Target', 'Cmd', 'StatsStream', 'Rows', 'DataPages' - $result = Get-DbaDbccStatistic -SqlInstance $TestConfig.instance2 -Database $dbname -Option StatsStream + Context "Validate standard output for StatsStream option" { + BeforeAll { + $props = @( + "ComputerName", + "InstanceName", + "SqlInstance", + "Database", + "Object", + "Target", + "Cmd", + "StatsStream", + "Rows", + "DataPages" + ) + $result = Get-DbaDbccStatistic -SqlInstance $TestConfig.instance2 -Database $dbname -Option StatsStream + } It "returns results" { - $result.Count -gt 0 | Should Be $true + $result.Count | Should -BeGreaterThan 0 } - foreach ($prop in $props) { - $p = $result[0].PSObject.Properties[$prop] - It "Should return property: $prop" { - $p.Name | Should Be $prop + It "Should return all expected properties" { + foreach ($prop in $props) { + $result[0].PSObject.Properties[$prop].Name | Should -Be $prop } - } } - Context "Validate returns results for single Object " { - $result = Get-DbaDbccStatistic -SqlInstance $TestConfig.instance2 -Database $dbname -Object $tableName2 -Option StatsStream + Context "Validate returns results for single Object" { + BeforeAll { + $result = Get-DbaDbccStatistic -SqlInstance $TestConfig.instance2 -Database $dbname -Object $tableName2 -Option StatsStream + } It "returns results" { - $result.Count -gt 0 | Should Be $true + $result.Count | Should -BeGreaterThan 0 } } - Context "Validate returns results for single Object and Target " { - $result = Get-DbaDbccStatistic -SqlInstance $TestConfig.instance2 -Database $dbname -Object $tableName2 -Target 'TestStat2' -Option DensityVector + Context "Validate returns results for single Object and Target" { + BeforeAll { + $result = Get-DbaDbccStatistic -SqlInstance $TestConfig.instance2 -Database $dbname -Object $tableName2 -Target "TestStat2" -Option DensityVector + } It "returns results" { - $result.Count -gt 0 | Should Be $true + $result.Count | Should -BeGreaterThan 0 } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaDbccUserOption.Tests.ps1 b/tests/Get-DbaDbccUserOption.Tests.ps1 index a99ef5672fc..7054f1c66eb 100644 --- a/tests/Get-DbaDbccUserOption.Tests.ps1 +++ b/tests/Get-DbaDbccUserOption.Tests.ps1 @@ -1,43 +1,78 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaDbccUserOption", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Option', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Option", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Test" -Tag "IntegrationTests" { - $props = 'ComputerName', 'InstanceName', 'SqlInstance', 'Option', 'Value' - $result = Get-DbaDbccUserOption -SqlInstance $TestConfig.instance2 + +Describe $CommandName -Tag IntegrationTests { + BeforeAll { + $props = @("ComputerName", "InstanceName", "SqlInstance", "Option", "Value") + } Context "Validate standard output" { - foreach ($prop in $props) { - $p = $result[0].PSObject.Properties[$prop] - It "Should return property: $prop" { - $p.Name | Should Be $prop - } + BeforeAll { + $result = Get-DbaDbccUserOption -SqlInstance $TestConfig.instance2 + } + + It "Should return property: ComputerName" { + $result[0].PSObject.Properties["ComputerName"].Name | Should -Be "ComputerName" + } + + It "Should return property: InstanceName" { + $result[0].PSObject.Properties["InstanceName"].Name | Should -Be "InstanceName" + } + + It "Should return property: SqlInstance" { + $result[0].PSObject.Properties["SqlInstance"].Name | Should -Be "SqlInstance" + } + + It "Should return property: Option" { + $result[0].PSObject.Properties["Option"].Name | Should -Be "Option" + } + + It "Should return property: Value" { + $result[0].PSObject.Properties["Value"].Name | Should -Be "Value" } - } - Context "Command returns proper info" { It "returns results for DBCC USEROPTIONS" { - $result.Count -gt 0 | Should Be $true + $result.Count | Should -BeGreaterThan 0 } } Context "Accepts an Option Value" { - $result = Get-DbaDbccUserOption -SqlInstance $TestConfig.instance2 -Option ansi_nulls + BeforeAll { + $result = Get-DbaDbccUserOption -SqlInstance $TestConfig.instance2 -Option ansi_nulls + } + It "Gets results" { - $result | Should Not Be $null + $result | Should -Not -BeNullOrEmpty } + It "Returns only one result" { - $result.Option -eq 'ansi_nulls' | Should Be $true + $result.Option | Should -Be "ansi_nulls" } } -} +} \ No newline at end of file