Skip to content

Add integration tests for Initialize-SqlDscRebuildDatabase#2309

Merged
johlju merged 4 commits intodsccommunity:mainfrom
johlju:fix/issue-#2242
Oct 19, 2025
Merged

Add integration tests for Initialize-SqlDscRebuildDatabase#2309
johlju merged 4 commits intodsccommunity:mainfrom
johlju:fix/issue-#2242

Conversation

@johlju
Copy link
Copy Markdown
Member

@johlju johlju commented Oct 18, 2025

Description

This pull request resolves issue #2242 by implementing comprehensive integration tests for the Initialize-SqlDscRebuildDatabase command.

Changes

Files Added

  • tests/Integration/Commands/Initialize-SqlDscRebuildDatabase.Integration.Tests.ps1 - New integration test file

Files Modified

  • tests/Integration/Commands/README.md - Added test documentation and dependency information
  • azure-pipelines.yml - Added new test to Group 8 in the Integration_Test_Commands_SqlServer stage
  • CHANGELOG.md - Documented the new integration tests in the Unreleased section

Test Coverage

The integration tests cover the following scenarios:

  1. Basic Rebuild with Mandatory Parameters

    • Tests rebuild with only required parameters (InstanceName, SqlSysAdminAccounts, MediaPath)
    • Verifies the service starts successfully after rebuild
    • Validates connectivity to the instance after rebuild
  2. Rebuild with TempDB Parameters

    • Tests rebuild with custom TempDB file count
    • Ensures service stability with configuration changes
  3. Rebuild with Custom Collation

    • Tests rebuild with custom SQL collation setting
    • Verifies proper database initialization

Testing

  • All tests follow SqlServerDsc integration test guidelines
  • Tests run in group 8, alongside Repair-SqlDscServer
  • Tests depend on order 1 (Install-SqlDscServer)
  • Supports SQL Server 2017, 2019, and 2022

Checklist

  • Integration test file created with proper structure
  • Test documentation updated in README.md
  • Azure Pipelines configuration updated
  • CHANGELOG.md updated with new tests entry
  • Follows SqlServerDsc community guidelines
  • Tests cover mandatory and optional parameters

This change is Reviewable

@johlju johlju requested a review from a team as a code owner October 18, 2025 15:16
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Oct 18, 2025

Walkthrough

Adds a new PowerShell integration test suite for Initialize-SqlDscRebuildDatabase, registers it in the Azure Pipelines SQL Server integration tests, updates CHANGELOG/README, and marks Repair-SqlDscServer integration test as skipped. Tests exercise rebuild scenarios, service lifecycle, and connectivity verification. (≤50 words)

Changes

Cohort / File(s) Summary
Pipeline configuration
azure-pipelines.yml
Registers Initialize-SqlDscRebuildDatabase.Integration.Tests.ps1 in Group 8 of the Integration Test Commands - SQL Server stage.
New integration tests
tests/Integration/Commands/Initialize-SqlDscRebuildDatabase.Integration.Tests.ps1
New PowerShell integration test suite: setup (BeforeDiscovery/BeforeAll), multi-version Describe blocks, mandatory and optional parameter scenarios, service stop/start around tests, connectivity checks, failure diagnostics, and splatted parameter usage.
Existing integration test update
tests/Integration/Commands/Repair-SqlDscServer.Integration.Tests.ps1
Test execution changed to skipped (-Skip added) with an explanatory note; structure and content preserved.
Changelog & docs
CHANGELOG.md, tests/Integration/Commands/README.md
CHANGELOG notes the added integration test and references issue #2242; README updated to list Initialize-SqlDscRebuildDatabase and include it among Uninstall-SqlDscServer dependencies.

Sequence Diagram(s)

sequenceDiagram
    participant TR as Test Runner
    participant Prep as BeforeDiscovery/BeforeAll
    participant Service as MSSQL$DSCSQLTEST Service
    participant Cmd as Initialize-SqlDscRebuildDatabase
    participant Engine as SQL Engine

    Note over TR,Prep: Test preparation
    TR->>Prep: Import module, resolve dependencies
    Prep->>Service: Ensure pre-test state (stop/start)
    TR->>Cmd: Invoke rebuild (splat params)
    Cmd->>Service: Perform rebuild & restart service
    Cmd->>Engine: Connect to validate engine
    Engine-->>Cmd: Connection result
    Cmd-->>TR: Return test outcome
    TR->>Service: Teardown (restore service state)
    Note over TR,Engine: Verify service status and connectivity
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related issues

Pre-merge checks

