Skip to content

Conversation

@johlju
Copy link
Member

@johlju johlju commented Aug 29, 2025

Pull Request (PR) description

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 August 29, 2025 19:27
@coderabbitai
Copy link

coderabbitai bot commented Aug 29, 2025

Walkthrough

Adds a trailing comma in SqlAgentAlert’s ExcludeDscProperties to correctly separate "Credential" and "Name". Expands unit tests to cover MessageId-based behavior across Get/Set/Modify and validation paths. Updates changelog to note the ExcludeDscProperties fix and new tests. No public API changes.

Changes

Cohort / File(s) Summary of Changes
Documentation (Changelog)
CHANGELOG.md
Added Unreleased entries: fixed ExcludeDscProperties delimiter in source/Classes/020.SqlAgentAlert.ps1; noted added unit tests for MessageId alerts, Modify() behavior, and AssertProperties() validation.
SqlAgentAlert class source
source/Classes/020.SqlAgentAlert.ps1
Fixed ExcludeDscProperties array by adding a trailing comma after 'Credential', ensuring 'Name' is a separate excluded property. No other logic changes.
Unit tests
tests/Unit/Classes/SqlAgentAlert.Tests.ps1
Added tests covering MessageId flows across Get/Set/Modify, creation/update scenarios for Severity vs MessageId, and validations for mutual exclusivity and Ensure Present/Absent rules.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs


📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • Jira integration is disabled
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 5a1db32 and c3ff4f0.

📒 Files selected for processing (2)
  • CHANGELOG.md (2 hunks)
  • tests/Unit/Classes/SqlAgentAlert.Tests.ps1 (12 hunks)
✅ Files skipped from review due to trivial changes (1)
  • CHANGELOG.md
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/Unit/Classes/SqlAgentAlert.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). (2)
  • GitHub Check: dsccommunity.SqlServerDsc (Build Package Module)
  • GitHub Check: PSScriptAnalyzer
✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

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

🧹 Nitpick comments (4)
CHANGELOG.md (1)

63-67: Remove duplicate entry for the same change

The ExcludeDscProperties formatting fix is listed under both “Fixed” and “Changed”. Keep it only under “Fixed” per project guidelines.

Apply this diff under the “Changed → SqlAgentAlert” subsection:

-  - Minor fix in `source/Classes/020.SqlAgentAlert.ps1` to correct `ExcludeDscProperties`
-    formatting (added missing delimiter).
tests/Unit/Classes/SqlAgentAlert.Tests.ps1 (3)

191-193: Do not place Mock inside InModuleScope

Move this Mock call outside the InModuleScope block to follow the Pester guideline.

Apply this diff to the InModuleScope block:

-                Mock -CommandName 'Get-SqlDscAgentAlert' -MockWith {
-                    return $script:mockAlertObjectWithMessageId
-                }

Then add the Mock just before the InModuleScope in the same It-block:

# outside InModuleScope
Mock -CommandName 'Get-SqlDscAgentAlert' -MockWith { $script:mockAlertObjectWithMessageId }

378-381: Avoid Mock inside InModuleScope (alert absent case)

Define Mock outside InModuleScope; returning $null needs no -MockWith.

Apply this diff to remove the inner Mock:

-                    Mock -CommandName 'Get-SqlDscAgentAlert'

And add before the InModuleScope in this It-block:

# outside InModuleScope
Mock -CommandName 'Get-SqlDscAgentAlert'

407-407: Avoid Mock inside InModuleScope (MessageId create case)

Same styling: move Mock outside the InModuleScope block.

Apply this diff to remove the inner Mock:

-                    Mock -CommandName 'Get-SqlDscAgentAlert'

And add before the InModuleScope in this It-block:

# outside InModuleScope
Mock -CommandName 'Get-SqlDscAgentAlert'
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • Jira integration is disabled
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 53a4a65 and 5a1db32.

📒 Files selected for processing (3)
  • CHANGELOG.md (2 hunks)
  • source/Classes/020.SqlAgentAlert.ps1 (1 hunks)
  • tests/Unit/Classes/SqlAgentAlert.Tests.ps1 (3 hunks)
🧰 Additional context used
📓 Path-based instructions (18)
**/*.{ps1,psm1,psd1}

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

Follow PowerShell code style guidelines in all PowerShell scripts, modules, and manifests

**/*.{ps1,psm1,psd1}: Use 4 spaces for indentation (no tabs)
No spaces on empty lines
Limit lines to 120 characters where practical
Empty hashtable: @{}
Hashtable: each property on its own line with proper indentation
Hashtable properties use PascalCase
End files with only one blank line
Use CR+LF line endings
Allow a maximum of two consecutive newlines
Use UTF-8 encoding without BOM for all files

