-
Notifications
You must be signed in to change notification settings - Fork 227
Fix DatabasePermission and ServerPermission Equals() and add GetHashCode() override #2392
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
|
Note Other AI code review bot(s) detectedCodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review. WalkthroughFixed equality semantics in DatabasePermission and ServerPermission to compare both State and Permission, added consistent GetHashCode() implementations, updated unit tests accordingly, and changed Set-SqlDscServerPermission to only modify permission categories explicitly provided by parameters. Changes
Sequence Diagram(s)(omitted) Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Pre-merge checks✅ Passed checks (5 passed)
📜 Recent review detailsConfiguration used: Organization UI Review profile: CHILL Plan: Pro 📒 Files selected for processing (3)
🚧 Files skipped from review as they are similar to previous changes (2)
🧰 Additional context used📓 Path-based instructions (3)CHANGELOG.md📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-changelog.instructions.md)
Files:
⚙️ CodeRabbit configuration file
Files:
**/*.md📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-markdown.instructions.md)
Files:
⚙️ CodeRabbit configuration file
Files:
**⚙️ CodeRabbit configuration file
Files:
🧠 Learnings (4)📓 Common learnings📚 Learning: 2025-11-27T17:58:08.884ZApplied to files:
📚 Learning: 2025-11-27T17:58:08.884ZApplied to files:
📚 Learning: 2025-11-27T17:58:08.884ZApplied to files:
⏰ 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)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
- Fixed DatabasePermission.Equals() to compare State property instead of non-existent Grant property - Fixed ServerPermission.Equals() to compare State property instead of non-existent Grant property - Updated unit tests to expect correct behavior (Should -BeFalse when State differs) - All unit tests pass for both classes and dependent resources Co-authored-by: johlju <[email protected]>
- Added test cases for Grant vs GrantWithGrant comparison in DatabasePermission - Added test cases for Grant vs GrantWithGrant comparison in ServerPermission - All 58 unit tests pass for the permission classes - All 76 unit tests pass for dependent resources Co-authored-by: johlju <[email protected]>
|
@coderabbitai review |
✅ Actions performedReview triggered.
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🧹 Nitpick comments (3)
source/Classes/002.DatabasePermission.ps1 (1)
180-196: Equals() fix correctly usesState; consider long‑term hashing alignmentThe updated
Equals()now gates the permission comparison onState, which correctly fixes the earlier bug whereGrantwas referenced instead. The type check plusStateequality plusCompare-ObjectonPermissiongives the expected semantics for value comparison.As a follow‑up (not specific to this change), if
DatabasePermissioninstances are ever used in hash-based collections, you may want to add/align aGetHashCode()override with theState+ normalizedPermissionequality semantics to keep them consistent.CHANGELOG.md (1)
235-246: Avoid duplicate### Fixedsections under UnreleasedThe new
DatabasePermission/ServerPermissionentries are accurate and properly reference [issue #2386], but they sit under a second### Fixedheading within the[Unreleased]section. To align with the changelog guidelines (no duplicate sections per change type in Unreleased), consider moving these bullets under the existing### Fixedat Line 173 and removing this extra heading.
As per changelog guidelines.tests/Unit/Classes/ServerPermission.Tests.ps1 (1)
133-161: Test logic is correct; consider fixing variable naming in a follow-up.The test correctly validates that
ServerPermissionobjects with differentStatevalues (DenyvsGrant) are not equal.The variable name
$databasePermissionInstanceon lines 138 and 149 is misleading since it creates a[ServerPermission]object, not[DatabasePermission]. This naming inconsistency exists throughout the file (also on lines 196, 210, etc.), so it's consistent with existing code but could be cleaned up in a future refactor.
📜 Review details
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (5)
CHANGELOG.mdsource/Classes/002.DatabasePermission.ps1source/Classes/002.ServerPermission.ps1tests/Unit/Classes/DatabasePermission.Tests.ps1tests/Unit/Classes/ServerPermission.Tests.ps1
🧰 Additional context used
📓 Path-based instructions (14)
source/[cC]lasses/**/*.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-class-resource.instructions.md)
source/[cC]lasses/**/*.ps1: DSC class-based resources must be decorated with[DscResource(RunAsCredential = 'Optional')]or[DscResource(RunAsCredential = 'Mandatory')]based on requirements
DSC class-based resources must inherit fromResourceBaseclass from the DscResource.Base module
DSC class-based resources must use[Nullable[{FullTypeName}]]syntax for value-type properties (e.g.,[Nullable[System.Int32]])
DSC class-based resources must implement a required constructor with signatureResourceName () : base ($PSScriptRoot)and populate$this.ExcludeDscPropertiesarray
DSC class-based resources must implement required methods:Get(),Test(),Set(),GetCurrentState(), andModify()following the specified pattern
DSC class-based resources may optionally implement methods:AssertProperties()andNormalizeProperties()following the specified pattern
DSC class-based resources must include comment-based help with .DESCRIPTION section containing Requirements and Known issues sections with a link to all open issues on GitHub
DSC class-based resources must usetry/catchblocks for exception handling in classes
DSC class-based resources must useNew-*Exceptioncommands (such asNew-InvalidDataException,New-ArgumentException,New-InvalidOperationException,New-ObjectNotFoundException,New-InvalidResultException,New-NotImplementedException) instead ofthrowfor terminating errors in classes
Files:
source/Classes/002.DatabasePermission.ps1source/Classes/002.ServerPermission.ps1
⚙️ CodeRabbit configuration file
source/[cC]lasses/**/*.ps1: # DSC Class-Based Resource GuidelinesApplies 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.localizedDatahashtable auto-populated byResourceBasefrom 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/002.DatabasePermission.ps1source/Classes/002.ServerPermission.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 in PowerShell scripts
Use localized string keys from $script:localizedData, not hardcoded strings, in diagnostic messages
Reference localized strings using the syntax: Write-Verbose -Message ($script:localizedData.KeyName -f $value1)Localize all strings using string keys; remove any orphaned string keys
Files:
source/Classes/002.DatabasePermission.ps1source/Classes/002.ServerPermission.ps1
⚙️ CodeRabbit configuration file
source/**/*.ps1: # Localization GuidelinesRequirements
- Localize all Write-Debug, Write-Verbose, Write-Error, Write-Warning and $PSCmdlet.ThrowTerminatingError() messages
- Use localized string keys, not hardcoded strings
- Assume
$script:localizedDatais availableString Files
- Commands/functions:
source/en-US/{MyModuleName}.strings.psd1- Class resources:
source/en-US/{ResourceClassName}.strings.psd1Key Naming Patterns
- Format:
Verb_FunctionName_Action(underscore separators), e.g.Get_Database_ConnectingToDatabaseString Format
ConvertFrom-StringData @' KeyName = Message with {0} placeholder. (PREFIX0001) '@String IDs
- Format:
(PREFIX####)- PREFIX: First letter of each word in class or function name (SqlSetup → SS, Get-SqlDscDatabase → GSDD)
- Number: Sequential from 0001
Usage
Write-Verbose -Message ($script:localizedData.KeyName -f $value1)
Files:
source/Classes/002.DatabasePermission.ps1source/Classes/002.ServerPermission.ps1
source/Classes/*.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines.instructions.md)
source/Classes/*.ps1: Classes should be located insource/Classes/{DependencyGroupNumber}.{ClassName}.ps1
DSC resources should always be created as class-based resources
Files:
source/Classes/002.DatabasePermission.ps1source/Classes/002.ServerPermission.ps1
**/*.{ps1,psm1,psd1}
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-powershell.instructions.md)
**/*.{ps1,psm1,psd1}: Use descriptive names (3+ characters, no abbreviations) for functions, parameters, variables, and classes
Functions: Use PascalCase with Verb-Noun format using approved verbs
Parameters: Use PascalCase naming
Variables: Use camelCase naming
Keywords: Use lower-case
Classes: Use PascalCase naming
Include scope for script/global/environment variables:$script:,$global:,$env:
Use 4 spaces for indentation (no tabs)
Use one space around operators:$a = 1 + 2
Use one space between type and variable:[String] $name
Use one space between keyword and parenthesis:if ($condition)
No spaces on empty lines
Limit lines to 120 characters
Place newline before opening brace (except variable assignments)
Place one newline after opening brace
Place two newlines after closing brace (one if followed by another brace or continuation)
Use single quotes unless variable expansion is needed:'text'vs"text $variable"
For single-line arrays use:@('one', 'two', 'three')
For multi-line arrays: place each element on separate line with proper indentation
Do not use the unary comma operator (,) in return statements to force an array
For empty hashtables use:@{}
For hashtables: place each property on separate line with proper indentation and use PascalCase for property names
Single-line comments: use# Commentformat (capitalized, on own line)
Multi-line comments: use<# Comment #>format (opening and closing brackets on own line with indented text)
No commented-out code
Always add comment-based help to all functions and scripts with SYNOPSIS, DESCRIPTION (40+ chars), PARAMETER, and EXAMPLE sections before function/class
Comment-based help indentation: keywords 4 spaces, text 8 spaces
Include examples in comment-based help for all parameter sets and combinations
INPUTS section in comment-based help: List each pipeline-accepted type as inline code with a 1-line description, repeat keyword for each input type, specifyNone.if there are no inp...
Files:
source/Classes/002.DatabasePermission.ps1tests/Unit/Classes/ServerPermission.Tests.ps1source/Classes/002.ServerPermission.ps1tests/Unit/Classes/DatabasePermission.Tests.ps1
**/[0-9][0-9][0-9].*.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-powershell.instructions.md)
Class files: Use
###.ClassName.ps1format (e.g.,001.SqlReason.ps1,004.StartupParameters.ps1)
Files:
source/Classes/002.DatabasePermission.ps1source/Classes/002.ServerPermission.ps1
**
⚙️ CodeRabbit configuration file
**: # DSC Community GuidelinesTerminology
- Command: Public command
- Function: Private function
- Resource: DSC class-based resource
Build & Test Workflow Requirements
- Run PowerShell script files from repository root
- Setup build and test environment (once per
pwshsession):./build.ps1 -Tasks noop- Build project before running tests:
./build.ps1 -Tasks build- Always run tests in new
pwshsession:Invoke-Pester -Path @({test paths}) -Output DetailedFile Organization
- Public commands:
source/Public/{CommandName}.ps1- Private functions:
source/Private/{FunctionName}.ps1- Classes:
source/Classes/{DependencyGroupNumber}.{ClassName}.ps1- Enums:
source/Enum/{DependencyGroupNumber}.{EnumName}.ps1- Unit tests:
tests/Unit/{Classes|Public|Private}/{Name}.Tests.ps1- Integration tests:
tests/Integration/Commands/{CommandName}.Integration.Tests.ps1Requirements
- Follow instructions over existing code patterns
- Follow PowerShell style and test guideline instructions strictly
- Always update CHANGELOG.md Unreleased section
- Localize all strings using string keys; remove any orphaned string keys
- Check DscResource.Common before creating private functions
- Separate reusable logic into private functions
- DSC resources should always be created as class-based resources
- Add unit tests for all commands/functions/resources
- Add integration tests for all public commands and resources
Files:
source/Classes/002.DatabasePermission.ps1tests/Unit/Classes/ServerPermission.Tests.ps1source/Classes/002.ServerPermission.ps1tests/Unit/Classes/DatabasePermission.Tests.ps1CHANGELOG.md
{**/*.ps1,**/*.psm1,**/*.psd1}
⚙️ CodeRabbit configuration file
{**/*.ps1,**/*.psm1,**/*.psd1}: # PowerShell GuidelinesNaming
- Use descriptive names (3+ characters, no abbreviations)
- Functions: PascalCase with Verb-Noun format using approved verbs
- Parameters: PascalCase
- Variables: camelCase
- Keywords: lower-case
- Classes: PascalCase
- Include scope for script/global/environment variables:
$script:,$global:,$env:File naming
- Class files:
###.ClassName.ps1format (e.g.001.SqlReason.ps1,004.StartupParameters.ps1)Formatting
Indentation & Spacing
- Use 4 spaces (no tabs)
- One space around operators:
$a = 1 + 2- One space between type and variable:
[String] $name- One space between keyword and parenthesis:
if ($condition)- No spaces on empty lines
- Try to limit lines to 120 characters
Braces
- Newline before opening brace (except variable assignments)
- One newline after opening brace
- Two newlines after closing brace (one if followed by another brace or continuation)
Quotes
- Use single quotes unless variable expansion is needed:
'text'vs"text $variable"Arrays
- Single line:
@('one', 'two', 'three')- Multi-line: each element on separate line with proper indentation
- Do not use the unary comma operator (
,) in return statements to force
an arrayHashtables
- Empty:
@{}- Each property on separate line with proper indentation
- Properties: Use PascalCase
Comments
- Single line:
# Comment(capitalized, on own line)- Multi-line:
<# Comment #>format (opening and closing brackets on own line), and indent text- No commented-out code
Comment-based help
- Always add comment-based help to all functions and scripts
- Comment-based help: SYNOPSIS, DESCRIPTION (40+ chars), PARAMETER, EXAMPLE sections before function/class
- Comment-based help indentation: keywords 4 spaces, text 8 spaces
- Include examples for all parameter sets and combinations
- INPUTS: List each pipeline‑accepted type as inline code with a 1‑line description...
Files:
source/Classes/002.DatabasePermission.ps1tests/Unit/Classes/ServerPermission.Tests.ps1source/Classes/002.ServerPermission.ps1tests/Unit/Classes/DatabasePermission.Tests.ps1
**/*.[Tt]ests.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-pester.instructions.md)
**/*.[Tt]ests.ps1: All public commands, private functions and classes must have unit tests
All public commands and class-based resources must have integration tests
Use Pester v5 syntax only
Test code only insideDescribeblocks
Assertions only inItblocks
Never test verbose messages, debug messages or parameter binding behavior
Pass all mandatory parameters to avoid prompts
InsideItblocks, assign unused return objects to$null(unless part of pipeline)
Tested entity must be called from within theItblocks
Keep results and assertions in sameItblock
Avoid try-catch-finally for cleanup, useAfterAllorAfterEach
Avoid unnecessary remove/recreate cycles
OneDescribeblock per file matching the tested entity name
Contextdescriptions start with 'When'
Itdescriptions start with 'Should', must not contain 'when'
Mock variables prefix: 'mock'
Public commands: Never useInModuleScope(unless retrieving localized strings or creating an object using an internal class)
Private functions/class resources: Always useInModuleScope
Each class method = separateContextblock
Each scenario = separateContextblock
Use nestedContextblocks for complex scenarios
Mocking inBeforeAll(BeforeEachonly when required)
Setup/teardown inBeforeAll,BeforeEach/AfterAll,AfterEachclose to usage
Spacing between blocks, arrange, act, and assert for readability
PascalCase:Describe,Context,It,Should,BeforeAll,BeforeEach,AfterAll,AfterEach
Use-BeTrue/-BeFalsenever-Be $true/-Be $false
Never useAssert-MockCalled, useShould -Invokeinstead
NoShould -Not -Throw- invoke commands directly
Never add an empty-MockWithblock
Omit-MockWithwhen returning$null
Set$PSDefaultParameterValuesforMock:ModuleName,Should:ModuleName,InModuleScope:ModuleName
Omit-ModuleNameparameter on Pester commands
Never useMockinsideInModuleScope-block
Never useparam()inside-MockWithscriptblock...
Files:
tests/Unit/Classes/ServerPermission.Tests.ps1tests/Unit/Classes/DatabasePermission.Tests.ps1
⚙️ CodeRabbit configuration file
**/*.[Tt]ests.ps1: # Tests GuidelinesCore Requirements
- All public commands, private functions and classes must have unit tests
- All public commands and class-based resources must have integration tests
- Use Pester v5 syntax only
- Test code only inside
Describeblocks- Assertions only in
Itblocks- Never test verbose messages, debug messages or parameter binding behavior
- Pass all mandatory parameters to avoid prompts
Requirements
- Inside
Itblocks, assign unused return objects to$null(unless part of pipeline)- Tested entity must be called from within the
Itblocks- Keep results and assertions in same
Itblock- Avoid try-catch-finally for cleanup, use
AfterAllorAfterEach- Avoid unnecessary remove/recreate cycles
Naming
- One
Describeblock per file matching the tested entity nameContextdescriptions start with 'When'Itdescriptions start with 'Should', must not contain 'when'- Mock variables prefix: 'mock'
Structure & Scope
- Public commands: Never use
InModuleScope(unless retrieving localized strings or creating an object using an internal class)- Private functions/class resources: Always use
InModuleScope- Each class method = separate
Contextblock- Each scenario = separate
Contextblock- Use nested
Contextblocks for complex scenarios- Mocking in
BeforeAll(BeforeEachonly when required)- Setup/teardown in
BeforeAll,BeforeEach/AfterAll,AfterEachclose to usage- Spacing between blocks, arrange, act, and assert for readability
Syntax Rules
- PascalCase:
Describe,Context,It,Should,BeforeAll,BeforeEach,AfterAll,AfterEach- Use
-BeTrue/-BeFalsenever-Be $true/-Be $false- Never use
Assert-MockCalled, useShould -Invokeinstead- No
Should -Not -Throw- invoke commands directly- Never add an empty
-MockWithblock- Omit
-MockWithwhen returning$null- Set
$PSDefaultParameterValuesforMock:ModuleName,Should:ModuleName, `...
Files:
tests/Unit/Classes/ServerPermission.Tests.ps1tests/Unit/Classes/DatabasePermission.Tests.ps1
tests/Unit/Classes/*.[Tt]ests.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-pester.instructions.md)
Class resources:
tests/Unit/Classes/{Name}.Tests.ps1
Files:
tests/Unit/Classes/ServerPermission.Tests.ps1tests/Unit/Classes/DatabasePermission.Tests.ps1
tests/Unit/**/*.Tests.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines.instructions.md)
Unit tests should be located in
tests/Unit/{Classes|Public|Private}/{Name}.Tests.ps1
Files:
tests/Unit/Classes/ServerPermission.Tests.ps1tests/Unit/Classes/DatabasePermission.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: Test with localized strings usingInModuleScope -ScriptBlock { $script:localizedData.Key }in Pester unit tests
Mock files using the$TestDrivevariable (path to the test drive) in Pester unit tests
All public commands require parameter set validation tests in unit tests
Use the exact Pester test setup block withBeforeDiscovery,BeforeAll, andAfterAllblocks beforeDescribein unit tests, includingDscResource.Testmodule import and PSDefaultParameterValues configuration
Use parameter set validation test template withGet-CommandandParameterSetsproperty, supporting both single and multiple parameter sets via-ForEacharray in Pester unit tests
Use parameter properties test template withGet-Commandto validate individual parameter attributes (e.g., Mandatory flag) in Pester unit tests
Files:
tests/Unit/Classes/ServerPermission.Tests.ps1tests/Unit/Classes/DatabasePermission.Tests.ps1
⚙️ CodeRabbit configuration file
tests/[Uu]nit/**/*.[Tt]ests.ps1: # Unit Tests Guidelines
- Test with localized strings: Use
InModuleScope -ScriptBlock { $script:localizedData.Key }- Mock files: Use
$TestDrivevariable (path to the test drive)- All public commands require parameter set validation tests
- After modifying classes, always run tests in new session (for changes to take effect)
Test Setup Requirements
Use this exact setup block before
Describe:[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification = 'Suppressing this rule because Script Analyzer does not understand Pester syntax.')] param () BeforeDiscovery { try { if (-not (Get-Module -Name 'DscResource.Test')) { # Assumes dependencies have been resolved, so if this module is not available, run 'noop' task. if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) { # Redirect all streams to $null, except the error stream (stream 2) & "$PSScriptRoot/../../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null } # If the dependencies have not been resolved, this will throw an error. Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' } } catch [System.IO.FileNotFoundException] { throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks noop" first.' } } BeforeAll { $script:moduleName = '{MyModuleName}' Import-Module -Name $script:moduleName -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:ModuleName') ...
Files:
tests/Unit/Classes/ServerPermission.Tests.ps1tests/Unit/Classes/DatabasePermission.Tests.ps1
**/tests/Unit/**/*.ps1
📄 CodeRabbit inference engine (.github/instructions/SqlServerDsc-guidelines.instructions.md)
**/tests/Unit/**/*.ps1: Unit tests must use SMO stub types from SMO.cs, never mock SMO types
Unit tests must add$env:SqlServerDscCI = $trueinBeforeAllblock and remove inAfterAllblock
Load SMO stub types from SMO.cs in unit test files usingAdd-Type -Path "$PSScriptRoot/../Stubs/SMO.cs"
Files:
tests/Unit/Classes/ServerPermission.Tests.ps1tests/Unit/Classes/DatabasePermission.Tests.ps1
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 in CHANGELOG.md
Describe notable changes briefly in CHANGELOG.md, ≤2 items per change type
Reference issues using format issue #<issue_number> in CHANGELOG.md
No empty lines between list items in same section of CHANGELOG.md
Skip adding entry if same change already exists in Unreleased section of CHANGELOG.md
No duplicate sections or items in Unreleased section of CHANGELOG.mdAlways update 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
- Skip adding entry if same change already exists in Unreleased section
- No duplicate sections or items in Unreleased section
Files:
CHANGELOG.md
**/*.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 files
Use '1.' for all items in ordered lists (1/1/1 numbering style)
DisableMD013rule 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
Format parameters using bold in Markdown documentation
Format values and literals usinginline codein Markdown documentation
Format resource/module/product names using italic in Markdown documentation
Format commands/files/paths usinginline codein Markdown documentation
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
MD013rule by adding a comment for tables/code blocks exceeding 80 characters- Empty lines required before/after code blocks and headings (except before line 1)
- Escape backslashes in file paths only (not in code blocks)
- Code blocks must specify language identifiers
Text Formatting
- Parameters: bold
- Values/literals:
inline code- Resource/module/product names: italic
- Commands/files/paths:
inline code
Files:
CHANGELOG.md
🧠 Learnings (21)
📚 Learning: 2026-01-01T11:57:15.286Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2026-01-01T11:57:15.286Z
Learning: Applies to **/tests/Unit/**/*.ps1 : Unit tests must add `$env:SqlServerDscCI = $true` in `BeforeAll` block and remove in `AfterAll` block
Applied to files:
tests/Unit/Classes/ServerPermission.Tests.ps1tests/Unit/Classes/DatabasePermission.Tests.ps1
📚 Learning: 2025-11-27T17:59:27.205Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-11-27T17:59:27.205Z
Learning: Applies to **/*.[Tt]ests.ps1 : Use nested `Context` blocks for complex scenarios
Applied to files:
tests/Unit/Classes/ServerPermission.Tests.ps1tests/Unit/Classes/DatabasePermission.Tests.ps1
📚 Learning: 2025-11-27T17:59:27.205Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-11-27T17:59:27.205Z
Learning: Applies to tests/Unit/Private/*.[Tt]ests.ps1 : Private functions: `tests/Unit/Private/{Name}.Tests.ps1`
Applied to files:
tests/Unit/Classes/ServerPermission.Tests.ps1tests/Unit/Classes/DatabasePermission.Tests.ps1
📚 Learning: 2025-11-27T17:59:27.205Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-11-27T17:59:27.205Z
Learning: Applies to **/*.[Tt]ests.ps1 : Each scenario = separate `Context` block
Applied to files:
tests/Unit/Classes/ServerPermission.Tests.ps1tests/Unit/Classes/DatabasePermission.Tests.ps1
📚 Learning: 2025-11-27T17:59:27.205Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-11-27T17:59:27.205Z
Learning: Applies to **/*.[Tt]ests.ps1 : Each class method = separate `Context` block
Applied to files:
tests/Unit/Classes/ServerPermission.Tests.ps1tests/Unit/Classes/DatabasePermission.Tests.ps1
📚 Learning: 2025-11-27T17:59:27.205Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-11-27T17:59:27.205Z
Learning: Applies to tests/Unit/Public/*.[Tt]ests.ps1 : Public commands: `tests/Unit/Public/{Name}.Tests.ps1`
Applied to files:
tests/Unit/Classes/ServerPermission.Tests.ps1tests/Unit/Classes/DatabasePermission.Tests.ps1
📚 Learning: 2025-12-30T15:15:25.261Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-integration-tests.instructions.md:0-0
Timestamp: 2025-12-30T15:15:25.261Z
Learning: Applies to tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1 : Integration tests must cover all scenarios and code paths
Applied to files:
tests/Unit/Classes/ServerPermission.Tests.ps1
📚 Learning: 2025-08-17T10:13:30.079Z
Learnt from: johlju
Repo: dsccommunity/SqlServerDsc PR: 2136
File: source/Public/Remove-SqlDscLogin.ps1:104-108
Timestamp: 2025-08-17T10:13:30.079Z
Learning: In SqlServerDsc unit tests, SMO object stubs (like Login objects) should have properly mocked Parent properties with correct Server stub types and valid InstanceName values, rather than handling null Parent scenarios in production code.
Applied to files:
tests/Unit/Classes/ServerPermission.Tests.ps1tests/Unit/Classes/DatabasePermission.Tests.ps1
📚 Learning: 2025-11-27T17:59:27.205Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-11-27T17:59:27.205Z
Learning: Applies to **/*.[Tt]ests.ps1 : Assertions only in `It` blocks
Applied to files:
tests/Unit/Classes/ServerPermission.Tests.ps1
📚 Learning: 2025-12-30T15:15:25.261Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-integration-tests.instructions.md:0-0
Timestamp: 2025-12-30T15:15:25.261Z
Learning: Applies to tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1 : Avoid using `ExpectedMessage` parameter for `Should -Throw` assertions in integration tests
Applied to files:
tests/Unit/Classes/ServerPermission.Tests.ps1
📚 Learning: 2025-11-27T17:59:27.205Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-11-27T17:59:27.205Z
Learning: Applies to **/*.[Tt]ests.ps1 : Never use `Mock` inside `InModuleScope`-block
Applied to files:
tests/Unit/Classes/ServerPermission.Tests.ps1tests/Unit/Classes/DatabasePermission.Tests.ps1
📚 Learning: 2025-11-27T17:59:27.205Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-11-27T17:59:27.205Z
Learning: Applies to **/*.[Tt]ests.ps1 : Never use `Assert-MockCalled`, use `Should -Invoke` instead
Applied to files:
tests/Unit/Classes/ServerPermission.Tests.ps1tests/Unit/Classes/DatabasePermission.Tests.ps1
📚 Learning: 2025-11-27T17:59:27.205Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-11-27T17:59:27.205Z
Learning: Applies to **/*.[Tt]ests.ps1 : Omit `-MockWith` when returning `$null`
Applied to files:
tests/Unit/Classes/ServerPermission.Tests.ps1tests/Unit/Classes/DatabasePermission.Tests.ps1
📚 Learning: 2025-09-25T16:38:08.867Z
Learnt from: johlju
Repo: dsccommunity/ActiveDirectoryDsc PR: 741
File: tests/Integration/MSFT_ADReadOnlyDomainControllerAccount.Integration.Tests.ps1:102-104
Timestamp: 2025-09-25T16:38:08.867Z
Learning: The PowerShell guideline "Use -BeTrue/-BeFalse; never use -Be $true/-Be $false" applies only when the actual return value is a boolean. When a cmdlet returns string values like 'True' or 'False', Should -Be 'True' is the appropriate assertion.
Applied to files:
tests/Unit/Classes/ServerPermission.Tests.ps1tests/Unit/Classes/DatabasePermission.Tests.ps1
📚 Learning: 2026-01-01T11:57:15.286Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2026-01-01T11:57:15.286Z
Learning: Applies to **/tests/Integration/**/*.ps1 : Integration tests must use `Disconnect-SqlDscDatabaseEngine` after `Connect-SqlDscDatabaseEngine`
Applied to files:
tests/Unit/Classes/DatabasePermission.Tests.ps1
📚 Learning: 2025-11-27T17:59:27.205Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-11-27T17:59:27.205Z
Learning: Applies to **/*.[Tt]ests.ps1 : `Context` descriptions start with 'When'
Applied to files:
tests/Unit/Classes/DatabasePermission.Tests.ps1
📚 Learning: 2026-01-01T11:57:15.286Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2026-01-01T11:57:15.286Z
Learning: Applies to **/tests/Integration/**/*.ps1 : Integration tests must use `Connect-SqlDscDatabaseEngine` for SQL Server DB session with correct CI credentials
Applied to files:
tests/Unit/Classes/DatabasePermission.Tests.ps1
📚 Learning: 2025-11-27T17:59:27.205Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-11-27T17:59:27.205Z
Learning: Applies to **/*.[Tt]ests.ps1 : PascalCase: `Describe`, `Context`, `It`, `Should`, `BeforeAll`, `BeforeEach`, `AfterAll`, `AfterEach`
Applied to files:
tests/Unit/Classes/DatabasePermission.Tests.ps1
📚 Learning: 2025-11-27T17:59:27.205Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-11-27T17:59:27.205Z
Learning: Applies to **/*.[Tt]ests.ps1 : Mocking in `BeforeAll` (`BeforeEach` only when required)
Applied to files:
tests/Unit/Classes/DatabasePermission.Tests.ps1
📚 Learning: 2025-11-27T17:59:27.205Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-11-27T17:59:27.205Z
Learning: Applies to **/*.[Tt]ests.ps1 : Use `-BeTrue`/`-BeFalse` never `-Be $true`/`-Be $false`
Applied to files:
tests/Unit/Classes/DatabasePermission.Tests.ps1
📚 Learning: 2025-11-27T17:58:08.884Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-changelog.instructions.md:0-0
Timestamp: 2025-11-27T17:58:08.884Z
Learning: Applies to CHANGELOG.md : Describe notable changes briefly in CHANGELOG.md, ≤2 items per change type
Applied to files:
CHANGELOG.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). (2)
- GitHub Check: PSScriptAnalyzer
- GitHub Check: dsccommunity.SqlServerDsc (Build Package Module)
🔇 Additional comments (4)
tests/Unit/Classes/DatabasePermission.Tests.ps1 (2)
133-161: New test context correctly validates State-based inequality.The test properly verifies that
DatabasePermissionobjects withState = 'Deny'andState = 'Grant'are not equal, which validates the bug fix in theEquals()method.
163-191: Test coverage for Grant vs GrantWithGrant looks good.This context correctly tests the second State combination to ensure inequality is properly detected.
source/Classes/002.ServerPermission.ps1 (1)
112-128: Correct fix for the State property comparison.The change from comparing the non-existent
Grantproperty to the actualStateproperty correctly fixes the equality logic. Previously, comparing undefined properties would always return$true(since$null -eq $null), causing incorrect equality results.tests/Unit/Classes/ServerPermission.Tests.ps1 (1)
163-191: Test coverage for Grant vs GrantWithGrant is correct.This context properly tests that objects with
State = 'Grant'andState = 'GrantWithGrant'are not considered equal, validating the fix to theEquals()method.
|
@copilot can we resolve this too?
|
- Added GetHashCode() override to DatabasePermission and ServerPermission to align with Equals() semantics - Hash code is based on State and sorted Permission values for consistent behavior - Fixed misleading variable naming in ServerPermission.Tests.ps1 (42 instances) - Added comprehensive unit tests for GetHashCode() method in both classes - All 64 unit tests pass (32 per class) - All 76 dependent resource tests pass Co-authored-by: johlju <[email protected]>
Done in commit bffc1ab. Both issues have been resolved:
Added comprehensive unit tests for |
|
@coderabbitai review |
✅ Actions performedReview triggered.
|
johlju
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@johlju reviewed 5 files and all commit messages, and made 1 comment.
Reviewable status:complete! all files reviewed, all discussions resolved (waiting on @copilot[bot]).
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 2
🧹 Nitpick comments (2)
source/Classes/002.DatabasePermission.ps1 (1)
198-210: GetHashCode() implementation is correct and aligns with Equals() semantics.The method properly combines
Statewith sortedPermissionvalues using XOR, ensuring consistent hash codes for equal objects regardless of Permission ordering.Optional: Initialize hashCode directly
The initial assignment to
0on line 200 is immediately overwritten on line 202. Consider initializing directly:[System.Int32] GetHashCode() { - [System.Int32] $hashCode = 0 - - $hashCode = $this.State.GetHashCode() + [System.Int32] $hashCode = $this.State.GetHashCode() foreach ($permission in ($this.Permission | Sort-Object)) { $hashCode = $hashCode -bxor $permission.GetHashCode() } return $hashCode }source/Classes/002.ServerPermission.ps1 (1)
130-147: GetHashCode() implementation is correct and consistent with DatabasePermission.The method properly combines
Statewith sortedPermissionvalues using XOR. The TODO comment appropriately notes the code duplication between DatabasePermission and ServerPermission.Optional: Initialize hashCode directly
Same minor optimization as DatabasePermission - the initial assignment to
0on line 137 is immediately overwritten on line 139:[System.Int32] GetHashCode() { - [System.Int32] $hashCode = 0 - - $hashCode = $this.State.GetHashCode() + [System.Int32] $hashCode = $this.State.GetHashCode() foreach ($permission in ($this.Permission | Sort-Object)) { $hashCode = $hashCode -bxor $permission.GetHashCode() } return $hashCode }
📜 Review details
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (5)
CHANGELOG.mdsource/Classes/002.DatabasePermission.ps1source/Classes/002.ServerPermission.ps1tests/Unit/Classes/DatabasePermission.Tests.ps1tests/Unit/Classes/ServerPermission.Tests.ps1
🧰 Additional context used
📓 Path-based instructions (14)
source/[cC]lasses/**/*.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-class-resource.instructions.md)
source/[cC]lasses/**/*.ps1: DSC class-based resources must be decorated with[DscResource(RunAsCredential = 'Optional')]or[DscResource(RunAsCredential = 'Mandatory')]based on requirements
DSC class-based resources must inherit fromResourceBaseclass from the DscResource.Base module
DSC class-based resources must use[Nullable[{FullTypeName}]]syntax for value-type properties (e.g.,[Nullable[System.Int32]])
DSC class-based resources must implement a required constructor with signatureResourceName () : base ($PSScriptRoot)and populate$this.ExcludeDscPropertiesarray
DSC class-based resources must implement required methods:Get(),Test(),Set(),GetCurrentState(), andModify()following the specified pattern
DSC class-based resources may optionally implement methods:AssertProperties()andNormalizeProperties()following the specified pattern
DSC class-based resources must include comment-based help with .DESCRIPTION section containing Requirements and Known issues sections with a link to all open issues on GitHub
DSC class-based resources must usetry/catchblocks for exception handling in classes
DSC class-based resources must useNew-*Exceptioncommands (such asNew-InvalidDataException,New-ArgumentException,New-InvalidOperationException,New-ObjectNotFoundException,New-InvalidResultException,New-NotImplementedException) instead ofthrowfor terminating errors in classes
Files:
source/Classes/002.ServerPermission.ps1source/Classes/002.DatabasePermission.ps1
⚙️ CodeRabbit configuration file
source/[cC]lasses/**/*.ps1: # DSC Class-Based Resource GuidelinesApplies 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.localizedDatahashtable auto-populated byResourceBasefrom 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/002.ServerPermission.ps1source/Classes/002.DatabasePermission.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 in PowerShell scripts
Use localized string keys from $script:localizedData, not hardcoded strings, in diagnostic messages
Reference localized strings using the syntax: Write-Verbose -Message ($script:localizedData.KeyName -f $value1)Localize all strings using string keys; remove any orphaned string keys
Files:
source/Classes/002.ServerPermission.ps1source/Classes/002.DatabasePermission.ps1
⚙️ CodeRabbit configuration file
source/**/*.ps1: # Localization GuidelinesRequirements
- Localize all Write-Debug, Write-Verbose, Write-Error, Write-Warning and $PSCmdlet.ThrowTerminatingError() messages
- Use localized string keys, not hardcoded strings
- Assume
$script:localizedDatais availableString Files
- Commands/functions:
source/en-US/{MyModuleName}.strings.psd1- Class resources:
source/en-US/{ResourceClassName}.strings.psd1Key Naming Patterns
- Format:
Verb_FunctionName_Action(underscore separators), e.g.Get_Database_ConnectingToDatabaseString Format
ConvertFrom-StringData @' KeyName = Message with {0} placeholder. (PREFIX0001) '@String IDs
- Format:
(PREFIX####)- PREFIX: First letter of each word in class or function name (SqlSetup → SS, Get-SqlDscDatabase → GSDD)
- Number: Sequential from 0001
Usage
Write-Verbose -Message ($script:localizedData.KeyName -f $value1)
Files:
source/Classes/002.ServerPermission.ps1source/Classes/002.DatabasePermission.ps1
source/Classes/*.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines.instructions.md)
source/Classes/*.ps1: Classes should be located insource/Classes/{DependencyGroupNumber}.{ClassName}.ps1
DSC resources should always be created as class-based resources
Files:
source/Classes/002.ServerPermission.ps1source/Classes/002.DatabasePermission.ps1
**/*.{ps1,psm1,psd1}
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-powershell.instructions.md)
**/*.{ps1,psm1,psd1}: Use descriptive names (3+ characters, no abbreviations) for functions, parameters, variables, and classes
Functions: Use PascalCase with Verb-Noun format using approved verbs
Parameters: Use PascalCase naming
Variables: Use camelCase naming
Keywords: Use lower-case
Classes: Use PascalCase naming
Include scope for script/global/environment variables:$script:,$global:,$env:
Use 4 spaces for indentation (no tabs)
Use one space around operators:$a = 1 + 2
Use one space between type and variable:[String] $name
Use one space between keyword and parenthesis:if ($condition)
No spaces on empty lines
Limit lines to 120 characters
Place newline before opening brace (except variable assignments)
Place one newline after opening brace
Place two newlines after closing brace (one if followed by another brace or continuation)
Use single quotes unless variable expansion is needed:'text'vs"text $variable"
For single-line arrays use:@('one', 'two', 'three')
For multi-line arrays: place each element on separate line with proper indentation
Do not use the unary comma operator (,) in return statements to force an array
For empty hashtables use:@{}
For hashtables: place each property on separate line with proper indentation and use PascalCase for property names
Single-line comments: use# Commentformat (capitalized, on own line)
Multi-line comments: use<# Comment #>format (opening and closing brackets on own line with indented text)
No commented-out code
Always add comment-based help to all functions and scripts with SYNOPSIS, DESCRIPTION (40+ chars), PARAMETER, and EXAMPLE sections before function/class
Comment-based help indentation: keywords 4 spaces, text 8 spaces
Include examples in comment-based help for all parameter sets and combinations
INPUTS section in comment-based help: List each pipeline-accepted type as inline code with a 1-line description, repeat keyword for each input type, specifyNone.if there are no inp...
Files:
source/Classes/002.ServerPermission.ps1tests/Unit/Classes/ServerPermission.Tests.ps1source/Classes/002.DatabasePermission.ps1tests/Unit/Classes/DatabasePermission.Tests.ps1
**/[0-9][0-9][0-9].*.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-powershell.instructions.md)
Class files: Use
###.ClassName.ps1format (e.g.,001.SqlReason.ps1,004.StartupParameters.ps1)
Files:
source/Classes/002.ServerPermission.ps1source/Classes/002.DatabasePermission.ps1
**
⚙️ CodeRabbit configuration file
**: # DSC Community GuidelinesTerminology
- Command: Public command
- Function: Private function
- Resource: DSC class-based resource
Build & Test Workflow Requirements
- Run PowerShell script files from repository root
- Setup build and test environment (once per
pwshsession):./build.ps1 -Tasks noop- Build project before running tests:
./build.ps1 -Tasks build- Always run tests in new
pwshsession:Invoke-Pester -Path @({test paths}) -Output DetailedFile Organization
- Public commands:
source/Public/{CommandName}.ps1- Private functions:
source/Private/{FunctionName}.ps1- Classes:
source/Classes/{DependencyGroupNumber}.{ClassName}.ps1- Enums:
source/Enum/{DependencyGroupNumber}.{EnumName}.ps1- Unit tests:
tests/Unit/{Classes|Public|Private}/{Name}.Tests.ps1- Integration tests:
tests/Integration/Commands/{CommandName}.Integration.Tests.ps1Requirements
- Follow instructions over existing code patterns
- Follow PowerShell style and test guideline instructions strictly
- Always update CHANGELOG.md Unreleased section
- Localize all strings using string keys; remove any orphaned string keys
- Check DscResource.Common before creating private functions
- Separate reusable logic into private functions
- DSC resources should always be created as class-based resources
- Add unit tests for all commands/functions/resources
- Add integration tests for all public commands and resources
Files:
source/Classes/002.ServerPermission.ps1tests/Unit/Classes/ServerPermission.Tests.ps1source/Classes/002.DatabasePermission.ps1tests/Unit/Classes/DatabasePermission.Tests.ps1CHANGELOG.md
{**/*.ps1,**/*.psm1,**/*.psd1}
⚙️ CodeRabbit configuration file
{**/*.ps1,**/*.psm1,**/*.psd1}: # PowerShell GuidelinesNaming
- Use descriptive names (3+ characters, no abbreviations)
- Functions: PascalCase with Verb-Noun format using approved verbs
- Parameters: PascalCase
- Variables: camelCase
- Keywords: lower-case
- Classes: PascalCase
- Include scope for script/global/environment variables:
$script:,$global:,$env:File naming
- Class files:
###.ClassName.ps1format (e.g.001.SqlReason.ps1,004.StartupParameters.ps1)Formatting
Indentation & Spacing
- Use 4 spaces (no tabs)
- One space around operators:
$a = 1 + 2- One space between type and variable:
[String] $name- One space between keyword and parenthesis:
if ($condition)- No spaces on empty lines
- Try to limit lines to 120 characters
Braces
- Newline before opening brace (except variable assignments)
- One newline after opening brace
- Two newlines after closing brace (one if followed by another brace or continuation)
Quotes
- Use single quotes unless variable expansion is needed:
'text'vs"text $variable"Arrays
- Single line:
@('one', 'two', 'three')- Multi-line: each element on separate line with proper indentation
- Do not use the unary comma operator (
,) in return statements to force
an arrayHashtables
- Empty:
@{}- Each property on separate line with proper indentation
- Properties: Use PascalCase
Comments
- Single line:
# Comment(capitalized, on own line)- Multi-line:
<# Comment #>format (opening and closing brackets on own line), and indent text- No commented-out code
Comment-based help
- Always add comment-based help to all functions and scripts
- Comment-based help: SYNOPSIS, DESCRIPTION (40+ chars), PARAMETER, EXAMPLE sections before function/class
- Comment-based help indentation: keywords 4 spaces, text 8 spaces
- Include examples for all parameter sets and combinations
- INPUTS: List each pipeline‑accepted type as inline code with a 1‑line description...
Files:
source/Classes/002.ServerPermission.ps1tests/Unit/Classes/ServerPermission.Tests.ps1source/Classes/002.DatabasePermission.ps1tests/Unit/Classes/DatabasePermission.Tests.ps1
**/*.[Tt]ests.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-pester.instructions.md)
**/*.[Tt]ests.ps1: All public commands, private functions and classes must have unit tests
All public commands and class-based resources must have integration tests
Use Pester v5 syntax only
Test code only insideDescribeblocks
Assertions only inItblocks
Never test verbose messages, debug messages or parameter binding behavior
Pass all mandatory parameters to avoid prompts
InsideItblocks, assign unused return objects to$null(unless part of pipeline)
Tested entity must be called from within theItblocks
Keep results and assertions in sameItblock
Avoid try-catch-finally for cleanup, useAfterAllorAfterEach
Avoid unnecessary remove/recreate cycles
OneDescribeblock per file matching the tested entity name
Contextdescriptions start with 'When'
Itdescriptions start with 'Should', must not contain 'when'
Mock variables prefix: 'mock'
Public commands: Never useInModuleScope(unless retrieving localized strings or creating an object using an internal class)
Private functions/class resources: Always useInModuleScope
Each class method = separateContextblock
Each scenario = separateContextblock
Use nestedContextblocks for complex scenarios
Mocking inBeforeAll(BeforeEachonly when required)
Setup/teardown inBeforeAll,BeforeEach/AfterAll,AfterEachclose to usage
Spacing between blocks, arrange, act, and assert for readability
PascalCase:Describe,Context,It,Should,BeforeAll,BeforeEach,AfterAll,AfterEach
Use-BeTrue/-BeFalsenever-Be $true/-Be $false
Never useAssert-MockCalled, useShould -Invokeinstead
NoShould -Not -Throw- invoke commands directly
Never add an empty-MockWithblock
Omit-MockWithwhen returning$null
Set$PSDefaultParameterValuesforMock:ModuleName,Should:ModuleName,InModuleScope:ModuleName
Omit-ModuleNameparameter on Pester commands
Never useMockinsideInModuleScope-block
Never useparam()inside-MockWithscriptblock...
Files:
tests/Unit/Classes/ServerPermission.Tests.ps1tests/Unit/Classes/DatabasePermission.Tests.ps1
⚙️ CodeRabbit configuration file
**/*.[Tt]ests.ps1: # Tests GuidelinesCore Requirements
- All public commands, private functions and classes must have unit tests
- All public commands and class-based resources must have integration tests
- Use Pester v5 syntax only
- Test code only inside
Describeblocks- Assertions only in
Itblocks- Never test verbose messages, debug messages or parameter binding behavior
- Pass all mandatory parameters to avoid prompts
Requirements
- Inside
Itblocks, assign unused return objects to$null(unless part of pipeline)- Tested entity must be called from within the
Itblocks- Keep results and assertions in same
Itblock- Avoid try-catch-finally for cleanup, use
AfterAllorAfterEach- Avoid unnecessary remove/recreate cycles
Naming
- One
Describeblock per file matching the tested entity nameContextdescriptions start with 'When'Itdescriptions start with 'Should', must not contain 'when'- Mock variables prefix: 'mock'
Structure & Scope
- Public commands: Never use
InModuleScope(unless retrieving localized strings or creating an object using an internal class)- Private functions/class resources: Always use
InModuleScope- Each class method = separate
Contextblock- Each scenario = separate
Contextblock- Use nested
Contextblocks for complex scenarios- Mocking in
BeforeAll(BeforeEachonly when required)- Setup/teardown in
BeforeAll,BeforeEach/AfterAll,AfterEachclose to usage- Spacing between blocks, arrange, act, and assert for readability
Syntax Rules
- PascalCase:
Describe,Context,It,Should,BeforeAll,BeforeEach,AfterAll,AfterEach- Use
-BeTrue/-BeFalsenever-Be $true/-Be $false- Never use
Assert-MockCalled, useShould -Invokeinstead- No
Should -Not -Throw- invoke commands directly- Never add an empty
-MockWithblock- Omit
-MockWithwhen returning$null- Set
$PSDefaultParameterValuesforMock:ModuleName,Should:ModuleName, `...
Files:
tests/Unit/Classes/ServerPermission.Tests.ps1tests/Unit/Classes/DatabasePermission.Tests.ps1
tests/Unit/Classes/*.[Tt]ests.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-pester.instructions.md)
Class resources:
tests/Unit/Classes/{Name}.Tests.ps1
Files:
tests/Unit/Classes/ServerPermission.Tests.ps1tests/Unit/Classes/DatabasePermission.Tests.ps1
tests/Unit/**/*.Tests.ps1
📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines.instructions.md)
Unit tests should be located in
tests/Unit/{Classes|Public|Private}/{Name}.Tests.ps1
Files:
tests/Unit/Classes/ServerPermission.Tests.ps1tests/Unit/Classes/DatabasePermission.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: Test with localized strings usingInModuleScope -ScriptBlock { $script:localizedData.Key }in Pester unit tests
Mock files using the$TestDrivevariable (path to the test drive) in Pester unit tests
All public commands require parameter set validation tests in unit tests
Use the exact Pester test setup block withBeforeDiscovery,BeforeAll, andAfterAllblocks beforeDescribein unit tests, includingDscResource.Testmodule import and PSDefaultParameterValues configuration
Use parameter set validation test template withGet-CommandandParameterSetsproperty, supporting both single and multiple parameter sets via-ForEacharray in Pester unit tests
Use parameter properties test template withGet-Commandto validate individual parameter attributes (e.g., Mandatory flag) in Pester unit tests
Files:
tests/Unit/Classes/ServerPermission.Tests.ps1tests/Unit/Classes/DatabasePermission.Tests.ps1
⚙️ CodeRabbit configuration file
tests/[Uu]nit/**/*.[Tt]ests.ps1: # Unit Tests Guidelines
- Test with localized strings: Use
InModuleScope -ScriptBlock { $script:localizedData.Key }- Mock files: Use
$TestDrivevariable (path to the test drive)- All public commands require parameter set validation tests
- After modifying classes, always run tests in new session (for changes to take effect)
Test Setup Requirements
Use this exact setup block before
Describe:[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification = 'Suppressing this rule because Script Analyzer does not understand Pester syntax.')] param () BeforeDiscovery { try { if (-not (Get-Module -Name 'DscResource.Test')) { # Assumes dependencies have been resolved, so if this module is not available, run 'noop' task. if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) { # Redirect all streams to $null, except the error stream (stream 2) & "$PSScriptRoot/../../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null } # If the dependencies have not been resolved, this will throw an error. Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' } } catch [System.IO.FileNotFoundException] { throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks noop" first.' } } BeforeAll { $script:moduleName = '{MyModuleName}' Import-Module -Name $script:moduleName -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:ModuleName') ...
Files:
tests/Unit/Classes/ServerPermission.Tests.ps1tests/Unit/Classes/DatabasePermission.Tests.ps1
**/tests/Unit/**/*.ps1
📄 CodeRabbit inference engine (.github/instructions/SqlServerDsc-guidelines.instructions.md)
**/tests/Unit/**/*.ps1: Unit tests must use SMO stub types from SMO.cs, never mock SMO types
Unit tests must add$env:SqlServerDscCI = $trueinBeforeAllblock and remove inAfterAllblock
Load SMO stub types from SMO.cs in unit test files usingAdd-Type -Path "$PSScriptRoot/../Stubs/SMO.cs"
Files:
tests/Unit/Classes/ServerPermission.Tests.ps1tests/Unit/Classes/DatabasePermission.Tests.ps1
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 in CHANGELOG.md
Describe notable changes briefly in CHANGELOG.md, ≤2 items per change type
Reference issues using format issue #<issue_number> in CHANGELOG.md
No empty lines between list items in same section of CHANGELOG.md
Skip adding entry if same change already exists in Unreleased section of CHANGELOG.md
No duplicate sections or items in Unreleased section of CHANGELOG.mdAlways update 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
- Skip adding entry if same change already exists in Unreleased section
- No duplicate sections or items in Unreleased section
Files:
CHANGELOG.md
**/*.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 files
Use '1.' for all items in ordered lists (1/1/1 numbering style)
DisableMD013rule 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
Format parameters using bold in Markdown documentation
Format values and literals usinginline codein Markdown documentation
Format resource/module/product names using italic in Markdown documentation
Format commands/files/paths usinginline codein Markdown documentation
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
MD013rule by adding a comment for tables/code blocks exceeding 80 characters- Empty lines required before/after code blocks and headings (except before line 1)
- Escape backslashes in file paths only (not in code blocks)
- Code blocks must specify language identifiers
Text Formatting
- Parameters: bold
- Values/literals:
inline code- Resource/module/product names: italic
- Commands/files/paths:
inline code
Files:
CHANGELOG.md
🧠 Learnings (27)
📓 Common learnings
Learnt from: johlju
Repo: dsccommunity/SqlServerDsc PR: 2136
File: source/Public/Remove-SqlDscLogin.ps1:104-108
Timestamp: 2025-08-17T10:13:30.079Z
Learning: In SqlServerDsc unit tests, SMO object stubs (like Login objects) should have properly mocked Parent properties with correct Server stub types and valid InstanceName values, rather than handling null Parent scenarios in production code.
📚 Learning: 2026-01-01T11:57:15.286Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2026-01-01T11:57:15.286Z
Learning: Applies to **/tests/Unit/**/*.ps1 : Unit tests must add `$env:SqlServerDscCI = $true` in `BeforeAll` block and remove in `AfterAll` block
Applied to files:
tests/Unit/Classes/ServerPermission.Tests.ps1tests/Unit/Classes/DatabasePermission.Tests.ps1
📚 Learning: 2025-11-27T17:59:27.205Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-11-27T17:59:27.205Z
Learning: Applies to tests/Unit/Public/*.[Tt]ests.ps1 : Public commands: `tests/Unit/Public/{Name}.Tests.ps1`
Applied to files:
tests/Unit/Classes/ServerPermission.Tests.ps1tests/Unit/Classes/DatabasePermission.Tests.ps1
📚 Learning: 2025-08-17T10:13:30.079Z
Learnt from: johlju
Repo: dsccommunity/SqlServerDsc PR: 2136
File: source/Public/Remove-SqlDscLogin.ps1:104-108
Timestamp: 2025-08-17T10:13:30.079Z
Learning: In SqlServerDsc unit tests, SMO object stubs (like Login objects) should have properly mocked Parent properties with correct Server stub types and valid InstanceName values, rather than handling null Parent scenarios in production code.
Applied to files:
tests/Unit/Classes/ServerPermission.Tests.ps1tests/Unit/Classes/DatabasePermission.Tests.ps1
📚 Learning: 2025-11-27T17:59:27.205Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-11-27T17:59:27.205Z
Learning: Applies to tests/Unit/Private/*.[Tt]ests.ps1 : Private functions: `tests/Unit/Private/{Name}.Tests.ps1`
Applied to files:
tests/Unit/Classes/ServerPermission.Tests.ps1tests/Unit/Classes/DatabasePermission.Tests.ps1
📚 Learning: 2025-11-27T17:59:27.205Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-11-27T17:59:27.205Z
Learning: Applies to **/*.[Tt]ests.ps1 : Each class method = separate `Context` block
Applied to files:
tests/Unit/Classes/ServerPermission.Tests.ps1tests/Unit/Classes/DatabasePermission.Tests.ps1
📚 Learning: 2025-12-30T15:15:25.261Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-integration-tests.instructions.md:0-0
Timestamp: 2025-12-30T15:15:25.261Z
Learning: Applies to tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1 : Integration tests must cover all scenarios and code paths
Applied to files:
tests/Unit/Classes/ServerPermission.Tests.ps1tests/Unit/Classes/DatabasePermission.Tests.ps1
📚 Learning: 2025-11-27T17:59:27.205Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-11-27T17:59:27.205Z
Learning: Applies to **/*.[Tt]ests.ps1 : Use nested `Context` blocks for complex scenarios
Applied to files:
tests/Unit/Classes/ServerPermission.Tests.ps1tests/Unit/Classes/DatabasePermission.Tests.ps1
📚 Learning: 2025-11-27T17:59:27.205Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-11-27T17:59:27.205Z
Learning: Applies to tests/Unit/Classes/*.[Tt]ests.ps1 : Class resources: `tests/Unit/Classes/{Name}.Tests.ps1`
Applied to files:
tests/Unit/Classes/ServerPermission.Tests.ps1
📚 Learning: 2025-11-27T17:59:27.205Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-11-27T17:59:27.205Z
Learning: Applies to **/*.[Tt]ests.ps1 : Each scenario = separate `Context` block
Applied to files:
tests/Unit/Classes/ServerPermission.Tests.ps1tests/Unit/Classes/DatabasePermission.Tests.ps1
📚 Learning: 2025-11-27T17:59:27.205Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-11-27T17:59:27.205Z
Learning: Applies to **/*.[Tt]ests.ps1 : All public commands and class-based resources must have integration tests
Applied to files:
tests/Unit/Classes/ServerPermission.Tests.ps1
📚 Learning: 2025-11-27T17:59:27.205Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-11-27T17:59:27.205Z
Learning: Applies to **/*.[Tt]ests.ps1 : Never use `Mock` inside `InModuleScope`-block
Applied to files:
tests/Unit/Classes/ServerPermission.Tests.ps1tests/Unit/Classes/DatabasePermission.Tests.ps1
📚 Learning: 2025-11-27T17:59:27.205Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-11-27T17:59:27.205Z
Learning: Applies to **/*.[Tt]ests.ps1 : Set `$PSDefaultParameterValues` for `Mock:ModuleName`, `Should:ModuleName`, `InModuleScope:ModuleName`
Applied to files:
tests/Unit/Classes/ServerPermission.Tests.ps1
📚 Learning: 2025-08-17T10:15:48.194Z
Learnt from: johlju
Repo: dsccommunity/SqlServerDsc PR: 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/Unit/Classes/ServerPermission.Tests.ps1
📚 Learning: 2025-11-27T17:59:27.205Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-11-27T17:59:27.205Z
Learning: Applies to **/*.[Tt]ests.ps1 : Mock variables prefix: 'mock'
Applied to files:
tests/Unit/Classes/ServerPermission.Tests.ps1
📚 Learning: 2025-11-27T17:59:27.205Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-11-27T17:59:27.205Z
Learning: Applies to **/*.[Tt]ests.ps1 : Private functions/class resources: Always use `InModuleScope`
Applied to files:
tests/Unit/Classes/ServerPermission.Tests.ps1
📚 Learning: 2025-11-27T17:59:27.205Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-11-27T17:59:27.205Z
Learning: Applies to **/*.[Tt]ests.ps1 : Public commands: Never use `InModuleScope` (unless retrieving localized strings or creating an object using an internal class)
Applied to files:
tests/Unit/Classes/ServerPermission.Tests.ps1
📚 Learning: 2026-01-01T11:57:15.286Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2026-01-01T11:57:15.286Z
Learning: Applies to **/tests/Integration/**/*.ps1 : Integration tests must use `Disconnect-SqlDscDatabaseEngine` after `Connect-SqlDscDatabaseEngine`
Applied to files:
tests/Unit/Classes/ServerPermission.Tests.ps1tests/Unit/Classes/DatabasePermission.Tests.ps1
📚 Learning: 2025-11-27T18:00:35.078Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines.instructions.md:0-0
Timestamp: 2025-11-27T18:00:35.078Z
Learning: Follow PowerShell style and test guideline instructions strictly
Applied to files:
tests/Unit/Classes/ServerPermission.Tests.ps1tests/Unit/Classes/DatabasePermission.Tests.ps1
📚 Learning: 2026-01-01T11:57:15.286Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2026-01-01T11:57:15.286Z
Learning: Applies to **/tests/Unit/**/*.ps1 : Unit tests must use SMO stub types from SMO.cs, never mock SMO types
Applied to files:
tests/Unit/Classes/ServerPermission.Tests.ps1
📚 Learning: 2025-11-27T17:59:27.205Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-11-27T17:59:27.205Z
Learning: Applies to **/*.[Tt]ests.ps1 : Never use `Assert-MockCalled`, use `Should -Invoke` instead
Applied to files:
tests/Unit/Classes/ServerPermission.Tests.ps1tests/Unit/Classes/DatabasePermission.Tests.ps1
📚 Learning: 2025-12-30T15:15:36.079Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-unit-tests.instructions.md:0-0
Timestamp: 2025-12-30T15:15:36.079Z
Learning: Applies to tests/[Uu]nit/**/*.[Tt]ests.ps1 : Use the exact Pester test setup block with `BeforeDiscovery`, `BeforeAll`, and `AfterAll` blocks before `Describe` in unit tests, including `DscResource.Test` module import and PSDefaultParameterValues configuration
Applied to files:
tests/Unit/Classes/DatabasePermission.Tests.ps1
📚 Learning: 2025-11-27T17:59:27.205Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-11-27T17:59:27.205Z
Learning: Applies to **/*.[Tt]ests.ps1 : One `Describe` block per file matching the tested entity name
Applied to files:
tests/Unit/Classes/DatabasePermission.Tests.ps1
📚 Learning: 2025-11-27T17:59:27.205Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-11-27T17:59:27.205Z
Learning: Applies to **/*.[Tt]ests.ps1 : Omit `-MockWith` when returning `$null`
Applied to files:
tests/Unit/Classes/DatabasePermission.Tests.ps1
📚 Learning: 2025-09-25T16:38:08.867Z
Learnt from: johlju
Repo: dsccommunity/ActiveDirectoryDsc PR: 741
File: tests/Integration/MSFT_ADReadOnlyDomainControllerAccount.Integration.Tests.ps1:102-104
Timestamp: 2025-09-25T16:38:08.867Z
Learning: The PowerShell guideline "Use -BeTrue/-BeFalse; never use -Be $true/-Be $false" applies only when the actual return value is a boolean. When a cmdlet returns string values like 'True' or 'False', Should -Be 'True' is the appropriate assertion.
Applied to files:
tests/Unit/Classes/DatabasePermission.Tests.ps1
📚 Learning: 2025-11-27T17:59:27.205Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-11-27T17:59:27.205Z
Learning: Applies to **/*.[Tt]ests.ps1 : Mocking in `BeforeAll` (`BeforeEach` only when required)
Applied to files:
tests/Unit/Classes/DatabasePermission.Tests.ps1
📚 Learning: 2025-11-27T17:59:27.205Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-11-27T17:59:27.205Z
Learning: Applies to **/*.[Tt]ests.ps1 : Use `-BeTrue`/`-BeFalse` never `-Be $true`/`-Be $false`
Applied to files:
tests/Unit/Classes/DatabasePermission.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: PSScriptAnalyzer
- GitHub Check: dsccommunity.SqlServerDsc (Build Package Module)
🔇 Additional comments (10)
source/Classes/002.DatabasePermission.ps1 (1)
186-186: LGTM! Critical equality bug fixed.The fix correctly compares
Stateinstead of the non-existentGrantproperty, ensuring equality checks work as intended.source/Classes/002.ServerPermission.ps1 (1)
118-118: LGTM! Critical equality bug fixed.The fix correctly compares
Stateinstead of the non-existentGrantproperty, mirroring the fix in DatabasePermission.tests/Unit/Classes/DatabasePermission.Tests.ps1 (2)
133-191: LGTM! Test reorganization follows Pester guidelines.The nested contexts properly separate scenarios (Deny vs Grant, Grant vs GrantWithGrant) and each test clearly validates that objects with different State values are not equal.
225-279: LGTM! Comprehensive GetHashCode() test coverage.The tests thoroughly validate GetHashCode() behavior:
- Equal objects produce identical hash codes (including order-independent Permission arrays)
- Different State produces different hash codes
- Different Permission produces different hash codes
The implementation correctly uses nested contexts and InModuleScope following Pester guidelines.
tests/Unit/Classes/ServerPermission.Tests.ps1 (6)
74-79: LGTM!Variable renaming from
$databasePermissionInstanceto$serverPermissionInstancecorrectly reflects the class under test.
96-127: LGTM!Consistent variable renaming in equality tests for both single and multiple permission scenarios.
133-191: Well-structured tests for the core bug fix.These new test contexts properly validate that
Equals()now correctly compares theStateproperty, ensuring instances withDenyvsGrantandGrantvsGrantWithGrantare not considered equal.
199-220: LGTM!Variable renaming applied consistently in the Permission comparison tests.
225-279: Comprehensive GetHashCode() coverage.The tests correctly verify:
- Equal objects produce identical hash codes (including permission order independence via sorted normalization at lines 233/237)
- Different
Statevalues produce different hash codes- Different
Permissionvalues produce different hash codesNote: While hash collisions are technically permitted by the
GetHashCode()contract, testing for inequality on clearly different inputs is reasonable for validating a well-implemented hash function.
31-51: Test setup follows all required conventions.Proper configuration of
$env:SqlServerDscCI, module import without-Force(preserving type identity for class comparisons), and correctPSDefaultParameterValuessetup per coding guidelines.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #2392 +/- ##
=====================================
Coverage 94% 94%
=====================================
Files 186 186
Lines 10238 10248 +10
=====================================
+ Hits 9633 9643 +10
Misses 605 605
🚀 New features to boost your workflow:
|
- Removed TODO comment from ServerPermission.GetHashCode() as requested - Simplified GetHashCode() initialization in both classes to directly assign State hash code - Changed from initializing to 0 then assigning to direct assignment - All 64 unit tests pass Co-authored-by: johlju <[email protected]>
|
@coderabbitai review |
✅ Actions performedReview triggered.
|
Fix DatabasePermission.Equals() to compare both State and Permission properties
Summary
Fixed a bug where
DatabasePermission.Equals()andServerPermission.Equals()only compared thePermissionproperty and ignored theStateproperty. The methods incorrectly referenced a non-existentGrantproperty instead of the correctStateproperty.Changes Made
Test Results
Fixes
Resolves issue #2386
Original prompt
✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.
This change is