✅ Passed checks (3 passed)
Check name Status Explanation
Title Check ✅ Passed The pull request title "Add integration tests for Initialize-SqlDscRebuildDatabase" is clear, concise, and directly reflects the primary change in the changeset. The title accurately summarizes the main objective of adding a new integration test file for a specific command, which aligns with the modifications to CHANGELOG.md, azure-pipelines.yml, README.md, and the new test file itself. A developer scanning the repository history would immediately understand that this PR adds integration tests for the Initialize-SqlDscRebuildDatabase command.
Description Check ✅ Passed The pull request description is well-structured and directly related to the changeset. It clearly identifies the issue being resolved (#2242), lists all files added and modified, provides detailed test coverage scenarios, and explains the testing approach. The description goes beyond the minimum requirements by outlining specific test cases and including a completion checklist, demonstrating thorough documentation of the changes made.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.

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
Copy Markdown

@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 (4)
tests/Integration/Commands/Initialize-SqlDscRebuildDatabase.Integration.Tests.ps1 (4)

34-54: Make service stop deterministic; fail fast on precondition errors.

Replace sleeps and Write-Error with a bounded wait loop and throw to ensure failures stop the run.

Apply:

-        if ($sqlService.Status -eq 'Running')
-        {
-            Write-Verbose -Message "Stopping SQL Server service '$serviceName'..." -Verbose
-            Stop-Service -Name $serviceName -Force -ErrorAction 'Stop'
-            Start-Sleep -Seconds 5
-        }
-
-        # Verify service is stopped
-        $sqlService = Get-Service -Name $serviceName -ErrorAction 'Stop'
-        if ($sqlService.Status -ne 'Stopped')
-        {
-            Write-Error -Message "Failed to stop SQL Server service '$serviceName'"
-        }
+        if ($sqlService.Status -eq 'Running')
+        {
+            Write-Verbose -Message "Stopping SQL Server service '$serviceName'..." -Verbose
+            Stop-Service -Name $serviceName -Force -ErrorAction 'Stop'
+        }
+
+        # Wait for Stopped (max 2 minutes)
+        $deadline = (Get-Date).AddMinutes(2)
+        while ((Get-Service -Name $serviceName -ErrorAction 'Stop').Status -ne 'Stopped' -and (Get-Date) -lt $deadline)
+        {
+            Start-Sleep -Seconds 2
+        }
+        if ((Get-Service -Name $serviceName -ErrorAction 'Stop').Status -ne 'Stopped')
+        {
+            throw "Failed to stop SQL Server service '$serviceName' within 2 minutes."
+        }

56-74: Symmetric start logic: wait for Running and throw on failure.

Avoid fixed sleeps; wait with timeout and throw if not Running.

Apply:

-        if ($sqlService.Status -ne 'Running')
-        {
-            Write-Verbose -Message "Starting SQL Server service '$serviceName'..." -Verbose
-            Start-Service -Name $serviceName -ErrorAction 'Stop'
-            Start-Sleep -Seconds 10
-        }
-
-        # Verify service is running
-        $sqlService = Get-Service -Name $serviceName -ErrorAction 'Stop'
-        if ($sqlService.Status -ne 'Running')
-        {
-            Write-Error -Message "Failed to start SQL Server service '$serviceName'"
-        }
+        if ($sqlService.Status -ne 'Running')
+        {
+            Write-Verbose -Message "Starting SQL Server service '$serviceName'..." -Verbose
+            Start-Service -Name $serviceName -ErrorAction 'Stop'
+        }
+
+        # Wait for Running (max 2 minutes)
+        $deadline = (Get-Date).AddMinutes(2)
+        while ((Get-Service -Name $serviceName -ErrorAction 'Stop').Status -ne 'Running' -and (Get-Date) -lt $deadline)
+        {
+            Start-Sleep -Seconds 2
+        }
+        if ((Get-Service -Name $serviceName -ErrorAction 'Stop').Status -ne 'Running')
+        {
+            throw "Failed to start SQL Server service '$serviceName' within 2 minutes."
+        }

94-101: Avoid fixed sleeps when checking service state.

Replace Start-Sleep with a bounded wait for Running to reduce flakiness.

Apply:

-                Start-Service -Name $serviceName -ErrorAction 'Stop'
-                Start-Sleep -Seconds 10
+                Start-Service -Name $serviceName -ErrorAction 'Stop'
+                $deadline = (Get-Date).AddMinutes(2)
+                while ((Get-Service -Name $serviceName -ErrorAction 'Stop').Status -ne 'Running' -and (Get-Date) -lt $deadline)
+                {
+                    Start-Sleep -Seconds 2
+                }

32-176: Small cleanup: define $serviceName once at Describe scope.

Avoid repetition; set once and reuse.

Apply:

-Describe 'Initialize-SqlDscRebuildDatabase' -Tag @('Integration_SQL2017', 'Integration_SQL2019', 'Integration_SQL2022') {
+Describe 'Initialize-SqlDscRebuildDatabase' -Tag @('Integration_SQL2017', 'Integration_SQL2019', 'Integration_SQL2022') {
+    $serviceName = 'MSSQL$DSCSQLTEST'

Then drop repeated reassignments of $serviceName inside blocks.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 01f5034 and 3a97cb1.

📒 Files selected for processing (4)
  • CHANGELOG.md (1 hunks)
  • azure-pipelines.yml (1 hunks)
  • tests/Integration/Commands/Initialize-SqlDscRebuildDatabase.Integration.Tests.ps1 (1 hunks)
  • tests/Integration/Commands/README.md (1 hunks)
🧰 Additional context used
📓 Path-based instructions (11)
azure-pipelines.yml

📄 CodeRabbit inference engine (.github/instructions/SqlServerDsc-guidelines.instructions.md)

Integration test script files must be added to a group within the test stage in ./azure-pipelines.yml, choosing an appropriate group number based on dependencies

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
  • tests/Integration/Commands/Initialize-SqlDscRebuildDatabase.Integration.Tests.ps1
  • CHANGELOG.md
  • tests/Integration/Commands/README.md
**/*.[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
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
Inside It blocks, assign unused return objects to $null (unless part of a pipeline)
Call the tested entity from within the It blocks
Keep results and assertions in the same It block
Avoid try/catch/finally for cleanup; use AfterAll or AfterEach
Avoid unnecessary remove/recreate cycles
One Describe block per file matching the tested entity name
Context descriptions start with 'When'
It descriptions start with 'Should' and must not contain 'when'
Mock variables must be prefixed with 'mock'
Public commands: never use InModuleScope (except for retrieving localized strings)
Private functions and class resources: always use InModuleScope
Each class method gets a separate Context block
Each scenario gets a separate Context block
Use nested Context blocks for complex scenarios
Perform mocking in BeforeAll (use BeforeEach only when required)
Place setup/teardown (BeforeAll/BeforeEach/AfterAll/AfterEach) close to usage
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 returning $null
Set $PSDefaultParameterValues 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 a separate BeforeDiscovery near usage
Use -ForEach only on Context and It blocks
Keep variable scope close to the usage c...

Files:

  • tests/Integration/Commands/Initialize-SqlDscRebuildDatabase.Integration.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/Initialize-SqlDscRebuildDatabase.Integration.Tests.ps1
**/*.{ps1,psm1}

📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-powershell.instructions.md)

**/*.{ps1,psm1}: Use descriptive names (3+ characters, no abbreviations)
Function names use PascalCase Verb-Noun with approved verbs
Parameter names use PascalCase
Variable names use camelCase
Keywords are lower-case
Class names use PascalCase
Include scope prefixes 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))
Place 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)
Use single quotes unless variable expansion is needed
Arrays on one line use @('one','two'); multi-line arrays have one element per line with proper indentation
Do not use unary comma in return statements to force an array
Single-line comments: '# Comment' capitalized on its own line
Multi-line comments use <# #> with brackets on their own lines and indented text
No commented-out code
Add comment-based help to all functions and scripts
Comment-based help must include SYNOPSIS, DESCRIPTION (40+ chars), PARAMETER, and EXAMPLE sections before function/class
Comment-based help indentation: keywords at 4 spaces, text at 8 spaces
Include examples for all parameter sets and combinations
INPUTS: list each pipeline-accepted type with one-line description; repeat .INPUTS per type
OUTPUTS: list each return type with one-line description; repeat .OUTPUTS per type; must match [OutputType()] and actual returns
.NOTES only if critical (constraints, side effects, security, version compatibility, breaking behavior), ≤2 short sentences
Avoid aliases; use full command names
Avoid Write-Host; prefer Write-Verbose/Write-Information/etc.
Avoid Write-Output; use return instead
Do not use ConvertTo-SecureString -AsPlainText in production code
Do not redefine reserved parameters (Verbose, Debug, etc.)
In...

Files:

  • tests/Integration/Commands/Initialize-SqlDscRebuildDatabase.Integration.Tests.ps1
**/*.{ps1,psm1,psd1}

📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-powershell.instructions.md)

**/*.{ps1,psm1,psd1}: Indent with 4 spaces; do not use tabs
No spaces on empty lines
Try to limit lines to 120 characters
Empty hashtable is @{}
Hashtable: each property on its own line with proper indentation
Hashtable property names use PascalCase
End files with exactly one blank line
Use line endings as defined by .gitattributes policy
Allow at most two consecutive newlines
No trailing whitespace on any line
Use UTF-8 encoding without BOM for all files

Files:

  • tests/Integration/Commands/Initialize-SqlDscRebuildDatabase.Integration.Tests.ps1
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/Initialize-SqlDscRebuildDatabase.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/Initialize-SqlDscRebuildDatabase.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/Initialize-SqlDscRebuildDatabase.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/Initialize-SqlDscRebuildDatabase.Integration.Tests.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/Initialize-SqlDscRebuildDatabase.Integration.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
🧠 Learnings (17)
📓 Common learnings
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-09-23T10:20:59.832Z
Learning: Integration tests must use Connect-SqlDscDatabaseEngine with correct CI credentials and call Disconnect-SqlDscDatabaseEngine after
📚 Learning: 2025-09-23T10:20:59.832Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-09-23T10:20:59.832Z
Learning: Applies to azure-pipelines.yml : Integration test script files must be added to a group within the test stage in ./azure-pipelines.yml, choosing an appropriate group number based on dependencies

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 : Call commands with -Force where applicable to avoid prompting

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/Integration/Commands/*.Integration.Tests.ps1 : Add integration tests for all public commands (and resources)

Applied to files:

  • azure-pipelines.yml
  • tests/Integration/Commands/Initialize-SqlDscRebuildDatabase.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
  • tests/Integration/Commands/Initialize-SqlDscRebuildDatabase.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/Integration/Commands/*.Integration.Tests.ps1 : Place command integration tests at tests/Integration/Commands/{CommandName}.Integration.Tests.ps1

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/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
📚 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-12T13:21:31.054Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-09-12T13:21:31.054Z
Learning: Applies to **/*.[Tt]ests.ps1 : All public commands and class-based resources must have 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-12T13:21:31.054Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-09-12T13:21:31.054Z
Learning: Applies to **/*.[Tt]ests.ps1 : Cover all scenarios and code paths

Applied to files:

  • azure-pipelines.yml
📚 Learning: 2025-09-12T13:21:31.054Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-09-12T13:21:31.054Z
Learning: Applies to **/*.[Tt]ests.ps1 : Avoid unnecessary remove/recreate cycles

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/Initialize-SqlDscRebuildDatabase.Integration.Tests.ps1
📚 Learning: 2025-09-23T10:20:59.832Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-09-23T10:20:59.832Z
Learning: In unit tests, add $env:SqlServerDscCI = $true in BeforeAll and remove it in AfterAll

Applied to files:

  • tests/Integration/Commands/Initialize-SqlDscRebuildDatabase.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/Initialize-SqlDscRebuildDatabase.Integration.Tests.ps1
📚 Learning: 2025-10-11T08:18:26.062Z
Learnt from: johlju
PR: dsccommunity/SqlServerDsc#2300
File: tests/Unit/DSC_SqlAGDatabase.Tests.ps1:22-22
Timestamp: 2025-10-11T08:18:26.062Z
Learning: In unit test files (tests/[Uu]nit/**/*.[Tt]ests.ps1), when DscResource.Test module dependency is not found during BeforeDiscovery setup, the error message should instruct users to run ".\build.ps1 -Tasks noop" (not "build") because the noop task is designed for quick test environment setup. The build task is more extensive and unnecessary when tests run in a separate process, as the module should already be built before running tests.

Applied to files:

  • tests/Integration/Commands/Initialize-SqlDscRebuildDatabase.Integration.Tests.ps1
📚 Learning: 2025-09-23T10:20:59.832Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-09-23T10:20:59.832Z
Learning: Testing CI environment instances: DSCSQLTEST (Database Engine), SSRS (Reporting Services), PBIRS (Power BI Report Server)

Applied to files:

  • tests/Integration/Commands/README.md
⏰ 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 (6)
CHANGELOG.md (1)

10-13: Changelog entry looks good

The new Unreleased note follows the Keep a Changelog guidance (brief summary, command name in backticks, correct issue link).

azure-pipelines.yml (1)

369-371: Integration suite update confirmed

Placing Initialize-SqlDscRebuildDatabase in Group 8 alongside Repair-SqlDscServer keeps the dependency chain intact and satisfies the requirement to register new command tests within the existing group ordering.

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

124-125: Run-order documentation aligned

Nice touch documenting Initialize-SqlDscRebuildDatabase at run order 8 and updating Uninstall-SqlDscServer’s dependencies—this mirrors the pipeline change and keeps contributors in sync.

tests/Integration/Commands/Initialize-SqlDscRebuildDatabase.Integration.Tests.ps1 (3)

4-24: Good: Required Pester setup block is present and correct.

BeforeDiscovery resolves DscResource.Test with the noop fallback, and the module is imported in BeforeAll. LGTM.


78-93: Basic rebuild invocation looks good.

Mandatory params + Force and -ErrorAction 'Stop' are passed; unused output assigned to $null. LGTM.


103-119: Do not use non-existent environment variables; add -ErrorAction to Disconnect call.

The suggested environment variables $env:SqlDsc_SqlAdminUsername and $env:SqlDsc_SqlAdminPassword are not provided by the CI pipeline and are not used anywhere in the codebase. All integration tests currently use hardcoded credentials (SqlAdmin / P@ssw0rd1), which is consistent with the existing pattern.

The valid concern is the missing -ErrorAction 'Stop' on the Disconnect call:

-                Disconnect-SqlDscDatabaseEngine -ServerObject $serverObject
+                Disconnect-SqlDscDatabaseEngine -ServerObject $serverObject -ErrorAction 'Stop'

Address the hardcoded credentials concern separately through a broader CI infrastructure change, not by referencing non-existent environment variables.

Likely an incorrect or invalid review comment.

@codecov
Copy link
Copy Markdown

codecov Bot commented Oct 18, 2025

Codecov Report

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

Additional details and impacted files

Impacted file tree graph

@@         Coverage Diff          @@
##           main   #2309   +/-   ##
====================================
  Coverage    94%     94%           
====================================
  Files       150     150           
  Lines      9239    9239           
====================================
  Hits       8751    8751           
  Misses      488     488           
Flag Coverage Δ
unit 94% <ø> (ø)
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Copy link
Copy Markdown

@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: 1

♻️ Duplicate comments (2)
tests/Integration/Commands/Initialize-SqlDscRebuildDatabase.Integration.Tests.ps1 (2)

151-205: Assert TempDB file count to validate SqlTempDbFileCount scenario.

The test sets SqlTempDbFileCount = 8 but only verifies service status, not the actual TempDB file count. This was flagged in a previous review and remains unaddressed.

Apply this diff to add the missing assertion:

             It 'Should have the SQL Server service running after rebuild with TempDB parameters' {
                 $serviceName = 'MSSQL$DSCSQLTEST'
                 Start-Service -Name $serviceName -ErrorAction 'Stop'
                 Start-Sleep -Seconds 10

                 $sqlService = Get-Service -Name $serviceName -ErrorAction 'Stop'
                 $sqlService.Status | Should -Be 'Running'
             }
+
+            It 'Should configure the requested TempDB data file count' {
+                $computerName = Get-ComputerName
+                $mockSqlAdministratorUserName = '{0}\SqlAdmin' -f $computerName
+                $mockSqlAdministratorPassword = ConvertTo-SecureString -String 'P@ssw0rd1' -AsPlainText -Force
+                $mockSqlAdminCredential = [System.Management.Automation.PSCredential]::new($mockSqlAdministratorUserName, $mockSqlAdministratorPassword)
+
+                $serverObject = Connect-SqlDscDatabaseEngine -InstanceName 'DSCSQLTEST' -Credential $mockSqlAdminCredential -ErrorAction 'Stop'
+                $serverObject.Databases['tempdb'].FileGroups['PRIMARY'].Files.Count | Should -Be 8
+                Disconnect-SqlDscDatabaseEngine -ServerObject $serverObject -ErrorAction 'Stop'
+            }

207-261: Assert server collation to validate SqlCollation scenario.

The test sets SqlCollation = 'SQL_Latin1_General_CP1_CI_AS' but only verifies service status, not the actual server collation. This was flagged in a previous review and remains unaddressed.

Apply this diff to add the missing assertion:

             It 'Should have the SQL Server service running after rebuild with collation' {
                 $serviceName = 'MSSQL$DSCSQLTEST'
                 Start-Service -Name $serviceName -ErrorAction 'Stop'
                 Start-Sleep -Seconds 10

                 $sqlService = Get-Service -Name $serviceName -ErrorAction 'Stop'
                 $sqlService.Status | Should -Be 'Running'
             }
+
+            It 'Should set the requested server collation' {
+                $computerName = Get-ComputerName
+                $mockSqlAdministratorUserName = '{0}\SqlAdmin' -f $computerName
+                $mockSqlAdministratorPassword = ConvertTo-SecureString -String 'P@ssw0rd1' -AsPlainText -Force
+                $mockSqlAdminCredential = [System.Management.Automation.PSCredential]::new($mockSqlAdministratorUserName, $mockSqlAdministratorPassword)
+
+                $serverObject = Connect-SqlDscDatabaseEngine -InstanceName 'DSCSQLTEST' -Credential $mockSqlAdminCredential -ErrorAction 'Stop'
+                $serverObject.Collation | Should -Be 'SQL_Latin1_General_CP1_CI_AS'
+                Disconnect-SqlDscDatabaseEngine -ServerObject $serverObject -ErrorAction 'Stop'
+            }
🧹 Nitpick comments (2)
tests/Integration/Commands/Initialize-SqlDscRebuildDatabase.Integration.Tests.ps1 (2)

35-75: Consider extracting the service name to a variable.

The service name 'MSSQL$DSCSQLTEST' is repeated throughout the file. Extracting it to a variable in the outermost BeforeAll block would improve maintainability.

Apply this diff to extract the service name:

 BeforeAll {
+    $script:serviceName = 'MSSQL$DSCSQLTEST'
+
     Write-Verbose -Message ('Running integration test as user ''{0}''.' -f $env:UserName) -Verbose

     # Stop the SQL Server instance so we can rebuild the databases
-    $serviceName = 'MSSQL$DSCSQLTEST'
-    $sqlService = Get-Service -Name $serviceName -ErrorAction 'Stop'
+    $sqlService = Get-Service -Name $script:serviceName -ErrorAction 'Stop'

Then reference $script:serviceName throughout the file (lines 59, 124, 198, 254).


95-120: Consider extracting error handling logic to reduce duplication.

The error handling block that outputs Summary.txt content is duplicated three times (lines 95-120, 169-194, 225-250). Extracting this to a helper function would improve maintainability.

Example helper function to add before the Describe block:

function Write-SqlSetupSummary
{
    [CmdletBinding()]
    param ()

    $summaryFiles = Get-ChildItem -Path 'C:\Program Files\Microsoft SQL Server' -Filter 'Summary.txt' -Recurse -ErrorAction SilentlyContinue |
        Where-Object { $_.FullName -match '\\Setup Bootstrap\\Log\\' } |
        Sort-Object -Property LastWriteTime -Descending |
        Select-Object -First 1

    if ($summaryFiles)
    {
        Write-Verbose "==== SQL Server Setup Summary.txt (from $($summaryFiles.FullName)) ====" -Verbose
        Get-Content -Path $summaryFiles.FullName | Write-Verbose -Verbose
        Write-Verbose "==== End of Summary.txt ====" -Verbose
    }
    else
    {
        Write-Verbose 'No Summary.txt file found.' -Verbose
    }
}

Then replace each catch block with:

catch
{
    Write-SqlSetupSummary
    throw $_
}

Also applies to: 169-194, 225-250

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 85d06fa and 0b7efb7.

📒 Files selected for processing (1)
  • tests/Integration/Commands/Initialize-SqlDscRebuildDatabase.Integration.Tests.ps1 (1 hunks)
🧰 Additional context used
📓 Path-based instructions (8)
**/*.[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
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
Inside It blocks, assign unused return objects to $null (unless part of a pipeline)
Call the tested entity from within the It blocks
Keep results and assertions in the same It block
Avoid try/catch/finally for cleanup; use AfterAll or AfterEach
Avoid unnecessary remove/recreate cycles
One Describe block per file matching the tested entity name
Context descriptions start with 'When'
It descriptions start with 'Should' and must not contain 'when'
Mock variables must be prefixed with 'mock'
Public commands: never use InModuleScope (except for retrieving localized strings)
Private functions and class resources: always use InModuleScope
Each class method gets a separate Context block
Each scenario gets a separate Context block
Use nested Context blocks for complex scenarios
Perform mocking in BeforeAll (use BeforeEach only when required)
Place setup/teardown (BeforeAll/BeforeEach/AfterAll/AfterEach) close to usage
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 returning $null
Set $PSDefaultParameterValues 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 a separate BeforeDiscovery near usage
Use -ForEach only on Context and It blocks
Keep variable scope close to the usage c...

Files:

  • tests/Integration/Commands/Initialize-SqlDscRebuildDatabase.Integration.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/Initialize-SqlDscRebuildDatabase.Integration.Tests.ps1
**/*.{ps1,psm1}

📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-powershell.instructions.md)

**/*.{ps1,psm1}: Use descriptive names (3+ characters, no abbreviations)
Function names use PascalCase Verb-Noun with approved verbs
Parameter names use PascalCase
Variable names use camelCase
Keywords are lower-case
Class names use PascalCase
Include scope prefixes 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))
Place 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)
Use single quotes unless variable expansion is needed
Arrays on one line use @('one','two'); multi-line arrays have one element per line with proper indentation
Do not use unary comma in return statements to force an array
Single-line comments: '# Comment' capitalized on its own line
Multi-line comments use <# #> with brackets on their own lines and indented text
No commented-out code
Add comment-based help to all functions and scripts
Comment-based help must include SYNOPSIS, DESCRIPTION (40+ chars), PARAMETER, and EXAMPLE sections before function/class
Comment-based help indentation: keywords at 4 spaces, text at 8 spaces
Include examples for all parameter sets and combinations
INPUTS: list each pipeline-accepted type with one-line description; repeat .INPUTS per type
OUTPUTS: list each return type with one-line description; repeat .OUTPUTS per type; must match [OutputType()] and actual returns
.NOTES only if critical (constraints, side effects, security, version compatibility, breaking behavior), ≤2 short sentences
Avoid aliases; use full command names
Avoid Write-Host; prefer Write-Verbose/Write-Information/etc.
Avoid Write-Output; use return instead
Do not use ConvertTo-SecureString -AsPlainText in production code
Do not redefine reserved parameters (Verbose, Debug, etc.)
In...

Files:

  • tests/Integration/Commands/Initialize-SqlDscRebuildDatabase.Integration.Tests.ps1
**/*.{ps1,psm1,psd1}

📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-powershell.instructions.md)