Files:

  • source/Classes/020.SqlAgentAlert.ps1
  • tests/Unit/Classes/SqlAgentAlert.Tests.ps1
**/*.{ps1,psm1}

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

**/*.{ps1,psm1}: Public PowerShell commands must use the naming format Verb-SqlDsc{Noun}
Private PowerShell functions must use the naming format Verb-Noun (no SqlDsc infix)
Always prefer SMO over T-SQL for SQL Server interaction

**/*.{ps1,psm1}: Use descriptive names (3+ characters, no abbreviations)
Functions must use PascalCase with Verb-Noun format using approved verbs
Parameters use PascalCase
Variables use camelCase
Keywords are lower-case
Classes use PascalCase
Include scope for script/global/environment variables: use $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 opening brace on a new line (except variable assignments)
Add one newline after an opening brace
Add two newlines after a closing brace (one if followed by another brace or continuation)
Use single quotes unless variable expansion is needed
Arrays single-line form: @('one','two','three')
Arrays multi-line: one element per line with proper indentation
Do not use unary comma operator in return statements to force an array
Single-line comments use '# Comment' (capitalized, on its own line)
Multi-line comments use <# #> with opening/closing on their own lines; indent text
No commented-out code
Always add comment-based help to all functions and scripts
Comment-based help must include SYNOPSIS, DESCRIPTION (40+ chars), PARAMETER, EXAMPLE sections before function/class
Comment-based help indentation: keywords indented 4 spaces, text 8 spaces
Include examples for all parameter sets and combinations in comment-based help
INPUTS: list each pipeline-accepted type (one per line) with a 1-line description
OUTPUTS: list each return type (one per line) with a 1-line description; must match [OutputType()] and actual returns
.NOTES: include only critical info (constraints, side effects, security, version compatibility, breaking behavior) up to 2 ...

Files:

  • source/Classes/020.SqlAgentAlert.ps1
  • tests/Unit/Classes/SqlAgentAlert.Tests.ps1
source/[cC]lasses/020.*.ps1

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

Place each DSC class-based resource in file: source/Classes/020.{ResourceName}.ps1

Files:

  • source/Classes/020.SqlAgentAlert.ps1
source/[cC]lasses/**/*.ps1

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

source/[cC]lasses/**/*.ps1: Decorate DSC resource classes with [DscResource(RunAsCredential = 'Optional')] (or 'Mandatory' if required)
DSC resource classes must inherit ResourceBase (from DscResource.Base)
Use $this.localizedData provided by ResourceBase for localization strings
For value-type properties, use [Nullable[FullTypeName]] (e.g., [Nullable[System.Int32]])
Include a constructor that chains to base: MyResourceName () : base ($PSScriptRoot) and initializes $this.ExcludeDscProperties = @()
Implement Get() that calls ([ResourceBase] $this).Get() and returns the current state
Implement Test() that calls ([ResourceBase] $this).Test() and returns a boolean in-desired-state
Implement Set() that calls ([ResourceBase] $this).Set() and performs any additional changes as needed
Provide hidden GetCurrentState([Hashtable] $properties) returning a Hashtable of current state
Provide hidden Modify([Hashtable] $properties) that applies desired state changes
Optional: hidden AssertProperties([Hashtable] $properties) to validate user-provided properties
Optional: hidden NormalizeProperties([Hashtable] $properties) to normalize user-provided properties
Comment-based help: In .DESCRIPTION include '## Requirements' and '## Known issues' with link pattern to all open issues for {ResourceName}
Use try/catch for error handling in resource methods
Do not use throw for terminating errors; use New-*Exception helpers (New-InvalidDataException, New-ArgumentException, New-InvalidOperationException, New-ObjectNotFoundException, New-InvalidResultException, New-NotImplementedException)
These guidelines apply only to classes decorated with [DscResource(...)]

Files:

  • source/Classes/020.SqlAgentAlert.ps1

⚙️ CodeRabbit configuration file

source/[cC]lasses/**/*.ps1: # DSC Class-Based Resource Guidelines

Applies to: Classes with [DscResource(...)] decoration only.

Requirements

  • File: source/Classes/020.{ResourceName}.ps1
  • Decoration: [DscResource(RunAsCredential = 'Optional')] (replace with 'Mandatory' if required)
  • Inheritance: Must inherit ResourceBase (part of module DscResource.Base)
  • $this.localizedData hashtable auto-populated by ResourceBase from localization file
  • value-type properties: Use [Nullable[{FullTypeName}]] (e.g., [Nullable[System.Int32]])

