Skip to content

Conversation

@johlju
Copy link
Member

@johlju johlju commented Oct 5, 2025

Pull Request (PR) description

  • Refactored integration tests to remove finally blocks from It-blocks and
    use Pester BeforeEach/AfterEach blocks instead, following DSC Community
    coding guidelines. This improves test cleanup reliability and maintainability
    across the following test files (issue #2288):
    • New-SqlDscLogin.Integration.Tests.ps1
    • New-SqlDscAudit.Integration.Tests.ps1
    • Get-SqlDscDatabasePermission.Integration.Tests.ps1
    • Get-SqlDscPreferredModule.Integration.Tests.ps1
    • New-SqlDscDatabase.Integration.Tests.ps1
  • Refactored unit tests to remove finally blocks from It-blocks and
    use Pester AfterEach blocks instead, following DSC Community coding
    guidelines. This improves test cleanup reliability and maintainability
    across the following test files (issue #2288):
    • Set-SqlDscConfigurationOption.Tests.ps1
    • Get-SqlDscConfigurationOption.Tests.ps1
    • Test-SqlDscConfigurationOption.Tests.ps1

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 5, 2025 18:50
@coderabbitai
Copy link

coderabbitai bot commented Oct 5, 2025

Walkthrough

Refactors multiple integration and unit tests to remove try/finally blocks in favor of Pester BeforeEach/AfterEach/AfterAll hooks and standardizes script-scoped variables for resource tracking. Adds a new Refresh parameter to Test-SqlDscIsDatabasePrincipal that refreshes only required SMO collections (honoring Exclude flags).

Changes

Cohort / File(s) Summary
CHANGELOG
CHANGELOG.md
Added Unreleased notes: test refactors to Pester lifecycle hooks and a Refresh parameter for Test-SqlDscIsDatabasePrincipal with targeted SMO collection refresh behavior.
Integration tests — Pester lifecycle / resource tracking
tests/Integration/Commands/Get-SqlDscDatabasePermission.Integration.Tests.ps1, tests/Integration/Commands/Get-SqlDscPreferredModule.Integration.Tests.ps1, tests/Integration/Commands/New-SqlDscAudit.Integration.Tests.ps1, tests/Integration/Commands/New-SqlDscDatabase.Integration.Tests.ps1, tests/Integration/Commands/New-SqlDscLogin.Integration.Tests.ps1
Removed try/finally cleanup inside It blocks; introduced BeforeEach/AfterEach (and contextual BeforeAll/AfterAll where appropriate); use script-scoped tracking variables; centralized teardown via AfterEach/AfterAll.
Integration tests — run-order README
tests/Integration/Commands/README.md
Updated integration test run-order dependencies to make New-SqlDscLogin a prerequisite for several permission/login-related tests and adjusted prerequisite chains accordingly.
Unit tests — tab-completion and global variable cleanup
tests/Unit/Public/Get-SqlDscConfigurationOption.Tests.ps1, tests/Unit/Public/Set-SqlDscConfigurationOption.Tests.ps1, tests/Unit/Public/Test-SqlDscConfigurationOption.Tests.ps1
Removed try/finally blocks; added AfterEach/AfterAll for global test-variable cleanup; preserved TabExpansion2 assertions and expected behavior.
Module API change
(module) Test-SqlDscIsDatabasePrincipal
Added new -Refresh parameter to control refreshing of SMO collections before evaluation; implementation refreshes only collections required for the check and respects Exclude* flags.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor Tester
  participant Cmd as Test-SqlDscIsDatabasePrincipal
  participant SMO as SMO(Server/Database)

  Tester->>Cmd: Invoke(... -Refresh? -Exclude*)
  alt Refresh specified
    Cmd->>SMO: Evaluate which collections required\n(based on Exclude flags)
    loop For each required collection
      Cmd->>SMO: Refresh(collection)
      SMO-->>Cmd: Collection refreshed
    end
  else No Refresh
    note right of Cmd #f9f0d9: Skip refresh step
  end
  Cmd->>SMO: Query principals/permissions
  SMO-->>Cmd: Principals/permissions data
  Cmd-->>Tester: Return boolean / result object
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Pre-merge checks

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Out of Scope Changes Check ⚠️ Warning The raw summary indicates an unexpected change to the public function Test-SqlDscIsDatabasePrincipal by adding a Refresh parameter and updating its signature, which is not mentioned in the PR description or linked issue objectives and therefore falls outside the stated scope of test cleanup refactoring. Remove the Test-SqlDscIsDatabasePrincipal Refresh parameter change from this pull request or split it into a separate feature PR, and ensure that this PR strictly contains only the test cleanup refactoring described in the linked issue.
✅ Passed checks (4 passed)
Check name Status Explanation
Title Check ✅ Passed The title “Improve integration and unit tests cleanup” succinctly and accurately captures the primary change of refactoring test cleanup across both integration and unit tests, reflecting the main intent without extraneous detail.
Linked Issues Check ✅ Passed The pull request addresses all coding objectives from issue #2288 by removing finally blocks from the listed test files and replacing them with appropriate Pester BeforeEach/AfterEach hooks, and it also updates integration test documentation where needed.
Description Check ✅ Passed The description clearly outlines the refactoring of integration and unit tests to remove finally blocks and replace them with Pester BeforeEach/AfterEach constructs, lists the affected files, and references the relevant issue, making it directly relevant to the changeset.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.

📜 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 c474c68 and 82e1e43.

📒 Files selected for processing (2)
  • tests/Integration/Commands/New-SqlDscLogin.Integration.Tests.ps1 (2 hunks)
  • tests/Integration/Commands/README.md (2 hunks)
🧰 Additional context used
📓 Path-based instructions (10)
**/*.[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/New-SqlDscLogin.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/New-SqlDscLogin.Integration.Tests.ps1
tests/[iI]ntegration/Commands/*.[iI]ntegration.[tT]ests.ps1

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

Place command integration tests at tests/Integration/Commands/{CommandName}.Integration.Tests.ps1

Files:

  • tests/Integration/Commands/New-SqlDscLogin.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
In CI, use Get-ComputerName for computer names
Avoid using ExpectedMessage with Should -Throw assertions
When invoking commands in integration tests, pass -Force where applicable to avoid prompts
Use -ErrorAction Stop on commands so failures surface immediately
At the top of each integration test file, include SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments') with an empty justification parameter and param ()
In BeforeDiscovery, ensure DscResource.Test is available; if not loaded or not available, run build.ps1 -Tasks 'noop' (suppressing non-error streams) and Import-Module 'DscResource.Test' -Force -ErrorAction Stop
Catch [System.IO.FileNotFoundException] during setup and throw: "DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks noop" first."
In BeforeAll, set $script:moduleName and Import-Module -Name $script:moduleName -Force -ErrorAction Stop

Files:

  • tests/Integration/Commands/New-SqlDscLogin.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/New-SqlDscLogin.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/New-SqlDscLogin.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/New-SqlDscLogin.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)

Files:

  • tests/Integration/Commands/New-SqlDscLogin.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/New-SqlDscLogin.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/New-SqlDscLogin.Integration.Tests.ps1
  • tests/Integration/Commands/README.md
{**/*.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/New-SqlDscLogin.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:

  • 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:

  • tests/Integration/Commands/README.md
🧠 Learnings (5)
📓 Common learnings
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 try/catch/finally for cleanup; use AfterAll or AfterEach
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
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
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 : Use BeforeEach and AfterEach sparingly
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 : Perform mocking in BeforeAll (use BeforeEach only when required)
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 : Define variables for -ForEach in a separate BeforeDiscovery near usage
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
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-integration-tests.instructions.md:0-0
Timestamp: 2025-09-16T16:32:58.363Z
Learning: Applies to tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1 : In BeforeDiscovery, ensure DscResource.Test is available; if not loaded or not available, run build.ps1 -Tasks 'noop' (suppressing non-error streams) and Import-Module 'DscResource.Test' -Force -ErrorAction Stop
📚 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/Integration/Commands/New-SqlDscLogin.Integration.Tests.ps1
📚 Learning: 2025-09-16T16:32:58.363Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-integration-tests.instructions.md:0-0
Timestamp: 2025-09-16T16:32:58.363Z
Learning: Applies to tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1 : When invoking commands in integration tests, pass -Force where applicable to avoid prompts

Applied to files:

  • tests/Integration/Commands/New-SqlDscLogin.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
📚 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: Integration tests must use Connect-SqlDscDatabaseEngine with correct CI credentials and call Disconnect-SqlDscDatabaseEngine after

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 (3)
tests/Integration/Commands/README.md (1)

66-91: LGTM! Dependency documentation accurately reflects test flow.

The updated dependencies correctly document that commands operating on logins (Disable/Enable-SqlDscLogin, Test-SqlDscIsLogin/Enabled, permission commands) now depend on New-SqlDscLogin creating the persistent test logins (IntegrationTestSqlLogin and SqlIntegrationTestGroup). This aligns with the refactored cleanup strategy.

tests/Integration/Commands/New-SqlDscLogin.Integration.Tests.ps1 (2)

66-98: Excellent refactoring! Previous cleanup concerns resolved.

The refactored cleanup strategy successfully addresses the previous review concern:

  1. BeforeEach/AfterEach lifecycle: Replaces try/finally blocks with Pester hooks as per PR objectives.
  2. Persistent login handling: Uses $script:isPersistentLogin = $true (line 81) to prevent AfterEach cleanup of logins needed by other integration tests.
  3. Consistent variable usage: Sets $script:testLoginName (line 80) so AfterEach can reference it.
  4. Conditional creation: Lines 84-87 prevent errors if the persistent login already exists from a previous test run.

The persistent login IntegrationTestSqlLogin will be cleaned up by the Remove-SqlDscLogin integration test at run order 8, as documented in the README.


140-193: Well-structured context-scoped cleanup.

The context-scoped BeforeEach/AfterEach blocks (lines 140-146 for Windows user, lines 176-186 for Force parameter) appropriately handle cleanup of context-specific test resources. This keeps cleanup logic close to usage and avoids unnecessary complexity in the main AfterEach block.


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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
tests/Unit/Public/Get-SqlDscConfigurationOption.Tests.ps1 (2)

410-428: Add cleanup for global test variable.

The test creates $global:BadTestServerObject (Line 417) but never cleans it up. Global variables should be removed to avoid polluting the test environment for subsequent tests.

Add cleanup in an AfterEach or AfterAll block:

+        AfterAll {
+            # Clean up global variables created in error handling tests
+            if (Get-Variable -Name 'BadTestServerObject' -Scope Global -ErrorAction SilentlyContinue) {
+                Remove-Variable -Name 'BadTestServerObject' -Scope Global -Force
+            }
+            if (Get-Variable -Name 'InvalidTestServerObject' -Scope Global -ErrorAction SilentlyContinue) {
+                Remove-Variable -Name 'InvalidTestServerObject' -Scope Global -Force
+            }
+        }
+
         It 'Should handle tab completion errors gracefully' {

Alternatively, place this AfterAll at the end of the "When testing argument completers through PowerShell tab completion system" Context block.


443-457: Add cleanup for global test variable.

The test creates $global:InvalidTestServerObject (Line 446) but never cleans it up. This global variable should be removed along with $global:BadTestServerObject as suggested in the previous comment.

🧹 Nitpick comments (1)
tests/Integration/Commands/New-SqlDscLogin.Integration.Tests.ps1 (1)

115-122: Prefer Get-SqlDscLogin for consistency.

Line 120 directly accesses $script:serverObject.Logins[$script:testLoginName] to retrieve the login. For consistency with other tests in this file (e.g., lines 101, 144) and to follow the module's public API patterns, consider using Get-SqlDscLogin instead.

-                $loginObject = $script:serverObject.Logins[$script:testLoginName]
+                $loginObject = Get-SqlDscLogin -ServerObject $script:serverObject -Name $script:testLoginName
                 $loginObject.IsDisabled | Should -BeTrue
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6e3fbfb and fd90eb3.

📒 Files selected for processing (9)
  • CHANGELOG.md (1 hunks)
  • tests/Integration/Commands/Get-SqlDscDatabasePermission.Integration.Tests.ps1 (2 hunks)
  • tests/Integration/Commands/Get-SqlDscPreferredModule.Integration.Tests.ps1 (1 hunks)
  • tests/Integration/Commands/New-SqlDscAudit.Integration.Tests.ps1 (1 hunks)
  • tests/Integration/Commands/New-SqlDscDatabase.Integration.Tests.ps1 (1 hunks)
  • tests/Integration/Commands/New-SqlDscLogin.Integration.Tests.ps1 (4 hunks)
  • tests/Unit/Public/Get-SqlDscConfigurationOption.Tests.ps1 (2 hunks)
  • tests/Unit/Public/Set-SqlDscConfigurationOption.Tests.ps1 (2 hunks)
  • tests/Unit/Public/Test-SqlDscConfigurationOption.Tests.ps1 (2 hunks)
🧰 Additional context used
📓 Path-based instructions (14)
**/*.[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/New-SqlDscDatabase.Integration.Tests.ps1
  • tests/Integration/Commands/Get-SqlDscDatabasePermission.Integration.Tests.ps1
  • tests/Unit/Public/Get-SqlDscConfigurationOption.Tests.ps1
  • tests/Integration/Commands/New-SqlDscLogin.Integration.Tests.ps1
  • tests/Integration/Commands/New-SqlDscAudit.Integration.Tests.ps1
  • tests/Unit/Public/Set-SqlDscConfigurationOption.Tests.ps1
  • tests/Integration/Commands/Get-SqlDscPreferredModule.Integration.Tests.ps1
  • tests/Unit/Public/Test-SqlDscConfigurationOption.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/New-SqlDscDatabase.Integration.Tests.ps1
  • tests/Integration/Commands/Get-SqlDscDatabasePermission.Integration.Tests.ps1
  • tests/Unit/Public/Get-SqlDscConfigurationOption.Tests.ps1
  • tests/Integration/Commands/New-SqlDscLogin.Integration.Tests.ps1
  • tests/Integration/Commands/New-SqlDscAudit.Integration.Tests.ps1
  • tests/Unit/Public/Set-SqlDscConfigurationOption.Tests.ps1
  • tests/Integration/Commands/Get-SqlDscPreferredModule.Integration.Tests.ps1
  • tests/Unit/Public/Test-SqlDscConfigurationOption.Tests.ps1
tests/[iI]ntegration/Commands/*.[iI]ntegration.[tT]ests.ps1

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

Place command integration tests at tests/Integration/Commands/{CommandName}.Integration.Tests.ps1

Files:

  • tests/Integration/Commands/New-SqlDscDatabase.Integration.Tests.ps1
  • tests/Integration/Commands/Get-SqlDscDatabasePermission.Integration.Tests.ps1
  • tests/Integration/Commands/New-SqlDscLogin.Integration.Tests.ps1
  • tests/Integration/Commands/New-SqlDscAudit.Integration.Tests.ps1
  • tests/Integration/Commands/Get-SqlDscPreferredModule.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
In CI, use Get-ComputerName for computer names
Avoid using ExpectedMessage with Should -Throw assertions
When invoking commands in integration tests, pass -Force where applicable to avoid prompts
Use -ErrorAction Stop on commands so failures surface immediately
At the top of each integration test file, include SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments') with an empty justification parameter and param ()
In BeforeDiscovery, ensure DscResource.Test is available; if not loaded or not available, run build.ps1 -Tasks 'noop' (suppressing non-error streams) and Import-Module 'DscResource.Test' -Force -ErrorAction Stop
Catch [System.IO.FileNotFoundException] during setup and throw: "DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks noop" first."
In BeforeAll, set $script:moduleName and Import-Module -Name $script:moduleName -Force -ErrorAction Stop

Files:

  • tests/Integration/Commands/New-SqlDscDatabase.Integration.Tests.ps1
  • tests/Integration/Commands/Get-SqlDscDatabasePermission.Integration.Tests.ps1
  • tests/Integration/Commands/New-SqlDscLogin.Integration.Tests.ps1
  • tests/Integration/Commands/New-SqlDscAudit.Integration.Tests.ps1
  • tests/Integration/Commands/Get-SqlDscPreferredModule.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/New-SqlDscDatabase.Integration.Tests.ps1
  • tests/Integration/Commands/Get-SqlDscDatabasePermission.Integration.Tests.ps1
  • tests/Integration/Commands/New-SqlDscLogin.Integration.Tests.ps1
  • tests/Integration/Commands/New-SqlDscAudit.Integration.Tests.ps1
  • tests/Integration/Commands/Get-SqlDscPreferredModule.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/New-SqlDscDatabase.Integration.Tests.ps1
  • tests/Integration/Commands/Get-SqlDscDatabasePermission.Integration.Tests.ps1
  • tests/Unit/Public/Get-SqlDscConfigurationOption.Tests.ps1
  • tests/Integration/Commands/New-SqlDscLogin.Integration.Tests.ps1
  • tests/Integration/Commands/New-SqlDscAudit.Integration.Tests.ps1
  • tests/Unit/Public/Set-SqlDscConfigurationOption.Tests.ps1
  • tests/Integration/Commands/Get-SqlDscPreferredModule.Integration.Tests.ps1
  • tests/Unit/Public/Test-SqlDscConfigurationOption.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/New-SqlDscDatabase.Integration.Tests.ps1
  • tests/Integration/Commands/Get-SqlDscDatabasePermission.Integration.Tests.ps1
  • tests/Unit/Public/Get-SqlDscConfigurationOption.Tests.ps1
  • tests/Integration/Commands/New-SqlDscLogin.Integration.Tests.ps1
  • tests/Integration/Commands/New-SqlDscAudit.Integration.Tests.ps1
  • tests/Unit/Public/Set-SqlDscConfigurationOption.Tests.ps1
  • tests/Integration/Commands/Get-SqlDscPreferredModule.Integration.Tests.ps1
  • tests/Unit/Public/Test-SqlDscConfigurationOption.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)

Files:

  • tests/Integration/Commands/New-SqlDscDatabase.Integration.Tests.ps1
  • tests/Integration/Commands/Get-SqlDscDatabasePermission.Integration.Tests.ps1
  • tests/Integration/Commands/New-SqlDscLogin.Integration.Tests.ps1
  • tests/Integration/Commands/New-SqlDscAudit.Integration.Tests.ps1
  • tests/Integration/Commands/Get-SqlDscPreferredModule.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/New-SqlDscDatabase.Integration.Tests.ps1
  • tests/Integration/Commands/Get-SqlDscDatabasePermission.Integration.Tests.ps1
  • tests/Unit/Public/Get-SqlDscConfigurationOption.Tests.ps1
  • tests/Integration/Commands/New-SqlDscLogin.Integration.Tests.ps1
  • tests/Integration/Commands/New-SqlDscAudit.Integration.Tests.ps1
  • tests/Unit/Public/Set-SqlDscConfigurationOption.Tests.ps1
  • tests/Integration/Commands/Get-SqlDscPreferredModule.Integration.Tests.ps1
  • tests/Unit/Public/Test-SqlDscConfigurationOption.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/New-SqlDscDatabase.Integration.Tests.ps1
  • tests/Integration/Commands/Get-SqlDscDatabasePermission.Integration.Tests.ps1
  • tests/Unit/Public/Get-SqlDscConfigurationOption.Tests.ps1
  • CHANGELOG.md
  • tests/Integration/Commands/New-SqlDscLogin.Integration.Tests.ps1
  • tests/Integration/Commands/New-SqlDscAudit.Integration.Tests.ps1
  • tests/Unit/Public/Set-SqlDscConfigurationOption.Tests.ps1
  • tests/Integration/Commands/Get-SqlDscPreferredModule.Integration.Tests.ps1
  • tests/Unit/Public/Test-SqlDscConfigurationOption.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/New-SqlDscDatabase.Integration.Tests.ps1
  • tests/Integration/Commands/Get-SqlDscDatabasePermission.Integration.Tests.ps1
  • tests/Unit/Public/Get-SqlDscConfigurationOption.Tests.ps1
  • tests/Integration/Commands/New-SqlDscLogin.Integration.Tests.ps1
  • tests/Integration/Commands/New-SqlDscAudit.Integration.Tests.ps1
  • tests/Unit/Public/Set-SqlDscConfigurationOption.Tests.ps1
  • tests/Integration/Commands/Get-SqlDscPreferredModule.Integration.Tests.ps1
  • tests/Unit/Public/Test-SqlDscConfigurationOption.Tests.ps1
tests/Unit/Public/*.Tests.ps1

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

Public command unit tests must reside in tests/Unit/Public/{Name}.Tests.ps1

Place unit tests for public commands in tests/Unit/Public/{Name}.Tests.ps1

Files:

  • tests/Unit/Public/Get-SqlDscConfigurationOption.Tests.ps1
  • tests/Unit/Public/Set-SqlDscConfigurationOption.Tests.ps1
  • tests/Unit/Public/Test-SqlDscConfigurationOption.Tests.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/Get-SqlDscConfigurationOption.Tests.ps1
  • tests/Unit/Public/Set-SqlDscConfigurationOption.Tests.ps1
  • tests/Unit/Public/Test-SqlDscConfigurationOption.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/Get-SqlDscConfigurationOption.Tests.ps1
  • tests/Unit/Public/Set-SqlDscConfigurationOption.Tests.ps1
  • tests/Unit/Public/Test-SqlDscConfigurationOption.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/Get-SqlDscConfigurationOption.Tests.ps1
  • tests/Unit/Public/Set-SqlDscConfigurationOption.Tests.ps1
  • tests/Unit/Public/Test-SqlDscConfigurationOption.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

⚙️ 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
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 (8)
📓 Common learnings
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 try/catch/finally for cleanup; use AfterAll or AfterEach
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
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
📚 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/New-SqlDscLogin.Integration.Tests.ps1
  • tests/Unit/Public/Test-SqlDscConfigurationOption.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/Integration/Commands/New-SqlDscLogin.Integration.Tests.ps1
  • tests/Integration/Commands/New-SqlDscAudit.Integration.Tests.ps1
📚 Learning: 2025-09-16T16:32:58.363Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-integration-tests.instructions.md:0-0
Timestamp: 2025-09-16T16:32:58.363Z
Learning: Applies to tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1 : When invoking commands in integration tests, pass -Force where applicable to avoid prompts

Applied to files:

  • tests/Integration/Commands/New-SqlDscLogin.Integration.Tests.ps1
📚 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 try/catch/finally for cleanup; use AfterAll or AfterEach

Applied to files:

  • tests/Unit/Public/Set-SqlDscConfigurationOption.Tests.ps1
  • tests/Unit/Public/Test-SqlDscConfigurationOption.Tests.ps1
📚 Learning: 2025-08-17T10:15:48.194Z
Learnt from: johlju
PR: dsccommunity/SqlServerDsc#2136
File: tests/Unit/Public/Remove-SqlDscLogin.Tests.ps1:36-39
Timestamp: 2025-08-17T10:15:48.194Z
Learning: Public command unit tests guideline: Never use InModuleScope unless accessing localized strings from $script:localizedData. PSDefaultParameterValues for InModuleScope should be kept in public command tests to support localized string retrieval when necessary.

Applied to files:

  • tests/Integration/Commands/Get-SqlDscPreferredModule.Integration.Tests.ps1
📚 Learning: 2025-09-16T16:32:58.363Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-integration-tests.instructions.md:0-0
Timestamp: 2025-09-16T16:32:58.363Z
Learning: Applies to tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1 : In BeforeAll, set $script:moduleName and Import-Module -Name $script:moduleName -Force -ErrorAction Stop

Applied to files:

  • tests/Integration/Commands/Get-SqlDscPreferredModule.Integration.Tests.ps1
📚 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 : Use BeforeEach and AfterEach sparingly

Applied to files:

  • tests/Unit/Public/Test-SqlDscConfigurationOption.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 (6)
tests/Integration/Commands/New-SqlDscDatabase.Integration.Tests.ps1 (1)

99-122: LGTM! Proper lifecycle hook implementation.

The refactor correctly replaces try/finally with BeforeEach/AfterEach:

  • Script-scoped variable ($script:refreshTestDbName) enables cleanup tracking across lifecycle blocks
  • AfterEach conditionally cleans up only if the test created a database
  • Test assigns a unique name before resource creation, ensuring proper cleanup

Based on learnings

tests/Integration/Commands/New-SqlDscAudit.Integration.Tests.ps1 (1)

108-120: LGTM! Cleanup handled by existing AfterEach.

The test reuses the script-scoped $script:testAuditName variable by reassigning it within the It block (Line 108). While slightly unconventional, this approach works correctly because:

  • The Context's AfterEach (lines 83-89) conditionally cleans up any audit matching the script-scoped name
  • The cleanup uses -ErrorAction 'SilentlyContinue' to handle cases where the audit may not exist
tests/Integration/Commands/Get-SqlDscDatabasePermission.Integration.Tests.ps1 (1)

166-207: LGTM! Lifecycle hooks properly isolate test state.

The refactor correctly implements BeforeEach/AfterEach:

  • BeforeEach initializes the script-scoped variable to null
  • Test creates custom role using the script-scoped name
  • AfterEach conditionally cleans up if a role was created
  • All SQL statements and assertions consistently reference $script:customRoleName

Based on learnings

tests/Integration/Commands/New-SqlDscLogin.Integration.Tests.ps1 (3)

66-76: LGTM! Proper lifecycle hook implementation.

The BeforeEach/AfterEach pattern correctly:

  • Initializes the script-scoped variable to null before each test
  • Conditionally cleans up using Test-SqlDscIsLogin to verify existence
  • Directly drops the login via SMO when cleanup is needed

Based on learnings


130-146: LGTM! Windows user login test properly refactored.

The test correctly:

  • Adds AfterEach for cleanup using the script-scoped $script:testWindowsUserName
  • Uses Get-SqlDscLogin for verification (consistent with other tests)
  • Conditionally drops the login only if it exists

161-177: LGTM! Force parameter test properly isolated.

The BeforeEach/AfterEach pattern correctly:

  • Initializes $script:forceLoginName before each test in this Context
  • Conditionally cleans up using Test-SqlDscIsLogin to verify existence
  • Uses the script-scoped variable consistently throughout

@codecov
Copy link

codecov bot commented Oct 5, 2025

Codecov Report

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

Additional details and impacted files

Impacted file tree graph

@@         Coverage Diff          @@
##           main   #2293   +/-   ##
====================================
  Coverage    94%     94%           
====================================
  Files       149     149           
  Lines      9180    9180           
====================================
  Hits       8700    8700           
  Misses      480     480           
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

@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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
tests/Integration/Commands/New-SqlDscLogin.Integration.Tests.ps1 (1)

149-158: Missing cleanup for Windows group login.

The Windows group login created in this context is never cleaned up, causing test pollution. Add an AfterEach block to ensure proper cleanup.

Apply this diff:

         Context 'When creating a Windows group login' {
+            AfterEach {
+                # Clean up Windows group login
+                if (Test-SqlDscIsLogin -ServerObject $script:serverObject -Name $script:testWindowsGroupName)
+                {
+                    $script:serverObject.Logins[$script:testWindowsGroupName].Drop()
+                }
+            }
+
             It 'Should create a Windows group login without error' {
                 $null = New-SqlDscLogin -ServerObject $script:serverObject -Name $script:testWindowsGroupName -WindowsGroup -Force
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between fd90eb3 and 9ba44b9.

📒 Files selected for processing (3)
  • tests/Integration/Commands/Get-SqlDscPreferredModule.Integration.Tests.ps1 (1 hunks)
  • tests/Integration/Commands/New-SqlDscLogin.Integration.Tests.ps1 (4 hunks)
  • tests/Unit/Public/Get-SqlDscConfigurationOption.Tests.ps1 (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • tests/Integration/Commands/Get-SqlDscPreferredModule.Integration.Tests.ps1
  • tests/Unit/Public/Get-SqlDscConfigurationOption.Tests.ps1
🧰 Additional context used
📓 Path-based instructions (9)
**/*.[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/New-SqlDscLogin.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/New-SqlDscLogin.Integration.Tests.ps1
tests/[iI]ntegration/Commands/*.[iI]ntegration.[tT]ests.ps1

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

Place command integration tests at tests/Integration/Commands/{CommandName}.Integration.Tests.ps1

Files:

  • tests/Integration/Commands/New-SqlDscLogin.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
In CI, use Get-ComputerName for computer names
Avoid using ExpectedMessage with Should -Throw assertions
When invoking commands in integration tests, pass -Force where applicable to avoid prompts
Use -ErrorAction Stop on commands so failures surface immediately
At the top of each integration test file, include SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments') with an empty justification parameter and param ()
In BeforeDiscovery, ensure DscResource.Test is available; if not loaded or not available, run build.ps1 -Tasks 'noop' (suppressing non-error streams) and Import-Module 'DscResource.Test' -Force -ErrorAction Stop
Catch [System.IO.FileNotFoundException] during setup and throw: "DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks noop" first."
In BeforeAll, set $script:moduleName and Import-Module -Name $script:moduleName -Force -ErrorAction Stop

Files:

  • tests/Integration/Commands/New-SqlDscLogin.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/New-SqlDscLogin.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/New-SqlDscLogin.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/New-SqlDscLogin.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)

Files:

  • tests/Integration/Commands/New-SqlDscLogin.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/New-SqlDscLogin.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/New-SqlDscLogin.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/New-SqlDscLogin.Integration.Tests.ps1
🧠 Learnings (3)
📓 Common learnings
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 try/catch/finally for cleanup; use AfterAll or AfterEach
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
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 : Use BeforeEach and AfterEach sparingly
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
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 : Perform mocking in BeforeAll (use BeforeEach only when required)
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 : Use PascalCase for Pester keywords: Describe, Context, It, Should, BeforeAll, BeforeEach, AfterAll, AfterEach
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 : Place setup/teardown (BeforeAll/BeforeEach/AfterAll/AfterEach) close to usage
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 : Define variables for -ForEach in a separate BeforeDiscovery near usage
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
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-integration-tests.instructions.md:0-0
Timestamp: 2025-09-16T16:32:58.363Z
Learning: Applies to tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1 : In BeforeDiscovery, ensure DscResource.Test is available; if not loaded or not available, run build.ps1 -Tasks 'noop' (suppressing non-error streams) and Import-Module 'DscResource.Test' -Force -ErrorAction Stop
📚 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/Integration/Commands/New-SqlDscLogin.Integration.Tests.ps1
📚 Learning: 2025-09-16T16:32:58.363Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-integration-tests.instructions.md:0-0
Timestamp: 2025-09-16T16:32:58.363Z
Learning: Applies to tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1 : When invoking commands in integration tests, pass -Force where applicable to avoid prompts

Applied to files:

  • tests/Integration/Commands/New-SqlDscLogin.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

@johlju johlju merged commit 70f4f9f into dsccommunity:main Oct 7, 2025
25 of 26 checks passed
@johlju johlju deleted the fix/issue#2288 branch October 7, 2025 15:54
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.

Refactor tests to remove finally blocks in favor of Pester Before*/After*-blocks

1 participant