**/*.{ps1,psm1,psd1}: Indent with 4 spaces; do not use tabs
No spaces on empty lines
Try to limit lines to 120 characters
Empty hashtable is @{}
Hashtable: each property on its own line with proper indentation
Hashtable property names use PascalCase
End files with exactly one blank line
Use line endings as defined by .gitattributes policy
Allow at most two consecutive newlines
No trailing whitespace on any line
Use UTF-8 encoding without BOM for all files

Files:

  • tests/Integration/Commands/Initialize-SqlDscRebuildDatabase.Integration.Tests.ps1
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/Initialize-SqlDscRebuildDatabase.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/Initialize-SqlDscRebuildDatabase.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/Initialize-SqlDscRebuildDatabase.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/Initialize-SqlDscRebuildDatabase.Integration.Tests.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/Initialize-SqlDscRebuildDatabase.Integration.Tests.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/Initialize-SqlDscRebuildDatabase.Integration.Tests.ps1
🧠 Learnings (4)
📓 Common learnings
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)
📚 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/Initialize-SqlDscRebuildDatabase.Integration.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/Initialize-SqlDscRebuildDatabase.Integration.Tests.ps1
📚 Learning: 2025-09-23T10:20:59.832Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-09-23T10:20:59.832Z
Learning: In unit tests, add $env:SqlServerDscCI = $true in BeforeAll and remove it in AfterAll

Applied to files:

  • tests/Integration/Commands/Initialize-SqlDscRebuildDatabase.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
🔇 Additional comments (1)
tests/Integration/Commands/Initialize-SqlDscRebuildDatabase.Integration.Tests.ps1 (1)

1-31: LGTM! Required setup blocks are correctly implemented.

The file includes the required SuppressMessage attributes, BeforeDiscovery block for dependency resolution, and BeforeAll block for module import, all following the integration test guidelines.

Copy link
Copy Markdown

@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: 1

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0b7efb7 and cc4e485.

📒 Files selected for processing (1)
  • tests/Integration/Commands/Repair-SqlDscServer.Integration.Tests.ps1 (3 hunks)
🧰 Additional context used
📓 Path-based instructions (8)
**/*.[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
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
Inside It blocks, assign unused return objects to $null (unless part of a pipeline)
Call the tested entity from within the It blocks
Keep results and assertions in the same It block
Avoid try/catch/finally for cleanup; use AfterAll or AfterEach
Avoid unnecessary remove/recreate cycles
One Describe block per file matching the tested entity name
Context descriptions start with 'When'
It descriptions start with 'Should' and must not contain 'when'
Mock variables must be prefixed with 'mock'
Public commands: never use InModuleScope (except for retrieving localized strings)
Private functions and class resources: always use InModuleScope
Each class method gets a separate Context block
Each scenario gets a separate Context block
Use nested Context blocks for complex scenarios
Perform mocking in BeforeAll (use BeforeEach only when required)
Place setup/teardown (BeforeAll/BeforeEach/AfterAll/AfterEach) close to usage
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 returning $null
Set $PSDefaultParameterValues 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 a separate BeforeDiscovery near usage
Use -ForEach only on Context and It blocks
Keep variable scope close to the usage c...

Files:

  • tests/Integration/Commands/Repair-SqlDscServer.Integration.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/Repair-SqlDscServer.Integration.Tests.ps1
**/*.{ps1,psm1}

📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-powershell.instructions.md)

**/*.{ps1,psm1}: Use descriptive names (3+ characters, no abbreviations)
Function names use PascalCase Verb-Noun with approved verbs
Parameter names use PascalCase
Variable names use camelCase
Keywords are lower-case
Class names use PascalCase
Include scope prefixes 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))
Place 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)
Use single quotes unless variable expansion is needed
Arrays on one line use @('one','two'); multi-line arrays have one element per line with proper indentation
Do not use unary comma in return statements to force an array
Single-line comments: '# Comment' capitalized on its own line
Multi-line comments use <# #> with brackets on their own lines and indented text
No commented-out code
Add comment-based help to all functions and scripts
Comment-based help must include SYNOPSIS, DESCRIPTION (40+ chars), PARAMETER, and EXAMPLE sections before function/class
Comment-based help indentation: keywords at 4 spaces, text at 8 spaces
Include examples for all parameter sets and combinations
INPUTS: list each pipeline-accepted type with one-line description; repeat .INPUTS per type
OUTPUTS: list each return type with one-line description; repeat .OUTPUTS per type; must match [OutputType()] and actual returns
.NOTES only if critical (constraints, side effects, security, version compatibility, breaking behavior), ≤2 short sentences
Avoid aliases; use full command names
Avoid Write-Host; prefer Write-Verbose/Write-Information/etc.
Avoid Write-Output; use return instead
Do not use ConvertTo-SecureString -AsPlainText in production code
Do not redefine reserved parameters (Verbose, Debug, etc.)
In...

