Skip to content

Conversation

@johlju
Copy link
Member

@johlju johlju commented Oct 26, 2025

Pull Request (PR) description

  • 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).
  • Added public command Test-SqlDscIsDatabase to test if a database exists on a
    SQL Server Database Engine instance (issue #2201).

This Pull Request (PR) fixes the following issues

Task list

  • Added an entry to the change log under the Unreleased section of the
    file CHANGELOG.md. Entry should say what was changed and how that
    affects users (if applicable), and reference the issue being resolved
    (if applicable).
  • Resource documentation updated in the resource's README.md.
  • Resource parameter descriptions updated in schema.mof.
  • Comment-based help updated, including parameter descriptions.
  • Localization strings updated.
  • Examples updated.
  • Unit tests updated. See DSC Community Testing Guidelines.
  • Integration tests updated (where possible). See DSC Community Testing Guidelines.
  • Code changes adheres to DSC Community Style Guidelines.

This change is Reviewable

@johlju johlju requested a review from a team as a code owner October 26, 2025 13:40
@coderabbitai
Copy link

coderabbitai bot commented Oct 26, 2025

Walkthrough

Removes 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

Cohort / File(s) Summary
Command removal & addition
source/Public/Test-SqlDscDatabase.ps1,
source/Public/Test-SqlDscIsDatabase.ps1
Deleted Test-SqlDscDatabase. Added Test-SqlDscIsDatabase — simple boolean existence check with -ServerObject, -Name, optional -Refresh.
Database property command update
source/Public/Test-SqlDscDatabaseProperty.ps1
Added [Switch] $Refresh to the ServerObjectSet parameter set; forwards -Refresh:$Refresh to Get-SqlDscDatabase; removes Refresh from bound-parameters used for property comparison.
Localization & changelog
source/en-US/SqlServerDsc.strings.psd1,
CHANGELOG.md
Removed Test-SqlDscDatabase localization entries and replaced with Test-SqlDscIsDatabase string(s); updated CHANGELOG text to mention using Test-SqlDscIsDatabase and Test-SqlDscDatabaseProperty.
CI pipeline config
azure-pipelines.yml
Replaced integration test reference Test-SqlDscDatabase.Integration.Tests.ps1 with Test-SqlDscIsDatabase.Integration.Tests.ps1 in Commands integration test group.
Integration tests
tests/Integration/Commands/Test-SqlDscDatabase.Integration.Tests.ps1 (removed),
tests/Integration/Commands/Test-SqlDscIsDatabase.Integration.Tests.ps1,
tests/Integration/Commands/Test-SqlDscDatabaseProperty.Integration.Tests.ps1
Removed old Test-SqlDscDatabase integration suite. Added Test-SqlDscIsDatabase integration tests (existence, system DBs, case-insensitivity, Refresh, pipeline). Refactored Test-SqlDscDatabaseProperty integration tests to use parameter hashtables and persistent DB variable.
Unit tests
tests/Unit/Public/Test-SqlDscDatabaseProperty.Tests.ps1,
tests/Unit/Public/Test-SqlDscIsDatabase.Tests.ps1
Added unit tests asserting Refresh passthrough for Test-SqlDscDatabaseProperty. Added unit suite for Test-SqlDscIsDatabase covering existence cases, Refresh forwarding, pipeline input, parameter validation, and SMO mocking.

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
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

  • Files to inspect closely:
    • source/Public/Test-SqlDscIsDatabase.ps1 — parameter validation, pipeline binding, error suppression, boolean output.
    • source/Public/Test-SqlDscDatabaseProperty.ps1 — forwarding -Refresh and ensuring Refresh is excluded from property comparisons.
    • Integration/unit test files and azure-pipelines.yml — naming, test registration, and splatting changes.
    • source/en-US/SqlServerDsc.strings.psd1 and CHANGELOG.md — ensure string keys and messages match cmdlet behavior.

Possibly related PRs

Pre-merge checks

❌ Failed checks (1 warning, 1 inconclusive)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
Out of Scope Changes Check ❓ Inconclusive Most changes are directly aligned with the stated objective of renaming Test-SqlDscDatabase to Test-SqlDscIsDatabase. However, one change warrants clarification: the addition of a Refresh parameter to Test-SqlDscDatabaseProperty. This parameter is not mentioned in issue #2201's stated objectives, which focus solely on the command rename and providing migration guidance. While the Refresh parameter addition appears to support consistency across related database commands (the branch is named "fix/refresh-parameter"), it extends beyond what the linked issue explicitly requires and could be considered a separate enhancement that should be verified against the original issue's intent.
✅ Passed checks (3 passed)
Check name Status Explanation
Title Check ✅ Passed The title "Test-SqlDscIsDatabase: Check database existence" directly and clearly summarizes the primary change in this pull request. It accurately reflects the main objective of introducing a new command that checks if a database exists on a SQL Server instance. The title is concise, specific, and avoids vague terminology, making it immediately clear to reviewers what the primary focus of this changeset is.
Linked Issues Check ✅ Passed The pull request substantially meets the core coding requirements from issue #2201. The old command Test-SqlDscDatabase has been removed, the new command Test-SqlDscIsDatabase has been added with proper parameters and behavior, CHANGELOG entries have been updated to document the breaking change and new command, documentation and examples have been updated, and both unit and integration tests have been added for the new command. The PR checklist indicates that Comment-based help, examples, unit tests, and integration tests were all updated. The one optional consideration from the issue—adding the old command name as an alias—was not implemented, but this was marked as "could add" rather than a required objective.
Description Check ✅ Passed The pull request description is directly related to the changeset and provides meaningful context. It clearly explains that the old command Test-SqlDscDatabase is being removed as redundant, the new command Test-SqlDscIsDatabase is being added for database existence checking, and users needing property validation should use Test-SqlDscDatabaseProperty instead. The description also references the linked issue #2201, providing traceability for the changes.

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9abef83 and cd79e93.

📒 Files selected for processing (1)
  • tests/Integration/Commands/Test-SqlDscDatabaseProperty.Integration.Tests.ps1 (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/Integration/Commands/Test-SqlDscDatabaseProperty.Integration.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

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@coderabbitai coderabbitai bot left a 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 Context block 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 help

Document 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 compatibility

Add [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

📥 Commits

Reviewing files that changed from the base of the PR and between 4423284 and a2b4c31.

📒 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 Guidelines

Terminology

  • 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 pwsh session): ./build.ps1 -Tasks noop
  • Build project before running tests: ./build.ps1 -Tasks build
  • Always run tests in new pwsh session: Invoke-Pester -Path @({test paths}) -Output Detailed

File 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.ps1

Requirements

  • 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.yml
  • source/Public/Test-SqlDscDatabaseProperty.ps1
  • tests/Integration/Commands/Test-SqlDscDatabaseProperty.Integration.Tests.ps1
  • source/Public/Test-SqlDscIsDatabase.ps1
  • CHANGELOG.md
  • tests/Integration/Commands/Test-SqlDscIsDatabase.Integration.Tests.ps1
  • tests/Unit/Public/Test-SqlDscIsDatabase.Tests.ps1
  • tests/Unit/Public/Test-SqlDscDatabaseProperty.Tests.ps1
  • source/en-US/SqlServerDsc.strings.psd1
  • tests/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.ps1
  • source/Public/Test-SqlDscIsDatabase.ps1

⚙️ CodeRabbit configuration file

source/**/*.ps1: # Localization Guidelines

Requirements

  • Localize all Write-Debug, Write-Verbose, Write-Error, Write-Warning and $PSCmdlet.ThrowTerminatingError() messages
  • Use localized string keys, not hardcoded strings
  • Assume $script:localizedData is available

String Files

  • Commands/functions: source/en-US/{MyModuleName}.strings.psd1
  • Class resources: source/en-US/{ResourceClassName}.strings.psd1

Key Naming Patterns

  • Format: Verb_FunctionName_Action (underscore separators), e.g. Get_Database_ConnectingToDatabase

String 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.ps1
  • 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-SqlDscDatabaseProperty.ps1
  • source/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.ps1
  • tests/Integration/Commands/Test-SqlDscDatabaseProperty.Integration.Tests.ps1
  • source/Public/Test-SqlDscIsDatabase.ps1
  • tests/Integration/Commands/Test-SqlDscIsDatabase.Integration.Tests.ps1
  • tests/Unit/Public/Test-SqlDscIsDatabase.Tests.ps1
  • tests/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.ps1
  • tests/Integration/Commands/Test-SqlDscDatabaseProperty.Integration.Tests.ps1
  • source/Public/Test-SqlDscIsDatabase.ps1
  • tests/Integration/Commands/Test-SqlDscIsDatabase.Integration.Tests.ps1
  • tests/Unit/Public/Test-SqlDscIsDatabase.Tests.ps1
  • tests/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.ps1
  • tests/Integration/Commands/Test-SqlDscDatabaseProperty.Integration.Tests.ps1
  • source/Public/Test-SqlDscIsDatabase.ps1
  • tests/Integration/Commands/Test-SqlDscIsDatabase.Integration.Tests.ps1
  • tests/Unit/Public/Test-SqlDscIsDatabase.Tests.ps1
  • tests/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.ps1
  • tests/Integration/Commands/Test-SqlDscDatabaseProperty.Integration.Tests.ps1
  • source/Public/Test-SqlDscIsDatabase.ps1
  • tests/Integration/Commands/Test-SqlDscIsDatabase.Integration.Tests.ps1
  • tests/Unit/Public/Test-SqlDscIsDatabase.Tests.ps1
  • tests/Unit/Public/Test-SqlDscDatabaseProperty.Tests.ps1
  • source/en-US/SqlServerDsc.strings.psd1
{**/*.ps1,**/*.psm1,**/*.psd1}

⚙️ CodeRabbit configuration file

{**/*.ps1,**/*.psm1,**/*.psd1}: # PowerShell Guidelines

Naming

  • 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.ps1 format (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 array

Hashtables

  • 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.ps1
  • tests/Integration/Commands/Test-SqlDscDatabaseProperty.Integration.Tests.ps1
  • source/Public/Test-SqlDscIsDatabase.ps1
  • tests/Integration/Commands/Test-SqlDscIsDatabase.Integration.Tests.ps1
  • tests/Unit/Public/Test-SqlDscIsDatabase.Tests.ps1
  • tests/Unit/Public/Test-SqlDscDatabaseProperty.Tests.ps1
  • source/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.ps1
  • tests/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.ps1
  • tests/Integration/Commands/Test-SqlDscIsDatabase.Integration.Tests.ps1

⚙️ CodeRabbit configuration file

tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1: # Integration Tests Guidelines

Requirements

  • 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-ComputerName for computer names in CI
  • Avoid ExpectedMessage for Should -Throw assertions
  • Only run integration tests in CI unless explicitly instructed.
  • Call commands with -Force parameter where applicable (avoids prompting).
  • Use -ErrorAction 'Stop' on commands so failures surface immediately

Required 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.ps1
  • tests/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.ps1
  • 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-SqlDscDatabaseProperty.Integration.Tests.ps1
  • tests/Integration/Commands/Test-SqlDscIsDatabase.Integration.Tests.ps1
  • tests/Unit/Public/Test-SqlDscIsDatabase.Tests.ps1
  • tests/Unit/Public/Test-SqlDscDatabaseProperty.Tests.ps1

⚙️ CodeRabbit configuration file

**/*.[Tt]ests.ps1: # Tests Guidelines

Core 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 Describe blocks
  • Assertions only in It blocks
  • Never test verbose messages, debug messages or parameter binding behavior
  • Pass all mandatory parameters to avoid prompts

Requirements

  • Inside It blocks, assign unused return objects to $null (unless part of pipeline)
  • Tested entity must be called from within the It blocks
  • Keep results and assertions in same It block
  • Avoid try-catch-finally for cleanup, use AfterAll or AfterEach
  • Avoid unnecessary remove/recreate cycles

Naming

  • One Describe block per file matching the tested entity name
  • Context descriptions start with 'When'
  • It descriptions 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 Context block
  • Each scenario = separate Context block
  • Use nested Context blocks for complex scenarios
  • Mocking in BeforeAll (BeforeEach only when required)
  • Setup/teardown in BeforeAll,BeforeEach/AfterAll,AfterEach close to usage

Syntax Rules

  • PascalCase: Describe, Context, It, Should, BeforeAll, BeforeEach, AfterAll, AfterEach
  • Use -BeTrue/-BeFalse never -Be $true/-Be $false
  • Never use Assert-MockCalled, use Should -Invoke instead
  • No Should -Not -Throw - invoke commands directly
  • Never add an empty -MockWith block
  • Omit -MockWith when returning $null
  • Set $PSDefaultParameterValues for Mock:ModuleName, Should:ModuleName, InModuleScope:ModuleName
  • Omit -ModuleName parameter on Pester commands
  • Never use Mock inside `InModuleSc...

Files:

  • tests/Integration/Commands/Test-SqlDscDatabaseProperty.Integration.Tests.ps1
  • tests/Integration/Commands/Test-SqlDscIsDatabase.Integration.Tests.ps1
  • tests/Unit/Public/Test-SqlDscIsDatabase.Tests.ps1
  • tests/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.md
  • tests/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 MD013 rule 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.md
  • tests/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 section

Always 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.ps1
  • tests/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 $TestDrive variable (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/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.ps1
  • tests/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.ps1
  • tests/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.ps1
  • tests/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 like KeyName = 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.yml
  • tests/Integration/Commands/Test-SqlDscIsDatabase.Integration.Tests.ps1
  • tests/Unit/Public/Test-SqlDscIsDatabase.Tests.ps1
  • tests/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.yml
  • tests/Integration/Commands/Test-SqlDscIsDatabase.Integration.Tests.ps1
  • tests/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.yml
  • tests/Integration/Commands/Test-SqlDscIsDatabase.Integration.Tests.ps1
  • tests/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.yml
  • tests/Integration/Commands/Test-SqlDscIsDatabase.Integration.Tests.ps1
  • tests/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.yml
  • tests/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.yml
  • tests/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.yml
  • 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 : 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.ps1 removed from source/Public
  • New command file Test-SqlDscIsDatabase.ps1 present 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 4

Placement and order look consistent with dependencies and existing command tests. LGTM.

tests/Integration/Commands/README.md (1)

95-96: Docs table updated for new commands

New 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 readability

Good 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 validated

Mocks + Should -Invoke checks confirm -Refresh is forwarded only when specified. LGTM.


482-487: Parameter set expectations updated to include -Refresh

Matches the ServerObjectSet contract; DatabaseObjectSet unchanged. LGTM.

source/Public/Test-SqlDscDatabaseProperty.ps1 (1)

29-38: LGTM! Refresh parameter implementation is correct.

The addition of the Refresh parameter 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:$Refresh pattern correctly passes the switch parameter state to Get-SqlDscDatabase
  • Properly excluded from property testing by removing it from $boundParameters

Also 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

Copy link

@coderabbitai coderabbitai bot left a 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 It

As 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

📥 Commits

Reviewing files that changed from the base of the PR and between a2b4c31 and f7aa355.

📒 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.ps1
  • tests/Unit/Public/Test-SqlDscIsDatabase.Tests.ps1
  • source/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 Guidelines

Requirements

  • 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-ComputerName for computer names in CI
  • Avoid ExpectedMessage for Should -Throw assertions
  • Only run integration tests in CI unless explicitly instructed.
  • Call commands with -Force parameter where applicable (avoids prompting).
  • Use -ErrorAction 'Stop' on commands so failures surface immediately

Required 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.ps1
  • tests/Unit/Public/Test-SqlDscIsDatabase.Tests.ps1
  • source/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.ps1
  • tests/Unit/Public/Test-SqlDscIsDatabase.Tests.ps1
  • source/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.ps1
  • tests/Unit/Public/Test-SqlDscIsDatabase.Tests.ps1

⚙️ CodeRabbit configuration file

**/*.[Tt]ests.ps1: # Tests Guidelines

Core 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 Describe blocks
  • Assertions only in It blocks
  • Never test verbose messages, debug messages or parameter binding behavior
  • Pass all mandatory parameters to avoid prompts

Requirements

  • Inside It blocks, assign unused return objects to $null (unless part of pipeline)
  • Tested entity must be called from within the It blocks
  • Keep results and assertions in same It block
  • Avoid try-catch-finally for cleanup, use AfterAll or AfterEach
  • Avoid unnecessary remove/recreate cycles

Naming

  • One Describe block per file matching the tested entity name
  • Context descriptions start with 'When'
  • It descriptions 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 Context block
  • Each scenario = separate Context block
  • Use nested Context blocks for complex scenarios
  • Mocking in BeforeAll (BeforeEach only when required)
  • Setup/teardown in BeforeAll,BeforeEach/AfterAll,AfterEach close to usage

Syntax Rules

  • PascalCase: Describe, Context, It, Should, BeforeAll, BeforeEach, AfterAll, AfterEach
  • Use -BeTrue/-BeFalse never -Be $true/-Be $false
  • Never use Assert-MockCalled, use Should -Invoke instead
  • No Should -Not -Throw - invoke commands directly
  • Never add an empty -MockWith block
  • Omit -MockWith when returning $null
  • Set $PSDefaultParameterValues for Mock:ModuleName, Should:ModuleName, InModuleScope:ModuleName
  • Omit -ModuleName parameter on Pester commands
  • Never use Mock inside `InModuleSc...

Files:

  • tests/Integration/Commands/Test-SqlDscIsDatabase.Integration.Tests.ps1
  • tests/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.ps1
  • tests/Unit/Public/Test-SqlDscIsDatabase.Tests.ps1
  • source/Public/Test-SqlDscIsDatabase.ps1
**

⚙️ CodeRabbit configuration file

**: # DSC Community Guidelines

Terminology

  • 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 pwsh session): ./build.ps1 -Tasks noop
  • Build project before running tests: ./build.ps1 -Tasks build
  • Always run tests in new pwsh session: Invoke-Pester -Path @({test paths}) -Output Detailed

File 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.ps1

Requirements

  • 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.ps1
  • tests/Unit/Public/Test-SqlDscIsDatabase.Tests.ps1
  • source/Public/Test-SqlDscIsDatabase.ps1
{**/*.ps1,**/*.psm1,**/*.psd1}

⚙️ CodeRabbit configuration file

{**/*.ps1,**/*.psm1,**/*.psd1}: # PowerShell Guidelines

Naming

  • 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.ps1 format (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 array

Hashtables

  • 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.ps1
  • tests/Unit/Public/Test-SqlDscIsDatabase.Tests.ps1
  • source/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 $TestDrive variable (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 Guidelines

Requirements

  • Localize all Write-Debug, Write-Verbose, Write-Error, Write-Warning and $PSCmdlet.ThrowTerminatingError() messages
  • Use localized string keys, not hardcoded strings
  • Assume $script:localizedData is available

String Files

  • Commands/functions: source/en-US/{MyModuleName}.strings.psd1
  • Class resources: source/en-US/{ResourceClassName}.strings.psd1

Key Naming Patterns

  • Format: Verb_FunctionName_Action (underscore separators), e.g. Get_Database_ConnectingToDatabase

String 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.ps1
  • tests/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.ps1
  • tests/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.ps1
  • 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 : 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
  • tests/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.ps1
  • tests/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

@codecov
Copy link

codecov bot commented Oct 26, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94%. Comparing base (4423284) to head (cd79e93).
⚠️ Report is 27 commits behind head on main.

Additional details and impacted files

Impacted file tree graph

@@         Coverage Diff          @@
##           main   #2325   +/-   ##
====================================
- Coverage    94%     94%   -1%     
====================================
  Files       152     152           
  Lines      9299    9277   -22     
====================================
- Hits       8811    8790   -21     
+ Misses      488     487    -1     
Flag Coverage Δ
unit 94% <100%> (-1%) ⬇️
Files with missing lines Coverage Δ
source/Public/Test-SqlDscDatabaseProperty.ps1 93% <100%> (ø)
source/Public/Test-SqlDscIsDatabase.ps1 100% <100%> (ø)
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Copy link
Member Author

@johlju johlju left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

:lgtm:

@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: :shipit: complete! all files reviewed, all discussions resolved (waiting on @johlju)

@johlju johlju merged commit d6111a3 into dsccommunity:main Oct 26, 2025
31 checks passed
@johlju johlju deleted the fix/refresh-parameter branch October 26, 2025 19:19
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Test-SqlDscIsDatabase: Command rename proposal

1 participant