Required constructor

MyResourceName () : base ($PSScriptRoot)
{
    # Property names where state cannot be enforced, e.g. IsSingleInstance, Force
    $this.ExcludeDscProperties = @()
}

Required Method Pattern

[MyResourceName] Get()
{
    # Call base implementation to get current state
    $currentState = ([ResourceBase] $this).Get()

    # If needed, post-processing on current state that can not be handled by GetCurrentState()

    return $currentState
}

[System.Boolean] Test()
{
    # Call base implementation to test current state
    $inDesiredState = ([ResourceBase] $this).Test()

    # If needed, post-processing on test result that can not be handled by base Test()

    return $inDesiredState
}

[void] Set()
{
    # Call base implementation to set desired state
    ([ResourceBase] $this).Set()

    # If needed, additional state changes that can not be handled by Modify()
}

hidden [System.Collections.Hashtable] GetCurrentState([System.Collections.Hashtable] $properties)
{
    # Always return current state as hashtable, $properties contains key properties
}

hidden [void] Modify([System.Collections.Hashtable] $properties)
{
    # Always set desired state, $properties contain those that must change state
}

Optional Method Pattern

hidden [void] AssertProperties([System.Collections.Hashtable] $properties)
{
    # Validate user-provided properties, $p...

Files:

  • source/Classes/020.SqlAgentAlert.ps1
source/**/*.ps1

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

source/**/*.ps1: Localize all Write-Debug, Write-Verbose, Write-Error, Write-Warning, and $PSCmdlet.ThrowTerminatingError() messages
Use localized string keys instead of hardcoded strings in script output/messages
Assume and use $script:localizedData for accessing localized strings
When emitting messages, reference $script:localizedData.KeyName and format with the -f operator (e.g., Write-Verbose -Message ($script:localizedData.KeyName -f $value1))

Files:

  • source/Classes/020.SqlAgentAlert.ps1

⚙️ CodeRabbit configuration file

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

Requirements

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

String Files

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

Key Naming Patterns

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

String Format

ConvertFrom-StringData @'
    KeyName = Message with {0} placeholder. (PREFIX0001)
'@

String IDs

  • Format: (PREFIX####)
  • PREFIX: First letter of each word in class or function name (SqlSetup → SS, Get-SqlDscDatabase → GSDD)
  • Number: Sequential from 0001

Usage

Write-Verbose -Message ($script:localizedData.KeyName -f $value1)

Files:

  • source/Classes/020.SqlAgentAlert.ps1
**/[0-9][0-9][0-9].[A-Z][A-Za-z0-9]*.ps1

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

Class files must follow naming format ###.ClassName.ps1 (e.g., 001.SqlReason.ps1)

Files:

  • source/Classes/020.SqlAgentAlert.ps1
**/*.{ps1,psd1}

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

Localize all strings using string keys and remove any orphaned string keys

Files:

  • source/Classes/020.SqlAgentAlert.ps1
  • tests/Unit/Classes/SqlAgentAlert.Tests.ps1
**

⚙️ CodeRabbit configuration file

**: # DSC Community Guidelines

Terminology

  • Command: Public command
  • Function: Private function
  • Resource: DSC class-based resource

Build & Test Workflow

  • Run in PowerShell, from repository root
  • Build before running tests: .\build.ps1 -Tasks build
  • Always run tests in new PowerShell 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 guidelines over existing code patterns
  • 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
  • Add unit tests for all commands/functions/resources
  • Add integration tests for all public commands and resources

Files:

  • source/Classes/020.SqlAgentAlert.ps1
  • CHANGELOG.md
  • tests/Unit/Classes/SqlAgentAlert.Tests.ps1
**/*.ps?(m|d)1

⚙️ CodeRabbit configuration file

**/*.ps?(m|d)1: # 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.
  • OUTPUTS: Lis...

Files:

  • source/Classes/020.SqlAgentAlert.ps1
  • tests/Unit/Classes/SqlAgentAlert.Tests.ps1
**/*.md

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

Follow Markdown formatting requirements for documentation

**/*.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/copilot-instructions.md)

Always update CHANGELOG.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
Do not add an item if there is already an existing item for the same change

Always update the CHANGELOG.md Unreleased section

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
  • Do not add item if there are already an existing item for the same change

Files:

  • CHANGELOG.md
**/*.Tests.ps1

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

Follow test patterns strictly for maintainability in Pester tests

Files:

  • tests/Unit/Classes/SqlAgentAlert.Tests.ps1
tests/Unit/**/*.ps1

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

tests/Unit/**/*.ps1: In unit tests, use SMO stub types from SMO.cs and never mock real SMO types
Unit tests must set $env:SqlServerDscCI = $true in BeforeAll and remove it in AfterAll
Load SMO stub types in unit tests, e.g., Add-Type -Path "$PSScriptRoot/../Stubs/SMO.cs"

Files:

  • tests/Unit/Classes/SqlAgentAlert.Tests.ps1
**/*.[Tt]ests.ps1

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

**/*.[Tt]ests.ps1: All public commands, private functions and classes must have unit tests
Use Pester v5 syntax only
Place test code only inside Describe blocks
Use assertions only inside It blocks
Never test verbose messages, debug messages, or parameter binding behavior
Pass all mandatory parameters in tests to avoid prompts
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'
Prefix mock variables with 'mock'
Use a separate Context block for each class method
Use a separate Context block for each scenario
Use nested Context blocks for complex scenarios
Define mocks in BeforeAll; use BeforeEach only when required
Place setup/teardown in BeforeAll/BeforeEach and AfterAll/AfterEach close to their usage
Use PascalCase for Pester keywords: Describe, Context, It, Should, BeforeAll, BeforeEach, AfterAll, AfterEach
Prefer -BeTrue/-BeFalse over -Be $true/-Be $false
Do not 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 block, close to their usage
Use -ForEach only on Context and It blocks
Keep variable scope close to the usage context
Inside It blocks, assign unused return objects to $null unless part of a pipeline
Call the tested entity from within It blocks
Keep results and assertions in the same It block
Cover all scenarios and code paths
Use BeforeEach and AfterEach sparingly
Avoid try/catch/finally for cleanup; use AfterAll or AfterEach
Avoid unnecessary remove/recreate cycles in tests

Files:

  • tests/Unit/Classes/SqlAgentAlert.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

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
  • Prefer -BeTrue/-BeFalse over -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 InModuleScope-block

File Organization

  • Class resources: tests/Unit/Classes/{Name}.Tests.ps1
  • Public commands: tests/Unit/Public/{Name}.Tests.ps1
  • Private functions: tests/Unit/Private/{Name}.Tests.ps1

Data-Driven Tests

  • Define variables in separate BeforeDiscovery for -ForEach (close to usage)
  • -ForEach al...

Files:

  • tests/Unit/Classes/SqlAgentAlert.Tests.ps1
tests/Unit/{Private,Classes}/*.Tests.ps1

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

For private functions and class resources, always use InModuleScope

Files:

  • tests/Unit/Classes/SqlAgentAlert.Tests.ps1
tests/Unit/Classes/*.Tests.ps1

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

Place class resource unit tests under tests/Unit/Classes/{Name}.Tests.ps1

Files:

  • tests/Unit/Classes/SqlAgentAlert.Tests.ps1
tests/Unit/@(Classes|Public|Private)/*.Tests.ps1

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

Place unit tests in tests/Unit/{Classes|Public|Private}/{Name}.Tests.ps1

Files:

  • tests/Unit/Classes/SqlAgentAlert.Tests.ps1
tests/Unit/**/*.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/Classes/SqlAgentAlert.Tests.ps1
🧠 Learnings (9)
📚 Learning: 2025-08-29T17:20:42.238Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-08-29T17:20:42.238Z
Learning: In Database Engine resources, add InstanceName, ServerName, and Credential to $this.ExcludeDscProperties

Applied to files:

  • source/Classes/020.SqlAgentAlert.ps1
📚 Learning: 2025-08-29T17:21:35.556Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-class-resource.instructions.md:0-0
Timestamp: 2025-08-29T17:21:35.556Z
Learning: Applies to source/[cC]lasses/**/*.ps1 : Include a constructor that chains to base: MyResourceName () : base ($PSScriptRoot) and initializes $this.ExcludeDscProperties = @()

Applied to files:

  • source/Classes/020.SqlAgentAlert.ps1
📚 Learning: 2025-08-29T17:20:51.216Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-changelog.instructions.md:0-0
Timestamp: 2025-08-29T17:20:51.216Z
Learning: Applies to CHANGELOG.md : Describe notable changes briefly, with no more than 2 items per change type

Applied to files:

  • CHANGELOG.md
📚 Learning: 2025-08-29T17:20:42.238Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-08-29T17:20:42.238Z
Learning: Applies to tests/Integration/**/*.ps1 : Use DSCSQLTEST (Database Engine), SSRS (Reporting Services), and PBIRS (Power BI Report Server) instance names in CI integration tests

Applied to files:

  • CHANGELOG.md
📚 Learning: 2025-08-29T17:19:40.921Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-29T17:19:40.921Z
Learning: Follow SqlServerDsc project-specific guidelines

Applied to files:

  • CHANGELOG.md
📚 Learning: 2025-08-18T13:50:53.789Z
Learnt from: johlju
PR: dsccommunity/SqlServerDsc#2132
File: tests/Unit/Public/New-SqlDscLogin.Tests.ps1:0-0
Timestamp: 2025-08-18T13:50:53.789Z
Learning: In SqlServerDsc unit tests, SMO stub objects can be used to verify method calls like Create() on Login objects by adding mock verifications with Should -Invoke, providing more robust testing than just checking for no exceptions.

Applied to files:

  • tests/Unit/Classes/SqlAgentAlert.Tests.ps1
📚 Learning: 2025-08-29T17:23:02.551Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-08-29T17:23:02.551Z
Learning: Applies to **/*.[Tt]ests.ps1 : Omit -MockWith when returning $null

Applied to files:

  • tests/Unit/Classes/SqlAgentAlert.Tests.ps1
📚 Learning: 2025-08-29T17:22:07.581Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-integration-tests.instructions.md:0-0
Timestamp: 2025-08-29T17:22:07.581Z
Learning: Applies to tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1 : Avoid using ExpectedMessage with Should -Throw assertions in Pester

Applied to files:

  • tests/Unit/Classes/SqlAgentAlert.Tests.ps1
📚 Learning: 2025-08-29T17:23:02.551Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-08-29T17:23:02.551Z
Learning: Applies to **/*.[Tt]ests.ps1 : Do not use Assert-MockCalled; use Should -Invoke instead

Applied to files:

  • tests/Unit/Classes/SqlAgentAlert.Tests.ps1
🧬 Code graph analysis (3)
source/Classes/020.SqlAgentAlert.ps1 (1)
tests/Unit/Stubs/SMO.cs (2)
  • Alert (1608-1650)
  • Microsoft (1499-1653)
CHANGELOG.md (1)
tests/Unit/Stubs/SMO.cs (3)
  • Alert (1608-1650)
  • Microsoft (1499-1653)
  • AlertCollection (1565-1599)
tests/Unit/Classes/SqlAgentAlert.Tests.ps1 (1)
tests/Unit/Stubs/SMO.cs (3)
  • Alert (1608-1650)
  • Microsoft (1499-1653)
  • AlertCollection (1565-1599)
⏰ 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)
source/Classes/020.SqlAgentAlert.ps1 (1)

147-149: ExcludeDscProperties delimiter fix — LGTM

The added comma correctly separates 'Credential' and 'Name' and aligns with the guidance to exclude InstanceName, ServerName, and Credential (and Name as key).

CHANGELOG.md (1)

15-17: Changelog “Fixed” entry — LGTM

Accurately describes the ExcludeDscProperties formatting fix.

tests/Unit/Classes/SqlAgentAlert.Tests.ps1 (4)

206-211: MessageId Get() branch assertions — LGTM

Solid coverage ensuring MessageId precedence and Severity null/empty behavior.


303-322: Creation with MessageId path — LGTM

ParameterFilter correctly asserts MessageId passed to New-SqlDscAgentAlert and guards against unintended removals.


397-401: Severity creation path assertions — LGTM

Verifies New-SqlDscAgentAlert receives the right Severity and no unintended Set/Remove calls.


426-429: MessageId creation path assertions — LGTM

ParameterFilter precisely validates MessageId propagation; no superfluous operations invoked.

@codecov
Copy link

codecov bot commented Aug 29, 2025

Codecov Report

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

Additional details and impacted files

Impacted file tree graph

@@          Coverage Diff          @@
##           main   #2153    +/-   ##
=====================================
  Coverage    94%     94%            
=====================================
  Files       122     127     +5     
  Lines      8355    8530   +175     
=====================================
+ Hits       7910    8077   +167     
- Misses      445     453     +8     
Flag Coverage Δ
unit 94% <ø> (+<1%) ⬆️
Files with missing lines Coverage Δ
source/Classes/020.SqlAgentAlert.ps1 100% <ø> (+2%) ⬆️
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@johlju johlju merged commit b990bb0 into dsccommunity:main Aug 30, 2025
43 checks passed
@johlju johlju deleted the fix/sqlagentalert branch August 30, 2025 08:58
@coderabbitai coderabbitai bot mentioned this pull request Jan 3, 2026
9 tasks
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