Files:

  • tests/Integration/Commands/Repair-SqlDscServer.Integration.Tests.ps1
**/*.{ps1,psm1,psd1}

📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-powershell.instructions.md)

**/*.{ps1,psm1,psd1}: Indent with 4 spaces; do not use tabs
No spaces on empty lines
Try to limit lines to 120 characters
Empty hashtable is @{}
Hashtable: each property on its own line with proper indentation
Hashtable property names use PascalCase
End files with exactly one blank line
Use line endings as defined by .gitattributes policy
Allow at most two consecutive newlines
No trailing whitespace on any line
Use UTF-8 encoding without BOM for all files

Files:

  • tests/Integration/Commands/Repair-SqlDscServer.Integration.Tests.ps1
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/Repair-SqlDscServer.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/Repair-SqlDscServer.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/Repair-SqlDscServer.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/Repair-SqlDscServer.Integration.Tests.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/Repair-SqlDscServer.Integration.Tests.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/Repair-SqlDscServer.Integration.Tests.ps1
🧠 Learnings (1)
📓 Common learnings
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)
⏰ 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

@johlju
Copy link
Copy Markdown
Member Author

johlju commented Oct 19, 2025

@coderabbitai please add an issue to track the nitpick comment:

95-120: Consider extracting error handling logic to reduce duplication.

