-
Notifications
You must be signed in to change notification settings - Fork 227
Test-SqlDscIsDatabase: Check database existence #2325
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
…ent test database variable for improved readability and maintainability
WalkthroughRemoves the multi-property Test-SqlDscDatabase cmdlet and its integration test; adds Test-SqlDscIsDatabase (existence-only check) and unit/integration tests; adds a Refresh switch to Test-SqlDscDatabaseProperty; updates localization, changelog, CI test mapping, and affected tests. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
participant Caller
participant TestIsDB as Test-SqlDscIsDatabase
participant GetDB as Get-SqlDscDatabase
participant SMO as SQL Server (SMO)
Caller->>TestIsDB: Invoke Test-SqlDscIsDatabase -ServerObject $s -Name $n [-Refresh]
TestIsDB->>GetDB: Get-SqlDscDatabase -ServerObject $s -Name $n -Refresh:$Refresh
GetDB->>SMO: Query Databases (optionally Refresh collection)
SMO-->>GetDB: Database object or $null
GetDB-->>TestIsDB: Database object or $null
alt Database found
TestIsDB-->>Caller: $true
else Not found
TestIsDB-->>Caller: $false
end
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes
Possibly related PRs
Pre-merge checks❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (3 passed)
📜 Recent review detailsConfiguration used: CodeRabbit UI Review profile: CHILL Plan: Pro 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 4
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
tests/Unit/Public/Test-SqlDscIsDatabase.Tests.ps1 (1)
109-142: Remove verbose message tests.Per coding guidelines: "Do not test verbose messages, debug messages, or parameter binding behavior." This entire
Contextblock should be removed.Apply this diff:
- Context 'When calling with verbose output' { - BeforeAll { - $mockExistingDatabase = New-Object -TypeName 'Microsoft.SqlServer.Management.Smo.Database' - $mockExistingDatabase | Add-Member -MemberType 'NoteProperty' -Name 'Name' -Value 'TestDatabase' -Force - - $mockServerObject = New-Object -TypeName 'Microsoft.SqlServer.Management.Smo.Server' - $mockServerObject | Add-Member -MemberType 'NoteProperty' -Name 'InstanceName' -Value 'TestInstance' -Force - $mockServerObject | Add-Member -MemberType 'ScriptProperty' -Name 'Databases' -Value { - return @{ - 'TestDatabase' = $mockExistingDatabase - } | Add-Member -MemberType 'ScriptMethod' -Name 'Refresh' -Value { - # Mock implementation - } -PassThru -Force - } -Force - } - - It 'Should write verbose message when database exists' { - Mock -CommandName Write-Verbose - - Test-SqlDscIsDatabase -ServerObject $mockServerObject -Name 'TestDatabase' -Verbose - - # Should be called 3 times: 1 from Test-SqlDscIsDatabase, 2 from Get-SqlDscDatabase - Should -Invoke -CommandName Write-Verbose -Exactly -Times 3 -Scope It - } - - It 'Should write verbose message when database does not exist' { - Mock -CommandName Write-Verbose - - Test-SqlDscIsDatabase -ServerObject $mockServerObject -Name 'NonExistentDatabase' -Verbose - - # Should be called 3 times: 1 from Test-SqlDscIsDatabase, 2 from Get-SqlDscDatabase - Should -Invoke -CommandName Write-Verbose -Exactly -Times 3 -Scope It - } - } -As per coding guidelines
🧹 Nitpick comments (4)
CHANGELOG.md (1)
10-14: Make the removal explicitly marked as a breaking change and add a brief migration note.Improves clarity in release notes for downstream users upgrading.
Apply this wording tweak:
-- Removed public command `Test-SqlDscDatabase` as it is now redundant. The new - command `Test-SqlDscIsDatabase` provides database existence checking with a - cleaner interface. Users testing database properties should use - `Test-SqlDscDatabaseProperty` instead ([issue #2201](https://github.com/dsccommunity/SqlServerDsc/issues/2201)). +- BREAKING CHANGE: Removed public command `Test-SqlDscDatabase`. Use + `Test-SqlDscIsDatabase` to check existence. For property checks, use + `Test-SqlDscDatabaseProperty`. See [issue #2201](https://github.com/dsccommunity/SqlServerDsc/issues/2201).source/Public/Test-SqlDscIsDatabase.ps1 (3)
1-36: Add INPUTS to comment-based helpDocument pipeline input type per guidelines.
.EXAMPLE @@ .OUTPUTS `[System.Boolean]` + + .INPUTS + `[Microsoft.SqlServer.Management.Smo.Server]` + + The server object can be provided via the pipeline to **ServerObject**.As per coding guidelines.
41-56: Consider alias for migration compatibilityAdd [Alias('Test-SqlDscDatabase')] to ease the rename transition; optionally emit a localized Write-Warning when invoked via the alias.
- [OutputType([System.Boolean])] - [CmdletBinding()] + [OutputType([System.Boolean])] + [CmdletBinding()] + [Alias('Test-SqlDscDatabase')]Please confirm the old command only checked existence so the alias remains behaviorally compatible. As per PR objectives.
58-73: Error handling parity with other Test-SqlDscIs commands*Using -ErrorAction 'SilentlyContinue' may mask real connectivity/errors. Align with the pattern used in similar commands (e.g., Test-SqlDscIsLogin/IsRole): stop on unexpected errors; treat only “not found” as false.
If those commands use -ErrorAction 'Stop' and selective catch, mirror that here; otherwise keep as-is for consistency. As per coding guidelines.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (12)
CHANGELOG.md(1 hunks)azure-pipelines.yml(1 hunks)source/Public/Test-SqlDscDatabase.ps1(0 hunks)source/Public/Test-SqlDscDatabaseProperty.ps1(4 hunks)source/Public/Test-SqlDscIsDatabase.ps1(1 hunks)source/en-US/SqlServerDsc.strings.psd1(1 hunks)tests/Integration/Commands/README.md(1 hunks)tests/Integration/Commands/Test-SqlDscDatabase.Integration.Tests.ps1(0 hunks)tests/Integration/Commands/Test-SqlDscDatabaseProperty.Integration.Tests.ps1(2 hunks)tests/Integration/Commands/Test-SqlDscIsDatabase.Integration.Tests.ps1(1 hunks)tests/Unit/Public/Test-SqlDscDatabaseProperty.Tests.ps1(2 hunks)tests/Unit/Public/Test-SqlDscIsDatabase.Tests.ps1(4 hunks)
💤 Files with no reviewable changes (2)
- source/Public/Test-SqlDscDatabase.ps1
- tests/Integration/Commands/Test-SqlDscDatabase.Integration.Tests.ps1
🧰 Additional context used
📓 Path-based instructions (21)
azure-pipelines.yml
📄 CodeRabbit inference engine (.github/instructions/SqlServerDsc-guidelines.instructions.md)
azure-pipelines.yml: Integration test script files must be added to a group within the test stage in ./azure-pipelines.yml
Choose an appropriate test group number based on required dependencies in the pipeline configuration
Files:
azure-pipelines.yml
**
⚙️ CodeRabbit configuration file
**: # DSC Community GuidelinesTerminology
- Command: Public command
- Function: Private function
- Resource: DSC class-based resource
Build & Test Workflow Requirements
- Run PowerShell script files from repository root
- Setup build and test environment (once per
pwshsession):./build.ps1 -Tasks noop- Build project before running tests:
./build.ps1 -Tasks build- Always run tests in new
pwshsession:Invoke-Pester -Path @({test paths}) -Output DetailedFile Organization
- Public commands:
source/Public/{CommandName}.ps1- Private functions:
source/Private/{FunctionName}.ps1- Unit tests:
tests/Unit/{Classes|Public|Private}/{Name}.Tests.ps1- Integration tests:
tests/Integration/Commands/{CommandName}.Integration.Tests.ps1Requirements
- Follow instructions over existing code patterns
- Follow PowerShell style and test guideline instructions strictly
- Always update CHANGELOG.md Unreleased section
- Localize all strings using string keys; remove any orphaned string keys
- Check DscResource.Common before creating private functions
- Separate reusable logic into private functions
- DSC resources should always be created as class-based resources
- Add unit tests for all commands/functions/resources
- Add integration tests for all public commands and resources
Files:
azure-pipelines.ymlsource/Public/Test-SqlDscDatabaseProperty.ps1tests/Integration/Commands/Test-SqlDscDatabaseProperty.Integration.Tests.ps1source/Public/Test-SqlDscIsDatabase.ps1CHANGELOG.mdtests/Integration/Commands/Test-SqlDscIsDatabase.Integration.Tests.ps1tests/Unit/Public/Test-SqlDscIsDatabase.Tests.ps1tests/Unit/Public/Test-SqlDscDatabaseProperty.Tests.ps1source/en-US/SqlServerDsc.strings.psd1tests/Integration/Commands/README.md
source/**/*.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-localization.instructions.md)
source/**/*.ps1: Localize all Write-Debug, Write-Verbose, Write-Error, Write-Warning, and $PSCmdlet.ThrowTerminatingError() messages
Use localized string keys instead of hardcoded strings in script output/messages
Assume and use $script:localizedData for accessing localized strings
When emitting messages, reference $script:localizedData.KeyName and format with the -f operator (e.g., Write-Verbose -Message ($script:localizedData.KeyName -f $value1))
Files:
source/Public/Test-SqlDscDatabaseProperty.ps1source/Public/Test-SqlDscIsDatabase.ps1
⚙️ CodeRabbit configuration file
source/**/*.ps1: # Localization GuidelinesRequirements
- Localize all Write-Debug, Write-Verbose, Write-Error, Write-Warning and $PSCmdlet.ThrowTerminatingError() messages
- Use localized string keys, not hardcoded strings
- Assume
$script:localizedDatais availableString Files
- Commands/functions:
source/en-US/{MyModuleName}.strings.psd1- Class resources:
source/en-US/{ResourceClassName}.strings.psd1Key Naming Patterns
- Format:
Verb_FunctionName_Action(underscore separators), e.g.Get_Database_ConnectingToDatabaseString Format
ConvertFrom-StringData @' KeyName = Message with {0} placeholder. (PREFIX0001) '@String IDs
- Format:
(PREFIX####)- PREFIX: First letter of each word in class or function name (SqlSetup → SS, Get-SqlDscDatabase → GSDD)
- Number: Sequential from 0001
Usage
Write-Verbose -Message ($script:localizedData.KeyName -f $value1)
Files:
source/Public/Test-SqlDscDatabaseProperty.ps1source/Public/Test-SqlDscIsDatabase.ps1
source/Public/*.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines.instructions.md)
Place public commands in source/Public/{CommandName}.ps1
Files:
source/Public/Test-SqlDscDatabaseProperty.ps1source/Public/Test-SqlDscIsDatabase.ps1
**/*.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines.instructions.md)
Follow PowerShell style and test guideline instructions strictly
Files:
source/Public/Test-SqlDscDatabaseProperty.ps1tests/Integration/Commands/Test-SqlDscDatabaseProperty.Integration.Tests.ps1source/Public/Test-SqlDscIsDatabase.ps1tests/Integration/Commands/Test-SqlDscIsDatabase.Integration.Tests.ps1tests/Unit/Public/Test-SqlDscIsDatabase.Tests.ps1tests/Unit/Public/Test-SqlDscDatabaseProperty.Tests.ps1
**/*.{ps1,psm1}
📄 CodeRabbit inference engine (.github/instructions/SqlServerDsc-guidelines.instructions.md)
**/*.{ps1,psm1}: Public PowerShell commands must follow the {Verb}-SqlDsc{Noun} naming format
Private PowerShell functions must follow the {Verb}-{Noun} naming format
**/*.{ps1,psm1}: Use descriptive names (3+ characters, no abbreviations)
Functions must use PascalCase with approved Verb-Noun format
Parameters use PascalCase
Variables use camelCase
Keywords are lower-case
Classes use PascalCase
Include scope for script/global/environment variables: $script:, $global:, $env:
Use one space around operators (e.g., $a = 1 + 2)
Use one space between type and variable (e.g., [String] $name)
Use one space between keyword and parenthesis (e.g., if ($condition))
Newline before opening brace except for variable assignments
One newline after opening brace
Two newlines after closing brace (one if followed by another brace or continuation)
Use single quotes unless variable expansion is needed
Arrays single-line format: @('one','two','three')
Multi-line arrays: one element per line with proper indentation
Do not use unary comma in return statements to force an array
Empty hashtable as @{}
Hashtable properties each on their own line with proper indentation
Hashtable property names use PascalCase
Single-line comments start with #, capitalized, on their own line
Multi-line comments use <# #>, brackets on their own lines, text indented
No commented-out code
Always add comment-based help to all functions and scripts
Comment-based help must include SYNOPSIS, DESCRIPTION (40+ chars), PARAMETER, EXAMPLE sections before function/class
Comment-based help indentation: keywords 4 spaces, text 8 spaces
Include examples for all parameter sets and combinations in comment-based help
INPUTS: list each pipeline-accepted type with one-line description; repeat keyword per type
OUTPUTS: list each return type with one-line description; repeat keyword per type; must match [OutputType()] and actual returns
.NOTES only if critical (constraints, side effects, security, version), ≤2 short sentences
Av...
Files:
source/Public/Test-SqlDscDatabaseProperty.ps1tests/Integration/Commands/Test-SqlDscDatabaseProperty.Integration.Tests.ps1source/Public/Test-SqlDscIsDatabase.ps1tests/Integration/Commands/Test-SqlDscIsDatabase.Integration.Tests.ps1tests/Unit/Public/Test-SqlDscIsDatabase.Tests.ps1tests/Unit/Public/Test-SqlDscDatabaseProperty.Tests.ps1
**/*.{ps1,psm1,cs}
📄 CodeRabbit inference engine (.github/instructions/SqlServerDsc-guidelines.instructions.md)
Prefer SMO over T-SQL for SQL Server interactions
Files:
source/Public/Test-SqlDscDatabaseProperty.ps1tests/Integration/Commands/Test-SqlDscDatabaseProperty.Integration.Tests.ps1source/Public/Test-SqlDscIsDatabase.ps1tests/Integration/Commands/Test-SqlDscIsDatabase.Integration.Tests.ps1tests/Unit/Public/Test-SqlDscIsDatabase.Tests.ps1tests/Unit/Public/Test-SqlDscDatabaseProperty.Tests.ps1
**/*.{ps1,psm1,psd1}
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-powershell.instructions.md)
**/*.{ps1,psm1,psd1}: Use 4 spaces for indentation (no tabs)
No spaces on empty lines
Try to limit lines to 120 characters
End files with exactly one blank line
Use line endings as defined by .gitattributes
Allow a maximum of two consecutive newlines
No trailing whitespace on any line
Use UTF-8 encoding without BOM for all files
Files:
source/Public/Test-SqlDscDatabaseProperty.ps1tests/Integration/Commands/Test-SqlDscDatabaseProperty.Integration.Tests.ps1source/Public/Test-SqlDscIsDatabase.ps1tests/Integration/Commands/Test-SqlDscIsDatabase.Integration.Tests.ps1tests/Unit/Public/Test-SqlDscIsDatabase.Tests.ps1tests/Unit/Public/Test-SqlDscDatabaseProperty.Tests.ps1source/en-US/SqlServerDsc.strings.psd1
{**/*.ps1,**/*.psm1,**/*.psd1}
⚙️ CodeRabbit configuration file
{**/*.ps1,**/*.psm1,**/*.psd1}: # PowerShell GuidelinesNaming
- Use descriptive names (3+ characters, no abbreviations)
- Functions: PascalCase with Verb-Noun format using approved verbs
- Parameters: PascalCase
- Variables: camelCase
- Keywords: lower-case
- Classes: PascalCase
- Include scope for script/global/environment variables:
$script:,$global:,$env:File naming
- Class files:
###.ClassName.ps1format (e.g.001.SqlReason.ps1,004.StartupParameters.ps1)Formatting
Indentation & Spacing
- Use 4 spaces (no tabs)
- One space around operators:
$a = 1 + 2- One space between type and variable:
[String] $name- One space between keyword and parenthesis:
if ($condition)- No spaces on empty lines
- Try to limit lines to 120 characters
Braces
- Newline before opening brace (except variable assignments)
- One newline after opening brace
- Two newlines after closing brace (one if followed by another brace or continuation)
Quotes
- Use single quotes unless variable expansion is needed:
'text'vs"text $variable"Arrays
- Single line:
@('one', 'two', 'three')- Multi-line: each element on separate line with proper indentation
- Do not use the unary comma operator (
,) in return statements to force
an arrayHashtables
- Empty:
@{}- Each property on separate line with proper indentation
- Properties: Use PascalCase
Comments
- Single line:
# Comment(capitalized, on own line)- Multi-line:
<# Comment #>format (opening and closing brackets on own line), and indent text- No commented-out code
Comment-based help
- Always add comment-based help to all functions and scripts
- Comment-based help: SYNOPSIS, DESCRIPTION (40+ chars), PARAMETER, EXAMPLE sections before function/class
- Comment-based help indentation: keywords 4 spaces, text 8 spaces
- Include examples for all parameter sets and combinations
- INPUTS: List each pipeline‑accepted type (one per line) with a 1‑line description...
Files:
source/Public/Test-SqlDscDatabaseProperty.ps1tests/Integration/Commands/Test-SqlDscDatabaseProperty.Integration.Tests.ps1source/Public/Test-SqlDscIsDatabase.ps1tests/Integration/Commands/Test-SqlDscIsDatabase.Integration.Tests.ps1tests/Unit/Public/Test-SqlDscIsDatabase.Tests.ps1tests/Unit/Public/Test-SqlDscDatabaseProperty.Tests.ps1source/en-US/SqlServerDsc.strings.psd1
tests/Integration/Commands/*.Integration.Tests.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines.instructions.md)
tests/Integration/Commands/*.Integration.Tests.ps1: Place integration tests for public commands in tests/Integration/Commands/{CommandName}.Integration.Tests.ps1
Add integration tests for all public commands (and resources)Place command integration tests at tests/Integration/Commands/{CommandName}.Integration.Tests.ps1
Files:
tests/Integration/Commands/Test-SqlDscDatabaseProperty.Integration.Tests.ps1tests/Integration/Commands/Test-SqlDscIsDatabase.Integration.Tests.ps1
tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-integration-tests.instructions.md)
tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1: Do not use mocking in integration tests; run against a real environment
Cover all scenarios and code paths in integration tests
Use Get-ComputerName to determine computer names in CI
Avoid using -ExpectedMessage with Should -Throw assertions
Call commands with -Force where applicable to avoid prompting
Use -ErrorAction 'Stop' on commands so failures surface immediately
Include the required Pester setup block (SuppressMessage param, BeforeDiscovery loading DscResource.Test, and BeforeAll importing the module)
Files:
tests/Integration/Commands/Test-SqlDscDatabaseProperty.Integration.Tests.ps1tests/Integration/Commands/Test-SqlDscIsDatabase.Integration.Tests.ps1
⚙️ CodeRabbit configuration file
tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1: # Integration Tests GuidelinesRequirements
- Location Commands:
tests/Integration/Commands/{CommandName}.Integration.Tests.ps1- Location Resources:
tests/Integration/Resources/{ResourceName}.Integration.Tests.ps1- No mocking - real environment only
- Cover all scenarios and code paths
- Use
Get-ComputerNamefor computer names in CI- Avoid
ExpectedMessageforShould -Throwassertions- Only run integration tests in CI unless explicitly instructed.
- Call commands with
-Forceparameter where applicable (avoids prompting).- Use
-ErrorAction 'Stop'on commands so failures surface immediatelyRequired Setup Block
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification = 'Suppressing this rule because Script Analyzer does not understand Pester syntax.')] param () BeforeDiscovery { try { if (-not (Get-Module -Name 'DscResource.Test')) { # Assumes dependencies have been resolved, so if this module is not available, run 'noop' task. if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) { # Redirect all streams to $null, except the error stream (stream 2) & "$PSScriptRoot/../../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null } # If the dependencies have not been resolved, this will throw an error. Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' } } catch [System.IO.FileNotFoundException] { throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks noop" first.' } } BeforeAll { $script:moduleName = '{MyModuleName}' Import-Module -Name $script:moduleName -Force -ErrorAction 'Stop' }
Files:
tests/Integration/Commands/Test-SqlDscDatabaseProperty.Integration.Tests.ps1tests/Integration/Commands/Test-SqlDscIsDatabase.Integration.Tests.ps1
tests/Integration/**/*.Tests.ps1
📄 CodeRabbit inference engine (.github/instructions/SqlServerDsc-guidelines.instructions.md)
tests/Integration/**/*.Tests.ps1: Integration tests must use Connect-SqlDscDatabaseEngine with correct CI credentials to open DB sessions
Integration tests must call Disconnect-SqlDscDatabaseEngine after Connect-SqlDscDatabaseEngine
Files:
tests/Integration/Commands/Test-SqlDscDatabaseProperty.Integration.Tests.ps1tests/Integration/Commands/Test-SqlDscIsDatabase.Integration.Tests.ps1
**/*.[Tt]ests.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-pester.instructions.md)
**/*.[Tt]ests.ps1: All public commands, private functions and classes must have unit tests
All public commands and class-based resources must have integration tests
Use Pester v5 syntax only
Place executable test code only inside Describe blocks
Place assertions only in It blocks
Do not test verbose messages, debug messages, or parameter binding behavior
Pass all mandatory parameters in tests to avoid prompts
Inside It blocks, assign unused return objects to $null (unless part of a pipeline)
Invoke the tested entity from within It blocks
Keep result capture and assertions in the same It block
Avoid try/catch/finally for cleanup; use AfterAll or AfterEach instead
Avoid unnecessary remove/recreate cycles in tests
Have exactly one Describe block per file, and name it to match the tested entity
Context descriptions must start with 'When'
It descriptions must start with 'Should' and must not contain 'when'
Prefix variables used for mocks with 'mock'
Create a separate Context block for each scenario
Use nested Context blocks for complex scenarios
Define mocks in BeforeAll; use BeforeEach only when required
Place setup/teardown in the nearest appropriate BeforeAll, BeforeEach, AfterAll, or AfterEach to where it’s used
Use PascalCase for Pester keywords: Describe, Context, It, Should, BeforeAll, BeforeEach, AfterAll, AfterEach
Use -BeTrue/-BeFalse; never use -Be $true/-Be $false
Never use Assert-MockCalled; use Should -Invoke instead
Do not use 'Should -Not -Throw'; invoke commands directly
Never add an empty -MockWith block
Omit -MockWith when the mock should return $null
Set $PSDefaultParameterValues entries for Mock:ModuleName, Should:ModuleName, and InModuleScope:ModuleName
Omit the -ModuleName parameter on Pester commands
Never use Mock inside an InModuleScope block
Define variables for -ForEach in BeforeDiscovery (close to usage)
Use -ForEach only on Context and It blocks
Do not add param() inside Pester blocks when using -ForEach
Access test case properties directl...
Files:
tests/Integration/Commands/Test-SqlDscDatabaseProperty.Integration.Tests.ps1tests/Integration/Commands/Test-SqlDscIsDatabase.Integration.Tests.ps1tests/Unit/Public/Test-SqlDscIsDatabase.Tests.ps1tests/Unit/Public/Test-SqlDscDatabaseProperty.Tests.ps1
⚙️ CodeRabbit configuration file
**/*.[Tt]ests.ps1: # Tests GuidelinesCore Requirements
- All public commands, private functions and classes must have unit tests
- All public commands and class-based resources must have integration tests
- Use Pester v5 syntax only
- Test code only inside
Describeblocks- Assertions only in
Itblocks- Never test verbose messages, debug messages or parameter binding behavior
- Pass all mandatory parameters to avoid prompts
Requirements
- Inside
Itblocks, assign unused return objects to$null(unless part of pipeline)- Tested entity must be called from within the
Itblocks- Keep results and assertions in same
Itblock- Avoid try-catch-finally for cleanup, use
AfterAllorAfterEach- Avoid unnecessary remove/recreate cycles
Naming
- One
Describeblock per file matching the tested entity nameContextdescriptions start with 'When'Itdescriptions start with 'Should', must not contain 'when'- Mock variables prefix: 'mock'
Structure & Scope
- Public commands: Never use
InModuleScope(unless retrieving localized strings)- Private functions/class resources: Always use
InModuleScope- Each class method = separate
Contextblock- Each scenario = separate
Contextblock- Use nested
Contextblocks for complex scenarios- Mocking in
BeforeAll(BeforeEachonly when required)- Setup/teardown in
BeforeAll,BeforeEach/AfterAll,AfterEachclose to usageSyntax Rules
- PascalCase:
Describe,Context,It,Should,BeforeAll,BeforeEach,AfterAll,AfterEach- Use
-BeTrue/-BeFalsenever-Be $true/-Be $false- Never use
Assert-MockCalled, useShould -Invokeinstead- No
Should -Not -Throw- invoke commands directly- Never add an empty
-MockWithblock- Omit
-MockWithwhen returning$null- Set
$PSDefaultParameterValuesforMock:ModuleName,Should:ModuleName,InModuleScope:ModuleName- Omit
-ModuleNameparameter on Pester commands- Never use
Mockinside `InModuleSc...
Files:
tests/Integration/Commands/Test-SqlDscDatabaseProperty.Integration.Tests.ps1tests/Integration/Commands/Test-SqlDscIsDatabase.Integration.Tests.ps1tests/Unit/Public/Test-SqlDscIsDatabase.Tests.ps1tests/Unit/Public/Test-SqlDscDatabaseProperty.Tests.ps1
**/*.md
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-markdown.instructions.md)
**/*.md: Wrap lines at word boundaries when over 80 characters (except tables/code blocks)
Use 2 spaces for indentation in Markdown documents
Use '1.' for all items in ordered lists (1/1/1 numbering style)
Disable MD013 for tables/code blocks exceeding 80 characters via an inline comment
Require empty lines before and after code blocks and headings (except before line 1)
Escape backslashes in file paths only, not inside code blocks
All fenced code blocks must specify a language identifier
Format parameter names as bold
Format values/literals as inline code
Format resource/module/product names as italic
Format commands, file names, and paths as inline code
Files:
CHANGELOG.mdtests/Integration/Commands/README.md
⚙️ CodeRabbit configuration file
**/*.md: # Markdown Style Guidelines
- Wrap lines at word boundaries when over 80 characters (except tables/code blocks)
- Use 2 spaces for indentation
- Use '1.' for all items in ordered lists (1/1/1 numbering style)
- Disable
MD013rule by adding a comment for tables/code blocks exceeding 80 characters- Empty lines required before/after code blocks and headings (except before line 1)
- Escape backslashes in file paths only (not in code blocks)
- Code blocks must specify language identifiers
Text Formatting
- Parameters: bold
- Values/literals:
inline code- Resource/module/product names: italic
- Commands/files/paths:
inline code
Files:
CHANGELOG.mdtests/Integration/Commands/README.md
CHANGELOG.md
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-changelog.instructions.md)
CHANGELOG.md: Always update the Unreleased section in CHANGELOG.md
Use Keep a Changelog format
Describe notable changes briefly, with no more than 2 items per change type
Reference issues using the format issue #<issue_number>
No empty lines between list items in the same section
Skip adding an entry if the same change already exists in the Unreleased section
No duplicate sections or items in the Unreleased sectionAlways update the Unreleased section of CHANGELOG.md
Files:
CHANGELOG.md
⚙️ CodeRabbit configuration file
CHANGELOG.md: # Changelog Guidelines
- Always update the Unreleased section in CHANGELOG.md
- Use Keep a Changelog format
- Describe notable changes briefly, ≤2 items per change type
- Reference issues using format issue #<issue_number>
- No empty lines between list items in same section
- Skip adding entry if same change already exists in Unreleased section
- No duplicate sections or items in Unreleased section
Files:
CHANGELOG.md
tests/[Uu]nit/**/*.[Tt]ests.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-unit-tests.instructions.md)
tests/[Uu]nit/**/*.[Tt]ests.ps1: In unit tests, access localized strings using InModuleScope -ScriptBlock { $script:localizedData.Key }
When mocking files in tests, use the $TestDrive variable for file system operations
All public commands must include parameter set validation tests
Include the exact Pester setup block before Describe: SuppressMessage attribute with param (); BeforeDiscovery to ensure DscResource.Test is available (fallback to build.ps1 -Tasks 'noop') and Import-Module; BeforeAll to set $script:moduleName, import the module, and set PSDefaultParameterValues for InModuleScope/Mock/Should; AfterAll to remove those defaults and unload the tested module
Use the provided Parameter Set Validation test template to assert command ParameterSetName and full parameter list string; for multiple parameter sets, supply multiple hashtables via -ForEach
Use the Parameter Properties template to assert a parameter is mandatory via $parameterInfo = (Get-Command -Name 'CommandName').Parameters['ParameterName']; $parameterInfo.Attributes.Mandatory | Should -BeTrue
Files:
tests/Unit/Public/Test-SqlDscIsDatabase.Tests.ps1tests/Unit/Public/Test-SqlDscDatabaseProperty.Tests.ps1
⚙️ CodeRabbit configuration file
tests/[Uu]nit/**/*.[Tt]ests.ps1: # Unit Tests Guidelines
- Test with localized strings: Use
InModuleScope -ScriptBlock { $script:localizedData.Key }- Mock files: Use
$TestDrivevariable (path to the test drive)- All public commands require parameter set validation tests
- After modifying classes, always run tests in new session (for changes to take effect)
Test Setup Requirements
Use this exact setup block before
Describe:[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification = 'Suppressing this rule because Script Analyzer does not understand Pester syntax.')] param () BeforeDiscovery { try { if (-not (Get-Module -Name 'DscResource.Test')) { # Assumes dependencies have been resolved, so if this module is not available, run 'noop' task. if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) { # Redirect all streams to $null, except the error stream (stream 2) & "$PSScriptRoot/../../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null } # If the dependencies have not been resolved, this will throw an error. Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' } } catch [System.IO.FileNotFoundException] { throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks noop" first.' } } BeforeAll { $script:moduleName = '{MyModuleName}' Import-Module -Name $script:moduleName -Force -ErrorAction 'Stop' $PSDefaultParameterValues['InModuleScope:ModuleName'] = $script:moduleName $PSDefaultParameterValues['Mock:ModuleName'] = $script:moduleName $PSDefaultParameterValues['Should:ModuleName'] = $script:moduleName } AfterAll { $PSDefaultParameterValues.Remove('InModuleScope:ModuleName') $PSDefaultParameterValues.Remove('Mock:ModuleNam...
Files:
tests/Unit/Public/Test-SqlDscIsDatabase.Tests.ps1tests/Unit/Public/Test-SqlDscDatabaseProperty.Tests.ps1
tests/Unit/Public/*.Tests.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines.instructions.md)
Place unit tests for public commands in tests/Unit/Public/{Name}.Tests.ps1
tests/Unit/Public/*.Tests.ps1: For public commands, never use InModuleScope (except when retrieving localized strings)
Place public command unit tests under tests/Unit/Public/{Name}.Tests.ps1
Files:
tests/Unit/Public/Test-SqlDscIsDatabase.Tests.ps1tests/Unit/Public/Test-SqlDscDatabaseProperty.Tests.ps1
tests/Unit/{Classes,Public,Private}/*.Tests.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines.instructions.md)
Add unit tests for all commands, functions, and resources
Files:
tests/Unit/Public/Test-SqlDscIsDatabase.Tests.ps1tests/Unit/Public/Test-SqlDscDatabaseProperty.Tests.ps1
tests/Unit/**/*.Tests.ps1
📄 CodeRabbit inference engine (.github/instructions/SqlServerDsc-guidelines.instructions.md)
tests/Unit/**/*.Tests.ps1: Unit tests must not mock real SMO types; use SMO stub types from SMO.cs
Unit tests must set $env:SqlServerDscCI = $true in BeforeAll and remove it in AfterAll
Unit tests that reference SMO types must load stubs via Add-Type -Path "$PSScriptRoot/../Stubs/SMO.cs"
Files:
tests/Unit/Public/Test-SqlDscIsDatabase.Tests.ps1tests/Unit/Public/Test-SqlDscDatabaseProperty.Tests.ps1
source/en-US/*.strings.psd1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-localization.instructions.md)
source/en-US/*.strings.psd1: Store command/function localization in source/en-US/{MyModuleName}.strings.psd1
Store class localization in source/en-US/{ResourceClassName}.strings.psd1
Name localization keys as Verb_FunctionName_Action using underscores (e.g., Get_Database_ConnectingToDatabase)
Define strings using ConvertFrom-StringData with entries likeKeyName = Message with {0} placeholder. (PREFIX0001)
Include string IDs in the form (PREFIX####), where PREFIX is initials from the class/function name and numbers are sequential from 0001
Files:
source/en-US/SqlServerDsc.strings.psd1
**/*.psd1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-powershell.instructions.md)
In module manifests, do not use NestedModules for shared commands without RootModule
Files:
source/en-US/SqlServerDsc.strings.psd1
🧠 Learnings (17)
📚 Learning: 2025-10-26T13:26:13.384Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-10-26T13:26:13.384Z
Learning: Applies to tests/Integration/**/*.Tests.ps1 : Integration tests must call Disconnect-SqlDscDatabaseEngine after Connect-SqlDscDatabaseEngine
Applied to files:
azure-pipelines.ymltests/Integration/Commands/Test-SqlDscIsDatabase.Integration.Tests.ps1tests/Unit/Public/Test-SqlDscIsDatabase.Tests.ps1tests/Integration/Commands/README.md
📚 Learning: 2025-09-16T16:35:31.909Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines.instructions.md:0-0
Timestamp: 2025-09-16T16:35:31.909Z
Learning: Applies to tests/Integration/Commands/*.Integration.Tests.ps1 : Add integration tests for all public commands (and resources)
Applied to files:
azure-pipelines.ymltests/Integration/Commands/Test-SqlDscIsDatabase.Integration.Tests.ps1tests/Integration/Commands/README.md
📚 Learning: 2025-10-26T13:26:13.384Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-10-26T13:26:13.384Z
Learning: Applies to tests/Integration/**/*.Tests.ps1 : Integration tests must use Connect-SqlDscDatabaseEngine with correct CI credentials to open DB sessions
Applied to files:
azure-pipelines.ymltests/Integration/Commands/Test-SqlDscIsDatabase.Integration.Tests.ps1tests/Integration/Commands/README.md
📚 Learning: 2025-10-12T11:23:30.123Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-integration-tests.instructions.md:0-0
Timestamp: 2025-10-12T11:23:30.123Z
Learning: Applies to tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1 : Call commands with -Force where applicable to avoid prompting
Applied to files:
azure-pipelines.ymltests/Integration/Commands/Test-SqlDscIsDatabase.Integration.Tests.ps1tests/Integration/Commands/README.md
📚 Learning: 2025-10-12T11:23:30.123Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-integration-tests.instructions.md:0-0
Timestamp: 2025-10-12T11:23:30.123Z
Learning: Applies to tests/Integration/Commands/*.Integration.Tests.ps1 : Place command integration tests at tests/Integration/Commands/{CommandName}.Integration.Tests.ps1
Applied to files:
azure-pipelines.ymltests/Integration/Commands/README.md
📚 Learning: 2025-09-16T16:35:31.909Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines.instructions.md:0-0
Timestamp: 2025-09-16T16:35:31.909Z
Learning: Applies to tests/Integration/Commands/*.Integration.Tests.ps1 : Place integration tests for public commands in tests/Integration/Commands/{CommandName}.Integration.Tests.ps1
Applied to files:
azure-pipelines.ymltests/Integration/Commands/README.md
📚 Learning: 2025-10-26T13:27:07.713Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-10-26T13:27:07.713Z
Learning: Applies to **/*.[Tt]ests.ps1 : All public commands and class-based resources must have integration tests
Applied to files:
azure-pipelines.ymltests/Integration/Commands/Test-SqlDscIsDatabase.Integration.Tests.ps1
📚 Learning: 2025-10-12T11:23:30.123Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-integration-tests.instructions.md:0-0
Timestamp: 2025-10-12T11:23:30.123Z
Learning: Applies to tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1 : Cover all scenarios and code paths in integration tests
Applied to files:
azure-pipelines.yml
📚 Learning: 2025-10-12T11:23:30.123Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-integration-tests.instructions.md:0-0
Timestamp: 2025-10-12T11:23:30.123Z
Learning: Applies to tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1 : Use -ErrorAction 'Stop' on commands so failures surface immediately
Applied to files:
azure-pipelines.yml
📚 Learning: 2025-09-16T16:35:31.909Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines.instructions.md:0-0
Timestamp: 2025-09-16T16:35:31.909Z
Learning: Applies to tests/Unit/{Classes,Public,Private}/*.Tests.ps1 : Add unit tests for all commands, functions, and resources
Applied to files:
azure-pipelines.yml
📚 Learning: 2025-09-16T16:34:44.689Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-unit-tests.instructions.md:0-0
Timestamp: 2025-09-16T16:34:44.689Z
Learning: Applies to tests/[Uu]nit/**/*.[Tt]ests.ps1 : Include the exact Pester setup block before Describe: SuppressMessage attribute with param (); BeforeDiscovery to ensure DscResource.Test is available (fallback to build.ps1 -Tasks 'noop') and Import-Module; BeforeAll to set $script:moduleName, import the module, and set PSDefaultParameterValues for InModuleScope/Mock/Should; AfterAll to remove those defaults and unload the tested module
Applied to files:
tests/Integration/Commands/Test-SqlDscIsDatabase.Integration.Tests.ps1
📚 Learning: 2025-10-12T11:23:30.123Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-integration-tests.instructions.md:0-0
Timestamp: 2025-10-12T11:23:30.123Z
Learning: Applies to tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1 : Include the required Pester setup block (SuppressMessage param, BeforeDiscovery loading DscResource.Test, and BeforeAll importing the module)
Applied to files:
tests/Integration/Commands/Test-SqlDscIsDatabase.Integration.Tests.ps1
📚 Learning: 2025-10-26T13:26:13.384Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-10-26T13:26:13.384Z
Learning: Applies to tests/Unit/**/*.Tests.ps1 : Unit tests must set $env:SqlServerDscCI = $true in BeforeAll and remove it in AfterAll
Applied to files:
tests/Integration/Commands/Test-SqlDscIsDatabase.Integration.Tests.ps1
📚 Learning: 2025-08-18T13:50:53.789Z
Learnt from: johlju
PR: dsccommunity/SqlServerDsc#2132
File: tests/Unit/Public/New-SqlDscLogin.Tests.ps1:0-0
Timestamp: 2025-08-18T13:50:53.789Z
Learning: In SqlServerDsc unit tests, SMO stub objects can be used to verify method calls like Create() on Login objects by adding mock verifications with Should -Invoke, providing more robust testing than just checking for no exceptions.
Applied to files:
tests/Unit/Public/Test-SqlDscIsDatabase.Tests.ps1
📚 Learning: 2025-09-16T16:34:44.689Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-unit-tests.instructions.md:0-0
Timestamp: 2025-09-16T16:34:44.689Z
Learning: Applies to tests/[Uu]nit/**/*.[Tt]ests.ps1 : Use the Parameter Properties template to assert a parameter is mandatory via $parameterInfo = (Get-Command -Name 'CommandName').Parameters['ParameterName']; $parameterInfo.Attributes.Mandatory | Should -BeTrue
Applied to files:
tests/Unit/Public/Test-SqlDscIsDatabase.Tests.ps1
📚 Learning: 2025-08-16T13:22:15.230Z
Learnt from: johlju
PR: dsccommunity/SqlServerDsc#2134
File: tests/Unit/Public/Get-SqlDscLogin.Tests.ps1:78-93
Timestamp: 2025-08-16T13:22:15.230Z
Learning: In PowerShell unit tests for parameter validation in SqlServerDsc, accessing parameter attributes directly like `$cmd.Parameters['ParameterName'].Attributes.Mandatory` works correctly because PowerShell automatically iterates through the array and returns the property values. Additional filtering to ParameterAttribute is not necessary when the parameter structure is known and controlled.
Applied to files:
tests/Unit/Public/Test-SqlDscIsDatabase.Tests.ps1
📚 Learning: 2025-10-04T21:33:23.022Z
Learnt from: dan-hughes
PR: dsccommunity/UpdateServicesDsc#85
File: source/en-US/UpdateServicesDsc.strings.psd1:1-2
Timestamp: 2025-10-04T21:33:23.022Z
Learning: In UpdateServicesDsc (and similar DSC modules), the module-level localization file (source/en-US/<ModuleName>.strings.psd1) can be empty when DSC resources have their own localization files in source/DSCResources/<ResourceName>/en-US/DSC_<ResourceName>.strings.psd1. Automated tests verify localization completeness for resources. Don't flag empty module-level localization files as issues when resources have separate localization.
Applied to files:
source/en-US/SqlServerDsc.strings.psd1
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
- GitHub Check: dsccommunity.SqlServerDsc (Build Package Module)
- GitHub Check: PSScriptAnalyzer
- GitHub Check: PSScriptAnalyzer
🔇 Additional comments (8)
CHANGELOG.md (1)
17-18: LGTM — migration verified complete.Verification confirmed:
- Old command file
Test-SqlDscDatabase.ps1removed fromsource/Public- New command file
Test-SqlDscIsDatabase.ps1present and active (no alias added)- References to old command name limited to CHANGELOG.md entries documenting the deprecation/removal—no active code references requiring updates
Consider adding a short example in docs in a follow-up PR.
azure-pipelines.yml (1)
339-339: IsDatabase integration test correctly added to group 4Placement and order look consistent with dependencies and existing command tests. LGTM.
tests/Integration/Commands/README.md (1)
95-96: Docs table updated for new commandsNew rows for Test-SqlDscIsDatabase and Test-SqlDscDatabaseProperty align with pipeline order. LGTM.
tests/Integration/Commands/Test-SqlDscDatabaseProperty.Integration.Tests.ps1 (1)
347-360: Param hashtable + persistent DB variable improve readabilityGood switch to using a single $testParameters hashtable and $script:persistentTestDatabase; keeps calls consistent and clear. LGTM.
Also applies to: 362-362, 369-369, 384-391, 392-392
tests/Unit/Public/Test-SqlDscDatabaseProperty.Tests.ps1 (2)
327-349: Refresh pass-through behavior validatedMocks + Should -Invoke checks confirm -Refresh is forwarded only when specified. LGTM.
482-487: Parameter set expectations updated to include -RefreshMatches the ServerObjectSet contract; DatabaseObjectSet unchanged. LGTM.
source/Public/Test-SqlDscDatabaseProperty.ps1 (1)
29-38: LGTM! Refresh parameter implementation is correct.The addition of the
Refreshparameter follows all coding guidelines:
- Comment-based help is properly formatted and clearly explains the parameter's purpose
- Parameter declaration correctly uses
ParameterSetName = 'ServerObjectSet'with appropriate type- The
-Refresh:$Refreshpattern correctly passes the switch parameter state toGet-SqlDscDatabase- Properly excluded from property testing by removing it from
$boundParametersAlso applies to: 518-520, 1126-1126, 1144-1144
tests/Unit/Public/Test-SqlDscIsDatabase.Tests.ps1 (1)
144-181: LGTM! Parameter validation tests follow guidelines correctly.The parameter validation tests properly use the required templates:
- Parameter Set Validation template for testing parameter sets
- Parameter Properties template for testing mandatory and optional parameters
- Pipeline input acceptance test
As per coding guidelines
tests/Integration/Commands/Test-SqlDscIsDatabase.Integration.Tests.ps1
Outdated
Show resolved
Hide resolved
…mentation to reflect usage of `Test-SqlDscIsDatabase` for existence checks.
…r improved error handling
…se and simplify Refresh verification
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 2
🧹 Nitpick comments (7)
tests/Integration/Commands/Test-SqlDscIsDatabase.Integration.Tests.ps1 (1)
33-49: Optional: set and restore $ErrorActionPreference during connect/disconnect.This keeps behavior consistent with scripts that use -ErrorAction 'Stop' and centralizes error handling.
Describe 'Test-SqlDscIsDatabase' -Tag @('Integration_SQL2017', 'Integration_SQL2019', 'Integration_SQL2022') { BeforeAll { + $script:oldEAP = $ErrorActionPreference + $ErrorActionPreference = 'Stop' $script:mockInstanceName = 'DSCSQLTEST' @@ } AfterAll { - Disconnect-SqlDscDatabaseEngine -ServerObject $script:serverObject -ErrorAction 'Stop' + Disconnect-SqlDscDatabaseEngine -ServerObject $script:serverObject -ErrorAction 'Stop' + $ErrorActionPreference = $script:oldEAP }Based on learnings.
source/Public/Test-SqlDscIsDatabase.ps1 (3)
68-68: Prefer -ErrorAction 'Ignore' to avoid polluting $Error.For existence checks, suppressing errors without adding them to $Error makes diagnostics cleaner.
- $sqlDatabaseObject = Get-SqlDscDatabase -ServerObject $ServerObject -Name $Name -Refresh:$Refresh -ErrorAction 'SilentlyContinue' + $sqlDatabaseObject = Get-SqlDscDatabase -ServerObject $ServerObject -Name $Name -Refresh:$Refresh -ErrorAction 'Ignore'
70-77: Simplify boolean return.Return the boolean directly to reduce branching.
- if ($sqlDatabaseObject) - { - return $true - } - else - { - return $false - } + return [bool] $sqlDatabaseObject
42-47: Consider adding an alias for migration and warn on deprecated name.To ease breaking change, add [Alias('Test-SqlDscDatabase')] and emit a localized deprecation warning when invoked via the old name. Ensure alias is exported in the module manifest.
function Test-SqlDscIsDatabase { + [Alias('Test-SqlDscDatabase')] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('UseSyntacticallyCorrectExamples', '', Justification = 'Because the rule does not yet support parsing the code when a parameter type is not available. The ScriptAnalyzer rule UseSyntacticallyCorrectExamples will always error in the editor due to https://github.com/indented-automation/Indented.ScriptAnalyzerRules/issues/8.')] [OutputType([System.Boolean])] [CmdletBinding()] @@ process { + if ($MyInvocation.InvocationName -ieq 'Test-SqlDscDatabase') + { + # Localize this string in source/en-US/SqlServerDsc.strings.psd1, e.g. IsDatabase_DeprecatedAlias_UseNew (TSDID0001) + Write-Warning -Message $script:localizedData.IsDatabase_DeprecatedAlias_UseNew + }I can add the string key and update the manifest’s AliasesToExport. As per PR objectives.
tests/Unit/Public/Test-SqlDscIsDatabase.Tests.ps1 (3)
90-93: Strengthen parameter verification for Refresh pass‑through.Also assert ServerObject and Name to fully verify call binding.
- Should -Invoke -CommandName Get-SqlDscDatabase -ParameterFilter { - $Refresh -eq $true - } -Exactly -Times 1 -Scope It + Should -Invoke -CommandName Get-SqlDscDatabase -ParameterFilter { + $Refresh -eq $true -and + $PSBoundParameters['ServerObject'] -eq $mockServerObject -and + $PSBoundParameters['Name'] -eq 'TestDatabase' + } -Exactly -Times 1 -Scope ItAs per test guidelines.
69-79: Optionally isolate existence tests with a Mock.Mock Get-SqlDscDatabase to avoid coupling to its implementation and keep these tests focused on this command’s behavior.
It 'Should return true when database exists' { - $result = Test-SqlDscIsDatabase -ServerObject $mockServerObject -Name 'TestDatabase' + Mock -CommandName Get-SqlDscDatabase -MockWith { $mockExistingDatabase } + $result = Test-SqlDscIsDatabase -ServerObject $mockServerObject -Name 'TestDatabase' @@ It 'Should return false when database does not exist' { - $result = Test-SqlDscIsDatabase -ServerObject $mockServerObject -Name 'NonExistentDatabase' + Mock -CommandName Get-SqlDscDatabase -MockWith { return $null } + $result = Test-SqlDscIsDatabase -ServerObject $mockServerObject -Name 'NonExistentDatabase'
103-108: Move ForEach test cases to BeforeDiscovery for clarity.Keeps data close to setup and aligns with conventions.
-BeforeAll { +BeforeDiscovery { + $script:parameterSetTestCases = @( + @{ + ExpectedParameterSetName = '__AllParameterSets' + ExpectedParameters = '[-ServerObject] <Server> [-Name] <String> [-Refresh] [<CommonParameters>]' + } + ) +} + +BeforeAll { @@ - It 'Should have the correct parameters in parameter set __AllParameterSets' -ForEach @( - @{ - ExpectedParameterSetName = '__AllParameterSets' - ExpectedParameters = '[-ServerObject] <Server> [-Name] <String> [-Refresh] [<CommonParameters>]' - } - ) { + It 'Should have the correct parameters in parameter set __AllParameterSets' -ForEach $script:parameterSetTestCases {As per test guidelines.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (5)
CHANGELOG.md(1 hunks)source/Public/Test-SqlDscIsDatabase.ps1(1 hunks)source/en-US/SqlServerDsc.strings.psd1(1 hunks)tests/Integration/Commands/Test-SqlDscIsDatabase.Integration.Tests.ps1(1 hunks)tests/Unit/Public/Test-SqlDscIsDatabase.Tests.ps1(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
- CHANGELOG.md
- source/en-US/SqlServerDsc.strings.psd1
🧰 Additional context used
📓 Path-based instructions (16)
tests/Integration/Commands/*.Integration.Tests.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines.instructions.md)
tests/Integration/Commands/*.Integration.Tests.ps1: Place integration tests for public commands in tests/Integration/Commands/{CommandName}.Integration.Tests.ps1
Add integration tests for all public commands (and resources)Place command integration tests at tests/Integration/Commands/{CommandName}.Integration.Tests.ps1
Files:
tests/Integration/Commands/Test-SqlDscIsDatabase.Integration.Tests.ps1
**/*.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines.instructions.md)
Follow PowerShell style and test guideline instructions strictly
Files:
tests/Integration/Commands/Test-SqlDscIsDatabase.Integration.Tests.ps1tests/Unit/Public/Test-SqlDscIsDatabase.Tests.ps1source/Public/Test-SqlDscIsDatabase.ps1
tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-integration-tests.instructions.md)
tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1: Do not use mocking in integration tests; run against a real environment
Cover all scenarios and code paths in integration tests
Use Get-ComputerName to determine computer names in CI
Avoid using -ExpectedMessage with Should -Throw assertions
Call commands with -Force where applicable to avoid prompting
Use -ErrorAction 'Stop' on commands so failures surface immediately
Include the required Pester setup block (SuppressMessage param, BeforeDiscovery loading DscResource.Test, and BeforeAll importing the module)
Files:
tests/Integration/Commands/Test-SqlDscIsDatabase.Integration.Tests.ps1
⚙️ CodeRabbit configuration file
tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1: # Integration Tests GuidelinesRequirements
- Location Commands:
tests/Integration/Commands/{CommandName}.Integration.Tests.ps1- Location Resources:
tests/Integration/Resources/{ResourceName}.Integration.Tests.ps1- No mocking - real environment only
- Cover all scenarios and code paths
- Use
Get-ComputerNamefor computer names in CI- Avoid
ExpectedMessageforShould -Throwassertions- Only run integration tests in CI unless explicitly instructed.
- Call commands with
-Forceparameter where applicable (avoids prompting).- Use
-ErrorAction 'Stop'on commands so failures surface immediatelyRequired Setup Block
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification = 'Suppressing this rule because Script Analyzer does not understand Pester syntax.')] param () BeforeDiscovery { try { if (-not (Get-Module -Name 'DscResource.Test')) { # Assumes dependencies have been resolved, so if this module is not available, run 'noop' task. if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) { # Redirect all streams to $null, except the error stream (stream 2) & "$PSScriptRoot/../../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null } # If the dependencies have not been resolved, this will throw an error. Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' } } catch [System.IO.FileNotFoundException] { throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks noop" first.' } } BeforeAll { $script:moduleName = '{MyModuleName}' Import-Module -Name $script:moduleName -Force -ErrorAction 'Stop' }
Files:
tests/Integration/Commands/Test-SqlDscIsDatabase.Integration.Tests.ps1
**/*.{ps1,psm1}
📄 CodeRabbit inference engine (.github/instructions/SqlServerDsc-guidelines.instructions.md)
**/*.{ps1,psm1}: Public PowerShell commands must follow the {Verb}-SqlDsc{Noun} naming format
Private PowerShell functions must follow the {Verb}-{Noun} naming format
**/*.{ps1,psm1}: Use descriptive names (3+ characters, no abbreviations)
Functions must use PascalCase with approved Verb-Noun format
Parameters use PascalCase
Variables use camelCase
Keywords are lower-case
Classes use PascalCase
Include scope for script/global/environment variables: $script:, $global:, $env:
Use one space around operators (e.g., $a = 1 + 2)
Use one space between type and variable (e.g., [String] $name)
Use one space between keyword and parenthesis (e.g., if ($condition))
Newline before opening brace except for variable assignments
One newline after opening brace
Two newlines after closing brace (one if followed by another brace or continuation)
Use single quotes unless variable expansion is needed
Arrays single-line format: @('one','two','three')
Multi-line arrays: one element per line with proper indentation
Do not use unary comma in return statements to force an array
Empty hashtable as @{}
Hashtable properties each on their own line with proper indentation
Hashtable property names use PascalCase
Single-line comments start with #, capitalized, on their own line
Multi-line comments use <# #>, brackets on their own lines, text indented
No commented-out code
Always add comment-based help to all functions and scripts
Comment-based help must include SYNOPSIS, DESCRIPTION (40+ chars), PARAMETER, EXAMPLE sections before function/class
Comment-based help indentation: keywords 4 spaces, text 8 spaces
Include examples for all parameter sets and combinations in comment-based help
INPUTS: list each pipeline-accepted type with one-line description; repeat keyword per type
OUTPUTS: list each return type with one-line description; repeat keyword per type; must match [OutputType()] and actual returns
.NOTES only if critical (constraints, side effects, security, version), ≤2 short sentences
Av...
Files:
tests/Integration/Commands/Test-SqlDscIsDatabase.Integration.Tests.ps1tests/Unit/Public/Test-SqlDscIsDatabase.Tests.ps1source/Public/Test-SqlDscIsDatabase.ps1
**/*.{ps1,psm1,cs}
📄 CodeRabbit inference engine (.github/instructions/SqlServerDsc-guidelines.instructions.md)
Prefer SMO over T-SQL for SQL Server interactions
Files:
tests/Integration/Commands/Test-SqlDscIsDatabase.Integration.Tests.ps1tests/Unit/Public/Test-SqlDscIsDatabase.Tests.ps1source/Public/Test-SqlDscIsDatabase.ps1
tests/Integration/**/*.Tests.ps1
📄 CodeRabbit inference engine (.github/instructions/SqlServerDsc-guidelines.instructions.md)
tests/Integration/**/*.Tests.ps1: Integration tests must use Connect-SqlDscDatabaseEngine with correct CI credentials to open DB sessions
Integration tests must call Disconnect-SqlDscDatabaseEngine after Connect-SqlDscDatabaseEngine
Files:
tests/Integration/Commands/Test-SqlDscIsDatabase.Integration.Tests.ps1
**/*.[Tt]ests.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-pester.instructions.md)
**/*.[Tt]ests.ps1: All public commands, private functions and classes must have unit tests
All public commands and class-based resources must have integration tests
Use Pester v5 syntax only
Place executable test code only inside Describe blocks
Place assertions only in It blocks
Do not test verbose messages, debug messages, or parameter binding behavior
Pass all mandatory parameters in tests to avoid prompts
Inside It blocks, assign unused return objects to $null (unless part of a pipeline)
Invoke the tested entity from within It blocks
Keep result capture and assertions in the same It block
Avoid try/catch/finally for cleanup; use AfterAll or AfterEach instead
Avoid unnecessary remove/recreate cycles in tests
Have exactly one Describe block per file, and name it to match the tested entity
Context descriptions must start with 'When'
It descriptions must start with 'Should' and must not contain 'when'
Prefix variables used for mocks with 'mock'
Create a separate Context block for each scenario
Use nested Context blocks for complex scenarios
Define mocks in BeforeAll; use BeforeEach only when required
Place setup/teardown in the nearest appropriate BeforeAll, BeforeEach, AfterAll, or AfterEach to where it’s used
Use PascalCase for Pester keywords: Describe, Context, It, Should, BeforeAll, BeforeEach, AfterAll, AfterEach
Use -BeTrue/-BeFalse; never use -Be $true/-Be $false
Never use Assert-MockCalled; use Should -Invoke instead
Do not use 'Should -Not -Throw'; invoke commands directly
Never add an empty -MockWith block
Omit -MockWith when the mock should return $null
Set $PSDefaultParameterValues entries for Mock:ModuleName, Should:ModuleName, and InModuleScope:ModuleName
Omit the -ModuleName parameter on Pester commands
Never use Mock inside an InModuleScope block
Define variables for -ForEach in BeforeDiscovery (close to usage)
Use -ForEach only on Context and It blocks
Do not add param() inside Pester blocks when using -ForEach
Access test case properties directl...
Files:
tests/Integration/Commands/Test-SqlDscIsDatabase.Integration.Tests.ps1tests/Unit/Public/Test-SqlDscIsDatabase.Tests.ps1
⚙️ CodeRabbit configuration file
**/*.[Tt]ests.ps1: # Tests GuidelinesCore Requirements
- All public commands, private functions and classes must have unit tests
- All public commands and class-based resources must have integration tests
- Use Pester v5 syntax only
- Test code only inside
Describeblocks- Assertions only in
Itblocks- Never test verbose messages, debug messages or parameter binding behavior
- Pass all mandatory parameters to avoid prompts
Requirements
- Inside
Itblocks, assign unused return objects to$null(unless part of pipeline)- Tested entity must be called from within the
Itblocks- Keep results and assertions in same
Itblock- Avoid try-catch-finally for cleanup, use
AfterAllorAfterEach- Avoid unnecessary remove/recreate cycles
Naming
- One
Describeblock per file matching the tested entity nameContextdescriptions start with 'When'Itdescriptions start with 'Should', must not contain 'when'- Mock variables prefix: 'mock'
Structure & Scope
- Public commands: Never use
InModuleScope(unless retrieving localized strings)- Private functions/class resources: Always use
InModuleScope- Each class method = separate
Contextblock- Each scenario = separate
Contextblock- Use nested
Contextblocks for complex scenarios- Mocking in
BeforeAll(BeforeEachonly when required)- Setup/teardown in
BeforeAll,BeforeEach/AfterAll,AfterEachclose to usageSyntax Rules
- PascalCase:
Describe,Context,It,Should,BeforeAll,BeforeEach,AfterAll,AfterEach- Use
-BeTrue/-BeFalsenever-Be $true/-Be $false- Never use
Assert-MockCalled, useShould -Invokeinstead- No
Should -Not -Throw- invoke commands directly- Never add an empty
-MockWithblock- Omit
-MockWithwhen returning$null- Set
$PSDefaultParameterValuesforMock:ModuleName,Should:ModuleName,InModuleScope:ModuleName- Omit
-ModuleNameparameter on Pester commands- Never use
Mockinside `InModuleSc...
Files:
tests/Integration/Commands/Test-SqlDscIsDatabase.Integration.Tests.ps1tests/Unit/Public/Test-SqlDscIsDatabase.Tests.ps1
**/*.{ps1,psm1,psd1}
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-powershell.instructions.md)
**/*.{ps1,psm1,psd1}: Use 4 spaces for indentation (no tabs)
No spaces on empty lines
Try to limit lines to 120 characters
End files with exactly one blank line
Use line endings as defined by .gitattributes
Allow a maximum of two consecutive newlines
No trailing whitespace on any line
Use UTF-8 encoding without BOM for all files
Files:
tests/Integration/Commands/Test-SqlDscIsDatabase.Integration.Tests.ps1tests/Unit/Public/Test-SqlDscIsDatabase.Tests.ps1source/Public/Test-SqlDscIsDatabase.ps1
**
⚙️ CodeRabbit configuration file
**: # DSC Community GuidelinesTerminology
- Command: Public command
- Function: Private function
- Resource: DSC class-based resource
Build & Test Workflow Requirements
- Run PowerShell script files from repository root
- Setup build and test environment (once per
pwshsession):./build.ps1 -Tasks noop- Build project before running tests:
./build.ps1 -Tasks build- Always run tests in new
pwshsession:Invoke-Pester -Path @({test paths}) -Output DetailedFile Organization
- Public commands:
source/Public/{CommandName}.ps1- Private functions:
source/Private/{FunctionName}.ps1- Unit tests:
tests/Unit/{Classes|Public|Private}/{Name}.Tests.ps1- Integration tests:
tests/Integration/Commands/{CommandName}.Integration.Tests.ps1Requirements
- Follow instructions over existing code patterns
- Follow PowerShell style and test guideline instructions strictly
- Always update CHANGELOG.md Unreleased section
- Localize all strings using string keys; remove any orphaned string keys
- Check DscResource.Common before creating private functions
- Separate reusable logic into private functions
- DSC resources should always be created as class-based resources
- Add unit tests for all commands/functions/resources
- Add integration tests for all public commands and resources
Files:
tests/Integration/Commands/Test-SqlDscIsDatabase.Integration.Tests.ps1tests/Unit/Public/Test-SqlDscIsDatabase.Tests.ps1source/Public/Test-SqlDscIsDatabase.ps1
{**/*.ps1,**/*.psm1,**/*.psd1}
⚙️ CodeRabbit configuration file
{**/*.ps1,**/*.psm1,**/*.psd1}: # PowerShell GuidelinesNaming
- Use descriptive names (3+ characters, no abbreviations)
- Functions: PascalCase with Verb-Noun format using approved verbs
- Parameters: PascalCase
- Variables: camelCase
- Keywords: lower-case
- Classes: PascalCase
- Include scope for script/global/environment variables:
$script:,$global:,$env:File naming
- Class files:
###.ClassName.ps1format (e.g.001.SqlReason.ps1,004.StartupParameters.ps1)Formatting
Indentation & Spacing
- Use 4 spaces (no tabs)
- One space around operators:
$a = 1 + 2- One space between type and variable:
[String] $name- One space between keyword and parenthesis:
if ($condition)- No spaces on empty lines
- Try to limit lines to 120 characters
Braces
- Newline before opening brace (except variable assignments)
- One newline after opening brace
- Two newlines after closing brace (one if followed by another brace or continuation)
Quotes
- Use single quotes unless variable expansion is needed:
'text'vs"text $variable"Arrays
- Single line:
@('one', 'two', 'three')- Multi-line: each element on separate line with proper indentation
- Do not use the unary comma operator (
,) in return statements to force
an arrayHashtables
- Empty:
@{}- Each property on separate line with proper indentation
- Properties: Use PascalCase
Comments
- Single line:
# Comment(capitalized, on own line)- Multi-line:
<# Comment #>format (opening and closing brackets on own line), and indent text- No commented-out code
Comment-based help
- Always add comment-based help to all functions and scripts
- Comment-based help: SYNOPSIS, DESCRIPTION (40+ chars), PARAMETER, EXAMPLE sections before function/class
- Comment-based help indentation: keywords 4 spaces, text 8 spaces
- Include examples for all parameter sets and combinations
- INPUTS: List each pipeline‑accepted type (one per line) with a 1‑line description...
Files:
tests/Integration/Commands/Test-SqlDscIsDatabase.Integration.Tests.ps1tests/Unit/Public/Test-SqlDscIsDatabase.Tests.ps1source/Public/Test-SqlDscIsDatabase.ps1
tests/[Uu]nit/**/*.[Tt]ests.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-unit-tests.instructions.md)
tests/[Uu]nit/**/*.[Tt]ests.ps1: In unit tests, access localized strings using InModuleScope -ScriptBlock { $script:localizedData.Key }
When mocking files in tests, use the $TestDrive variable for file system operations
All public commands must include parameter set validation tests
Include the exact Pester setup block before Describe: SuppressMessage attribute with param (); BeforeDiscovery to ensure DscResource.Test is available (fallback to build.ps1 -Tasks 'noop') and Import-Module; BeforeAll to set $script:moduleName, import the module, and set PSDefaultParameterValues for InModuleScope/Mock/Should; AfterAll to remove those defaults and unload the tested module
Use the provided Parameter Set Validation test template to assert command ParameterSetName and full parameter list string; for multiple parameter sets, supply multiple hashtables via -ForEach
Use the Parameter Properties template to assert a parameter is mandatory via $parameterInfo = (Get-Command -Name 'CommandName').Parameters['ParameterName']; $parameterInfo.Attributes.Mandatory | Should -BeTrue
Files:
tests/Unit/Public/Test-SqlDscIsDatabase.Tests.ps1
⚙️ CodeRabbit configuration file
tests/[Uu]nit/**/*.[Tt]ests.ps1: # Unit Tests Guidelines
- Test with localized strings: Use
InModuleScope -ScriptBlock { $script:localizedData.Key }- Mock files: Use
$TestDrivevariable (path to the test drive)- All public commands require parameter set validation tests
- After modifying classes, always run tests in new session (for changes to take effect)
Test Setup Requirements
Use this exact setup block before
Describe:[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification = 'Suppressing this rule because Script Analyzer does not understand Pester syntax.')] param () BeforeDiscovery { try { if (-not (Get-Module -Name 'DscResource.Test')) { # Assumes dependencies have been resolved, so if this module is not available, run 'noop' task. if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) { # Redirect all streams to $null, except the error stream (stream 2) & "$PSScriptRoot/../../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null } # If the dependencies have not been resolved, this will throw an error. Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' } } catch [System.IO.FileNotFoundException] { throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks noop" first.' } } BeforeAll { $script:moduleName = '{MyModuleName}' Import-Module -Name $script:moduleName -Force -ErrorAction 'Stop' $PSDefaultParameterValues['InModuleScope:ModuleName'] = $script:moduleName $PSDefaultParameterValues['Mock:ModuleName'] = $script:moduleName $PSDefaultParameterValues['Should:ModuleName'] = $script:moduleName } AfterAll { $PSDefaultParameterValues.Remove('InModuleScope:ModuleName') $PSDefaultParameterValues.Remove('Mock:ModuleNam...
Files:
tests/Unit/Public/Test-SqlDscIsDatabase.Tests.ps1
tests/Unit/Public/*.Tests.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines.instructions.md)
Place unit tests for public commands in tests/Unit/Public/{Name}.Tests.ps1
tests/Unit/Public/*.Tests.ps1: For public commands, never use InModuleScope (except when retrieving localized strings)
Place public command unit tests under tests/Unit/Public/{Name}.Tests.ps1
Files:
tests/Unit/Public/Test-SqlDscIsDatabase.Tests.ps1
tests/Unit/{Classes,Public,Private}/*.Tests.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines.instructions.md)
Add unit tests for all commands, functions, and resources
Files:
tests/Unit/Public/Test-SqlDscIsDatabase.Tests.ps1
tests/Unit/**/*.Tests.ps1
📄 CodeRabbit inference engine (.github/instructions/SqlServerDsc-guidelines.instructions.md)
tests/Unit/**/*.Tests.ps1: Unit tests must not mock real SMO types; use SMO stub types from SMO.cs
Unit tests must set $env:SqlServerDscCI = $true in BeforeAll and remove it in AfterAll
Unit tests that reference SMO types must load stubs via Add-Type -Path "$PSScriptRoot/../Stubs/SMO.cs"
Files:
tests/Unit/Public/Test-SqlDscIsDatabase.Tests.ps1
source/**/*.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-localization.instructions.md)
source/**/*.ps1: Localize all Write-Debug, Write-Verbose, Write-Error, Write-Warning, and $PSCmdlet.ThrowTerminatingError() messages
Use localized string keys instead of hardcoded strings in script output/messages
Assume and use $script:localizedData for accessing localized strings
When emitting messages, reference $script:localizedData.KeyName and format with the -f operator (e.g., Write-Verbose -Message ($script:localizedData.KeyName -f $value1))
Files:
source/Public/Test-SqlDscIsDatabase.ps1
⚙️ CodeRabbit configuration file
source/**/*.ps1: # Localization GuidelinesRequirements
- Localize all Write-Debug, Write-Verbose, Write-Error, Write-Warning and $PSCmdlet.ThrowTerminatingError() messages
- Use localized string keys, not hardcoded strings
- Assume
$script:localizedDatais availableString Files
- Commands/functions:
source/en-US/{MyModuleName}.strings.psd1- Class resources:
source/en-US/{ResourceClassName}.strings.psd1Key Naming Patterns
- Format:
Verb_FunctionName_Action(underscore separators), e.g.Get_Database_ConnectingToDatabaseString Format
ConvertFrom-StringData @' KeyName = Message with {0} placeholder. (PREFIX0001) '@String IDs
- Format:
(PREFIX####)- PREFIX: First letter of each word in class or function name (SqlSetup → SS, Get-SqlDscDatabase → GSDD)
- Number: Sequential from 0001
Usage
Write-Verbose -Message ($script:localizedData.KeyName -f $value1)
Files:
source/Public/Test-SqlDscIsDatabase.ps1
source/Public/*.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines.instructions.md)
Place public commands in source/Public/{CommandName}.ps1
Files:
source/Public/Test-SqlDscIsDatabase.ps1
🧠 Learnings (13)
📓 Common learnings
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-10-26T13:26:13.384Z
Learning: Applies to tests/Integration/**/*.Tests.ps1 : Integration tests must call Disconnect-SqlDscDatabaseEngine after Connect-SqlDscDatabaseEngine
📚 Learning: 2025-10-26T13:26:13.384Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-10-26T13:26:13.384Z
Learning: Applies to tests/Integration/**/*.Tests.ps1 : Integration tests must call Disconnect-SqlDscDatabaseEngine after Connect-SqlDscDatabaseEngine
Applied to files:
tests/Integration/Commands/Test-SqlDscIsDatabase.Integration.Tests.ps1tests/Unit/Public/Test-SqlDscIsDatabase.Tests.ps1
📚 Learning: 2025-09-16T16:35:31.909Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines.instructions.md:0-0
Timestamp: 2025-09-16T16:35:31.909Z
Learning: Applies to tests/Integration/Commands/*.Integration.Tests.ps1 : Add integration tests for all public commands (and resources)
Applied to files:
tests/Integration/Commands/Test-SqlDscIsDatabase.Integration.Tests.ps1tests/Unit/Public/Test-SqlDscIsDatabase.Tests.ps1
📚 Learning: 2025-10-26T13:26:13.384Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-10-26T13:26:13.384Z
Learning: Applies to tests/Integration/**/*.Tests.ps1 : Integration tests must use Connect-SqlDscDatabaseEngine with correct CI credentials to open DB sessions
Applied to files:
tests/Integration/Commands/Test-SqlDscIsDatabase.Integration.Tests.ps1tests/Unit/Public/Test-SqlDscIsDatabase.Tests.ps1
📚 Learning: 2025-09-16T16:34:44.689Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-unit-tests.instructions.md:0-0
Timestamp: 2025-09-16T16:34:44.689Z
Learning: Applies to tests/[Uu]nit/**/*.[Tt]ests.ps1 : Include the exact Pester setup block before Describe: SuppressMessage attribute with param (); BeforeDiscovery to ensure DscResource.Test is available (fallback to build.ps1 -Tasks 'noop') and Import-Module; BeforeAll to set $script:moduleName, import the module, and set PSDefaultParameterValues for InModuleScope/Mock/Should; AfterAll to remove those defaults and unload the tested module
Applied to files:
tests/Integration/Commands/Test-SqlDscIsDatabase.Integration.Tests.ps1tests/Unit/Public/Test-SqlDscIsDatabase.Tests.ps1
📚 Learning: 2025-10-26T13:27:07.713Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-10-26T13:27:07.713Z
Learning: Applies to **/*.[Tt]ests.ps1 : All public commands and class-based resources must have integration tests
Applied to files:
tests/Integration/Commands/Test-SqlDscIsDatabase.Integration.Tests.ps1
📚 Learning: 2025-10-12T11:23:30.123Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-integration-tests.instructions.md:0-0
Timestamp: 2025-10-12T11:23:30.123Z
Learning: Applies to tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1 : Include the required Pester setup block (SuppressMessage param, BeforeDiscovery loading DscResource.Test, and BeforeAll importing the module)
Applied to files:
tests/Integration/Commands/Test-SqlDscIsDatabase.Integration.Tests.ps1
📚 Learning: 2025-10-26T13:26:13.384Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-10-26T13:26:13.384Z
Learning: Applies to tests/Unit/**/*.Tests.ps1 : Unit tests must set $env:SqlServerDscCI = $true in BeforeAll and remove it in AfterAll
Applied to files:
tests/Integration/Commands/Test-SqlDscIsDatabase.Integration.Tests.ps1tests/Unit/Public/Test-SqlDscIsDatabase.Tests.ps1
📚 Learning: 2025-10-12T11:23:30.123Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-integration-tests.instructions.md:0-0
Timestamp: 2025-10-12T11:23:30.123Z
Learning: Applies to tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1 : Cover all scenarios and code paths in integration tests
Applied to files:
tests/Integration/Commands/Test-SqlDscIsDatabase.Integration.Tests.ps1
📚 Learning: 2025-10-12T11:23:30.123Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-integration-tests.instructions.md:0-0
Timestamp: 2025-10-12T11:23:30.123Z
Learning: Applies to tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1 : Call commands with -Force where applicable to avoid prompting
Applied to files:
tests/Integration/Commands/Test-SqlDscIsDatabase.Integration.Tests.ps1
📚 Learning: 2025-10-12T11:23:30.123Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-integration-tests.instructions.md:0-0
Timestamp: 2025-10-12T11:23:30.123Z
Learning: Applies to tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1 : Use -ErrorAction 'Stop' on commands so failures surface immediately
Applied to files:
tests/Integration/Commands/Test-SqlDscIsDatabase.Integration.Tests.ps1
📚 Learning: 2025-10-26T13:28:23.406Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-powershell.instructions.md:0-0
Timestamp: 2025-10-26T13:28:23.406Z
Learning: Applies to **/*.{ps1,psm1} : Set $ErrorActionPreference = 'Stop' before commands using -ErrorAction 'Stop'; restore previous value after (no try-catch-finally)
Applied to files:
tests/Integration/Commands/Test-SqlDscIsDatabase.Integration.Tests.ps1
📚 Learning: 2025-09-16T16:35:31.909Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines.instructions.md:0-0
Timestamp: 2025-09-16T16:35:31.909Z
Learning: Applies to tests/Unit/{Classes,Public,Private}/*.Tests.ps1 : Add unit tests for all commands, functions, and resources
Applied to files:
tests/Unit/Public/Test-SqlDscIsDatabase.Tests.ps1
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
- GitHub Check: dsccommunity.SqlServerDsc (Build Package Module)
- GitHub Check: PSScriptAnalyzer
- GitHub Check: PSScriptAnalyzer
tests/Integration/Commands/Test-SqlDscIsDatabase.Integration.Tests.ps1
Outdated
Show resolved
Hide resolved
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #2325 +/- ##
====================================
- Coverage 94% 94% -1%
====================================
Files 152 152
Lines 9299 9277 -22
====================================
- Hits 8811 8790 -21
+ Misses 488 487 -1
🚀 New features to boost your workflow:
|
… improved verification of database existence and refresh behavior
…abase for improved error handling
johlju
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@johlju reviewed 6 of 12 files at r1, 2 of 5 files at r2, 4 of 4 files at r3, all commit messages.
Reviewable status:complete! all files reviewed, all discussions resolved (waiting on @johlju)
Pull Request (PR) description
Test-SqlDscDatabaseas it is now redundant. The newcommand
Test-SqlDscIsDatabaseprovides database existence checking with acleaner interface. Users testing database properties should use
Test-SqlDscDatabasePropertyinstead (issue #2201).Test-SqlDscIsDatabaseto test if a database exists on aSQL Server Database Engine instance (issue #2201).
This Pull Request (PR) fixes the following issues
Test-SqlDscIsDatabase: Command rename proposal #2201Task list
file CHANGELOG.md. Entry should say what was changed and how that
affects users (if applicable), and reference the issue being resolved
(if applicable).
This change is