The error handling block that outputs Summary.txt content is duplicated three times (lines 95-120, 169-194, 225-250). Extracting this to a helper function would improve maintainability.

Example helper function to add before the Describe block:

function Get-SqlDscSetupLog
{
    [CmdletBinding()]
    param ()

    $summaryFiles = Get-ChildItem -Path 'C:\Program Files\Microsoft SQL Server' -Filter 'Summary.txt' -Recurse -ErrorAction 'SilentlyContinue' |
        Where-Object { $_.FullName -match '\\Setup Bootstrap\\Log\\' } |
        Sort-Object -Property 'LastWriteTime' -Descending |
        Select-Object -First 1

    if ($summaryFiles)
    {
        "==== SQL Server Setup Summary.txt (from $($summaryFiles.FullName)) ===="
        Get-Content -Path $summaryFiles.FullName
        "==== End of Summary.txt ===="
    }
    else
    {
        'No Summary.txt file found.' 
    }
}

Then replace each catch block with:

catch
{
    Write-Verbose -Message (Get-SqlSetupLog) -Verbose
    throw $_
}
Also applies to: 169-194, 225-250

We should also re-use this for all integration tests needing this functionality, also this should be a public command that users can run interactively to get the setup bootstrap log. The user should be able to pass parameters to control the behaviour of the command, like path and filename but use the default values.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Oct 19, 2025

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Create a GitHub issue to track the refactoring of error handling logic

gh issue create \
  --title "Add public command Get-SqlDscSetupLog to retrieve SQL Server setup bootstrap logs" \
  --body "## Description

Extract the duplicated error handling logic from integration tests into a new public command that retrieves SQL Server setup bootstrap logs (Summary.txt).

## Background

Currently, the error handling block that outputs Summary.txt content is duplicated across multiple integration tests. For example, in the Initialize-SqlDscRebuildDatabase integration test, this pattern appears three times (lines 95-120, 169-194, 225-250).

## Proposal

Create a new public command \`Get-SqlDscSetupLog\` that:
- Retrieves the SQL Server setup bootstrap log (Summary.txt)
- Can be used interactively by users
- Accepts parameters to control behavior (e.g., path and filename) with sensible default values
- Can be reused across all integration tests needing this functionality

### Example implementation structure:

\`\`\`powershell
function Get-SqlDscSetupLog
{
    [CmdletBinding()]
    param (
        [Parameter()]
        [System.String]
        \$Path = 'C:\Program Files\Microsoft SQL Server',

        [Parameter()]
        [System.String]
        \$FileName = 'Summary.txt'
    )

    \$summaryFiles = Get-ChildItem -Path \$Path -Filter \$FileName -Recurse -ErrorAction 'SilentlyContinue' |
        Where-Object { \$_.FullName -match '\\\\Setup Bootstrap\\\\Log\\\\' } |
        Sort-Object -Property 'LastWriteTime' -Descending |
        Select-Object -First 1

    if (\$summaryFiles)
    {
        \"==== SQL Server Setup Summary.txt (from \$(\$summaryFiles.FullName)) =====\"
        Get-Content -Path \$summaryFiles.FullName
        \"==== End of Summary.txt =====\"
    }
    else
    {
        'No Summary.txt file found.'
    }
}
\`\`\`

### Usage in integration tests:

\`\`\`powershell
catch
{
    Write-Verbose -Message (Get-SqlDscSetupLog) -Verbose
    throw \$_
}
\`\`\`

## Tasks

- [ ] Create the public command Get-SqlDscSetupLog with appropriate parameters
- [ ] Add unit tests for the new command
- [ ] Update integration tests to use the new command (Initialize-SqlDscRebuildDatabase and others)
- [ ] Add command documentation
- [ ] Update CHANGELOG.md

## References

- PR #2309: https://github.com/dsccommunity/SqlServerDsc/pull/2309
- Original comment: https://github.com/dsccommunity/SqlServerDsc/pull/2309#discussion_r1872000000

Requested by: @johlju" \
  --assignee johlju \
  --label enhancement

Length of output: 56


@johlju I've created issue #2311 to track this enhancement: #2311

The issue captures:

  • The need to create a new public command Get-SqlDscSetupLog that users can run interactively
  • Parameters for path and filename with default values
  • Reusability across all integration tests
  • Tasks including creating the command, unit tests, updating existing integration tests, documentation, and CHANGELOG
  • Backlinks to PR Add integration tests for Initialize-SqlDscRebuildDatabase #2309 and the original comment

The issue has been assigned to you and labeled as an enhancement.

@johlju johlju merged commit 7b219cc into dsccommunity:main Oct 19, 2025
17 of 25 checks passed
@johlju johlju deleted the fix/issue-#2242 branch October 19, 2025 11:45
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.

1 participant