Skip to content

Get-SqlDscServerPermission: Check for both login and role#2131

Merged
johlju merged 43 commits intodsccommunity:mainfrom
johlju:fix/get-sqldscserverpermission
Sep 5, 2025
Merged

Get-SqlDscServerPermission: Check for both login and role#2131
johlju merged 43 commits intodsccommunity:mainfrom
johlju:fix/get-sqldscserverpermission

Conversation

@johlju
Copy link
Member

@johlju johlju commented Aug 12, 2025

Pull Request (PR) description

  • Get-SqlDscServerPermission
    • Enhanced the command to support server roles in addition to logins by utilizing
      Test-SqlDscIsRole alongside the existing Test-SqlDscIsLogin check.
    • The function now accepts both login principals and server role principals
      as the Name parameter.

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 12, 2025 11:11
@coderabbitai
Copy link

coderabbitai bot commented Aug 12, 2025

Note

Other AI code review bot(s) detected

CodeRabbit 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.

Walkthrough

Get-SqlDscServerPermission now accepts server-role principals and pipeline Login/ServerRole objects, adds a -PrincipalType filter and new parameter sets (ByName/Login/ServerRole). Tests, changelog, localization, and server-permission cmdlet error handling were updated; many integration test harnesses were adjusted.

Changes

Cohort / File(s) Summary
Cmdlet logic & public API
source/Public/Get-SqlDscServerPermission.ps1
Adds -PrincipalType ([string[]] 'Login'
Unit tests — Get-SqlDscServerPermission
tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1
Adds Test-SqlDscIsRole mocks, server-role contexts, pipeline-object paths, expanded PrincipalType permutations, and detailed verification of test-call counts and parameters.
Integration tests & harness
tests/Integration/Commands/Get-SqlDscServerPermission.Integration.Tests.ps1, many tests/Integration/Commands/*.Integration.Tests.ps1, azure-pipelines.yml, tests/Integration/Commands/README.md
New integration tests for logins and server roles, PrincipalType and pipeline/parameter-set consistency. Widespread harness changes: rename $script:dscModuleName$script:moduleName, add Import-Module -Force -ErrorAction 'Stop', drop Integration_SQL2016 tag, adjust service start/stop, convert permission enum tokens to quoted strings, and remove module unload AfterAlls.
Error reporting & localization
source/Public/Grant-SqlDscServerPermission.ps1, source/Public/Deny-SqlDscServerPermission.ps1, source/Public/Revoke-SqlDscServerPermission.ps1, source/en-US/SqlServerDsc.strings.psd1
Removed unused permission-name enumeration, updated catch blocks to include requested-permissions list, construct exceptions preserving inner exceptions, raise ErrorRecord with exception, and updated localized messages to include permissions placeholder; added test-related strings.
Test helpers & docs
source/Public/Test-SqlDscServerPermission.ps1, source/Public/Test-SqlDscIsRole.ps1, CHANGELOG.md
Added Write-Debug messages for current/no permissions, updated Test-SqlDscIsRole wording to server principal/server role, expanded changelog and examples.
Other tests & minor updates
tests/Unit/Public/Revoke-SqlDscServerPermission.Tests.ps1, many tests/Integration/Commands/*
Convert permission tokens to quoted strings in tests, adjust parameter-set and pipeline tests, and widespread test scaffold renames/bootstrapping.
Dependency pinning
RequiredModules.psd1
Pins DscResource.Test from latest to 0.17.2.

Sequence Diagram(s)

sequenceDiagram
  participant Caller
  participant Cmdlet as Get-SqlDscServerPermission
  participant LoginCheck as Test-SqlDscIsLogin
  participant RoleCheck as Test-SqlDscIsRole
  participant SMO as SMO Server

  Note over Cmdlet: Determine ParameterSet (ByName / Login / ServerRole) and PrincipalType flags
  Caller->>Cmdlet: Invoke(Name or -Login/-ServerRole, -PrincipalType?, -ServerObject)
  alt ParameterSet = Login
    Cmdlet->>LoginCheck: Test-SqlDscIsLogin(ServerObject, principalName)
  else ParameterSet = ServerRole
    Cmdlet->>RoleCheck: Test-SqlDscIsRole(ServerObject, principalName)
  else ParameterSet = ByName
    alt PrincipalType includes Login
      Cmdlet->>LoginCheck: Test-SqlDscIsLogin(ServerObject, principalName)
    end
    alt PrincipalType includes Role
      Cmdlet->>RoleCheck: Test-SqlDscIsRole(ServerObject, principalName)
    end
  end
  alt Principal confirmed
    Cmdlet->>SMO: EnumServerPermissions(principalName, ServerObject)
    SMO-->>Cmdlet: ServerPermissionInfo[]
    Cmdlet-->>Caller: Return permissions
  else Neither confirmed
    Cmdlet-->>Caller: Throw "principal is not a login nor role" error
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Assessment against linked issues

Objective Addressed Explanation
Return permissions for a server role (#2063)

Out-of-scope changes

Code Change Explanation
CI test ordering/formatting (azure-pipelines.yml) Formatting change only; unrelated to server-role permission retrieval.
Test harness imports & tagging (tests/Integration/Commands/*.Integration.Tests.ps1) Renaming $script:dscModuleName$script:moduleName, adding Import-Module -Force -ErrorAction 'Stop', removing Integration_SQL2016 and AfterAll unloads are scaffolding adjustments not required by #2063.
Permission literal conversions in tests (tests/Integration/..., tests/Unit/...) Switching enum tokens to quoted strings affects tests only and is not necessary for server-role detection/permission retrieval.

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 b56bca4 and 59a8983.

📒 Files selected for processing (2)
  • azure-pipelines.yml (0 hunks)
  • tests/Unit/Public/Revoke-SqlDscServerPermission.Tests.ps1 (6 hunks)
💤 Files with no reviewable changes (1)
  • azure-pipelines.yml
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/Unit/Public/Revoke-SqlDscServerPermission.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). (4)
  • GitHub Check: dsccommunity.SqlServerDsc (Quality Test and Unit Test Unit)
  • GitHub Check: dsccommunity.SqlServerDsc (Quality Test and Unit Test Determine DSC Resource Test Requirements)
  • GitHub Check: dsccommunity.SqlServerDsc (Quality Test and Unit Test HQRM)
  • GitHub Check: dsccommunity.SqlServerDsc (Build Package Module)
✨ 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: 3

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 14c5107 and a81e9f5.

📒 Files selected for processing (3)
  • CHANGELOG.md (1 hunks)
  • source/Public/Get-SqlDscServerPermission.ps1 (1 hunks)
  • tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1 (4 hunks)
🧰 Additional context used
📓 Path-based instructions (10)
source/Public/*.ps1

📄 CodeRabbit Inference Engine (.github/copilot-instructions.md)

source/Public/*.ps1: Public PowerShell commands should each have their own script file named after the command (with .ps1 extension) and be placed in the folder source/Public.
All public command names must have the noun prefixed with 'SqlDsc', e.g. {Verb}-SqlDsc{Noun}.

Files:

  • source/Public/Get-SqlDscServerPermission.ps1
source/{Public,Private,Classes}/*.ps1

📄 CodeRabbit Inference Engine (.github/copilot-instructions.md)

source/{Public,Private,Classes}/*.ps1: Comment-based help should always be before the function-statement for each public command and private function, and before the class-statement for each class-based resource. It should be in the format of a comment block and at least use the keywords: .SYNOPSIS, .DESCRIPTION, .PARAMETER, .EXAMPLE, and .NOTES.
Each comment-based help keyword should be indented with 4 spaces and each keyword's text should be indented 8 spaces.
The text for keyword .DESCRIPTION should be descriptive and must have a length greater than 40 characters. The .SYNOPSIS keyword text should be a short description.
A comment-based help must have at least one example, but preferably more examples to showcase all possible parameter sets and different parameter combinations.
Use PascalCase for function names and parameters in public commands, private functions, and class-based resources.

Files:

  • source/Public/Get-SqlDscServerPermission.ps1
source/{Public,Private}/*.ps1

📄 CodeRabbit Inference Engine (.github/copilot-instructions.md)

source/{Public,Private}/*.ps1: All message strings for Write-Debug, Write-Verbose, Write-Error, Write-Warning and other error messages in public commands and private functions should be localized using localized string keys.
All public command and private function names must follow the standard PowerShell Verb-Noun format.
All public command and private function names must use PowerShell approved verbs.
All public commands and private functions should always be advanced functions and have [CmdLetBinding()] attribute.
Public commands and private functions with no parameters should still have an empty parameter block param ().
Every parameter in public commands and private functions should include the [Parameter()] attribute.
A mandatory parameter in public commands and private functions should contain the decoration [Parameter(Mandatory = $true)], and non-mandatory parameters should not contain the Mandatory decoration.
Parameters attributes, datatype and its name should be on separate lines.
Parameters must be separated by a single, blank line.
Use Write-Verbose to output verbose output for actions a public command or private function does.
Use Write-Debug for debug output for processes within the script for user to see the decisions a command or private function does.

Files:

  • source/Public/Get-SqlDscServerPermission.ps1
**/*.ps1

📄 CodeRabbit Inference Engine (.github/copilot-instructions.md)

**/*.ps1: All PowerShell files should use UTF8 without BOM.
All PowerShell files must end with a new line.
Try to limit PowerShell code lines to 120 characters.
Use 4 spaces for indentation in PowerShell files, never use tabs.
Use '#' for single line comments in PowerShell code.
Use comment-blocks for multiline comments with the format <# ... #> where the multiline text is indented 4 spaces.
Use descriptive, clear, and full names for all variables, parameters, and function names. All names must be more than 2 characters. No abbreviations should be used.
Use camelCase for local variable names in PowerShell.
Use Write-Error for error messages.
Use Write-Warning for warning messages.
Use Write-Information for informational messages.
Never use Write-Host.
Never use backtick as line continuation in code.
Use splatting for commands to reduce line length.
PowerShell reserved keywords should be in all lower case.
Single quotes should always be used to delimit string literals wherever possible. Double quoted string literals may only be used when string literals contain ($) expressions that need to be evaluated.
Hashtables properties should always be in PascalCase and be on a separate line.
When comparing a value to $null, $null should be on the left side of the comparison.

Files:

  • source/Public/Get-SqlDscServerPermission.ps1
  • tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1
CHANGELOG.md

📄 CodeRabbit Inference Engine (.github/copilot-instructions.md)

The Unreleased section in CHANGELOG.md should always be updated when making changes to the codebase, using the keepachangelog format and providing concrete release notes.

Files:

  • CHANGELOG.md
**/*.md

📄 CodeRabbit Inference Engine (.github/copilot-instructions.md)

**/*.md: Markdown files should wrap lines after a word when a line exceeds 80 characters.
Use 2 spaces for indentation in Markdown files.

Files:

  • CHANGELOG.md
tests/**/*.ps1

📄 CodeRabbit Inference Engine (.github/copilot-instructions.md)

tests/**/*.ps1: All tests should use the Pester framework and use Pester v5.0 syntax.
Parameter validation should never be tested.
Test code should never be added outside of the Describe block.
There should only be one Pester Describe block per test file, and the name of the Describe block should be the same as the name of the public command, private function, or class-based resource being tested.
Each scenario or code path being tested should have its own Pester Context block that starts with the phrase 'When'.
Pester It block descriptions should start with the phrase 'Should'.
It blocks must always call the command or function being tested and result and outcomes should be kept in the same It block.
BeforeAll and BeforeEach blocks should never call the command or function being tested.
BeforeAll, BeforeEach, AfterAll and AfterEach blocks should be used inside the Context block as near as possible to the It block that will use the test data, test setup and teardown.
AfterAll block can be used to clean up any test data.
BeforeEach and AfterEach blocks should be used sparingly.
It is okay to duplicate code in BeforeAll and BeforeEach blocks that are used inside different Context blocks.
Use localized strings in the tests only when necessary.
Files that need to be mocked should be created in Pester's test drive using the $TestDrive variable.

Files:

  • tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1
tests/Unit/{Classes,Public,Private}/*.Tests.ps1

📄 CodeRabbit Inference Engine (.github/copilot-instructions.md)

Unit tests should be added for all public commands, private functions and class-based resources. Unit tests for class-based resources should be placed in tests/Unit/Classes, for public commands in tests/Unit/Public, and for private functions in tests/Unit/Private. The unit tests should be named after the item being tested with the suffix .Tests.ps1.

Files:

  • tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1
tests/Unit/Public/*.Tests.ps1

📄 CodeRabbit Inference Engine (.github/copilot-instructions.md)

tests/Unit/Public/*.Tests.ps1: All public commands should always have a test to validate parameter sets using the provided template.
All public commands should also include tests to validate parameter properties.

Files:

  • tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1
tests/Unit/**/*.ps1

📄 CodeRabbit Inference Engine (.github/copilot-instructions.md)

tests/Unit/**/*.ps1: Never test, mock or use Should -Invoke for Write-Verbose and Write-Debug.
Never use Should -Not -Throw in tests; instead, call the command directly.
All unit tests should use the provided code block prior to the Describe block to set up the test environment and load the correct module.

Files:

  • tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1
🧠 Learnings (5)
📚 Learning: 2025-08-03T09:50:27.001Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-03T09:50:27.001Z
Learning: Applies to tests/Unit/**/*.ps1 : Never use Should -Not -Throw in tests; instead, call the command directly.

Applied to files:

  • tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1
📚 Learning: 2025-08-03T09:50:27.001Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-03T09:50:27.001Z
Learning: Applies to tests/Unit/**/*.ps1 : Never test, mock or use Should -Invoke for Write-Verbose and Write-Debug.

Applied to files:

  • tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1
📚 Learning: 2025-08-03T09:50:27.001Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-03T09:50:27.001Z
Learning: Applies to tests/**/*.ps1 : Files that need to be mocked should be created in Pester's test drive using the $TestDrive variable.

Applied to files:

  • tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1
📚 Learning: 2025-08-03T09:50:27.001Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-03T09:50:27.001Z
Learning: Applies to tests/**/*.ps1 : It blocks must always call the command or function being tested and result and outcomes should be kept in the same It block.

Applied to files:

  • tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1
📚 Learning: 2025-08-03T09:50:27.001Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-03T09:50:27.001Z
Learning: Applies to tests/**/*.ps1 : BeforeAll and BeforeEach blocks should never call the command or function being tested.

Applied to files:

  • tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1
🧬 Code Graph Analysis (1)
CHANGELOG.md (1)
tests/Unit/Stubs/SMO.cs (1)
  • ServerPermissionSet (183-205)
⏰ 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 (Quality Test and Unit Test HQRM)
  • GitHub Check: dsccommunity.SqlServerDsc (Quality Test and Unit Test Unit)
  • GitHub Check: dsccommunity.SqlServerDsc (Build Package Module)
🔇 Additional comments (5)
source/Public/Get-SqlDscServerPermission.ps1 (1)

53-61: Role support integrated correctly (login OR role).

Shared parameter splatting, role detection via Test-SqlDscIsRole, and the broadened predicate if ($isLogin -or $isRole) are spot on for enabling server role principals.

tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1 (4)

62-64: Missing-principal path correctly considers both login and role checks.

Mocking Test-SqlDscIsRole to $false alongside Test-SqlDscIsLogin keeps the negative path faithful to the new logic.


88-156: Login scenario tests are clear and robust.

Isolating the login path by mocking the role check to $false and asserting the two-permission shape looks good.


158-226: New server-role scenario is well covered (including pipeline input).

Good use of the SMO stubs to model ViewServerState and ControlServer permissions and validate both direct and pipeline invocation.


257-297: Parameter metadata validation remains correct and aligns with guidelines.

Confirms mandatory parameters and pipeline input, matching the public API.

@codecov
Copy link

codecov bot commented Aug 12, 2025

Codecov Report

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

Additional details and impacted files

Impacted file tree graph

@@         Coverage Diff          @@
##           main   #2131   +/-   ##
====================================
  Coverage    94%     94%           
====================================
  Files       131     131           
  Lines      8686    8701   +15     
====================================
+ Hits       8230    8245   +15     
  Misses      456     456           
Flag Coverage Δ
unit 94% <100%> (+<1%) ⬆️
Files with missing lines Coverage Δ
source/Public/Deny-SqlDscServerPermission.ps1 100% <100%> (ø)
source/Public/Get-SqlDscServerPermission.ps1 100% <100%> (ø)
source/Public/Grant-SqlDscServerPermission.ps1 100% <100%> (ø)
source/Public/Revoke-SqlDscServerPermission.ps1 100% <100%> (ø)
source/Public/Test-SqlDscIsRole.ps1 100% <ø> (ø)
source/Public/Test-SqlDscServerPermission.ps1 94% <100%> (+<1%) ⬆️
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@johlju
Copy link
Member Author

johlju commented Aug 12, 2025

@copilot can you add integration tests for the command Get-SqlDscServerPermission. Test for both a valid and invalid sql login and server role. Use existing logins and server roles, e.g. SQL login SqlAdmin which should have sysadmin role: https://github.com/dsccommunity/SqlServerDsc/blob/main/tests/Integration/Commands/README.md

@johlju johlju requested a review from Copilot August 12, 2025 15:49

This comment was marked as outdated.

@johlju
Copy link
Member Author

johlju commented Aug 12, 2025

@copilot can you add integration tests for the command Get-SqlDscServerPermission. Test for both a valid and invalid sql login and server role. Use existing logins and server roles, e.g. SQL login SqlAdmin which should have sysadmin role: https://github.com/dsccommunity/SqlServerDsc/blob/main/tests/Integration/Commands/README.md

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

♻️ Duplicate comments (3)
CHANGELOG.md (1)

21-25: Server-role support is clearly documented; issue link included.

The entry accurately captures the enhancement and now links to the tracked issue, which addresses prior feedback.

source/Public/Get-SqlDscServerPermission.ps1 (2)

6-8: Help: DESCRIPTION explicitly lists logins and server roles.

Accurately reflects the new capability and aligns with style guidance.


26-31: Help: Added example for server-role ('sysadmin') usage.

Concrete example is helpful and follows existing patterns.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a81e9f5 and 38082f7.

📒 Files selected for processing (2)
  • CHANGELOG.md (1 hunks)
  • source/Public/Get-SqlDscServerPermission.ps1 (3 hunks)
🧰 Additional context used
📓 Path-based instructions (6)
source/Public/*.ps1

📄 CodeRabbit Inference Engine (.github/copilot-instructions.md)

source/Public/*.ps1: Public PowerShell commands should each have their own script file named after the command (with .ps1 extension) and be placed in the folder source/Public.
All public command names must have the noun prefixed with 'SqlDsc', e.g. {Verb}-SqlDsc{Noun}.

Files:

  • source/Public/Get-SqlDscServerPermission.ps1
source/{Public,Private,Classes}/*.ps1

📄 CodeRabbit Inference Engine (.github/copilot-instructions.md)

source/{Public,Private,Classes}/*.ps1: Comment-based help should always be before the function-statement for each public command and private function, and before the class-statement for each class-based resource. It should be in the format of a comment block and at least use the keywords: .SYNOPSIS, .DESCRIPTION, .PARAMETER, .EXAMPLE, and .NOTES.
Each comment-based help keyword should be indented with 4 spaces and each keyword's text should be indented 8 spaces.
The text for keyword .DESCRIPTION should be descriptive and must have a length greater than 40 characters. The .SYNOPSIS keyword text should be a short description.
A comment-based help must have at least one example, but preferably more examples to showcase all possible parameter sets and different parameter combinations.
Use PascalCase for function names and parameters in public commands, private functions, and class-based resources.

Files:

  • source/Public/Get-SqlDscServerPermission.ps1
source/{Public,Private}/*.ps1

📄 CodeRabbit Inference Engine (.github/copilot-instructions.md)

source/{Public,Private}/*.ps1: All message strings for Write-Debug, Write-Verbose, Write-Error, Write-Warning and other error messages in public commands and private functions should be localized using localized string keys.
All public command and private function names must follow the standard PowerShell Verb-Noun format.
All public command and private function names must use PowerShell approved verbs.
All public commands and private functions should always be advanced functions and have [CmdLetBinding()] attribute.
Public commands and private functions with no parameters should still have an empty parameter block param ().
Every parameter in public commands and private functions should include the [Parameter()] attribute.
A mandatory parameter in public commands and private functions should contain the decoration [Parameter(Mandatory = $true)], and non-mandatory parameters should not contain the Mandatory decoration.
Parameters attributes, datatype and its name should be on separate lines.
Parameters must be separated by a single, blank line.
Use Write-Verbose to output verbose output for actions a public command or private function does.
Use Write-Debug for debug output for processes within the script for user to see the decisions a command or private function does.

Files:

  • source/Public/Get-SqlDscServerPermission.ps1
**/*.ps1

📄 CodeRabbit Inference Engine (.github/copilot-instructions.md)

**/*.ps1: All PowerShell files should use UTF8 without BOM.
All PowerShell files must end with a new line.
Try to limit PowerShell code lines to 120 characters.
Use 4 spaces for indentation in PowerShell files, never use tabs.
Use '#' for single line comments in PowerShell code.
Use comment-blocks for multiline comments with the format <# ... #> where the multiline text is indented 4 spaces.
Use descriptive, clear, and full names for all variables, parameters, and function names. All names must be more than 2 characters. No abbreviations should be used.
Use camelCase for local variable names in PowerShell.
Use Write-Error for error messages.
Use Write-Warning for warning messages.
Use Write-Information for informational messages.
Never use Write-Host.
Never use backtick as line continuation in code.
Use splatting for commands to reduce line length.
PowerShell reserved keywords should be in all lower case.
Single quotes should always be used to delimit string literals wherever possible. Double quoted string literals may only be used when string literals contain ($) expressions that need to be evaluated.
Hashtables properties should always be in PascalCase and be on a separate line.
When comparing a value to $null, $null should be on the left side of the comparison.

Files:

  • source/Public/Get-SqlDscServerPermission.ps1
CHANGELOG.md

📄 CodeRabbit Inference Engine (.github/copilot-instructions.md)

The Unreleased section in CHANGELOG.md should always be updated when making changes to the codebase, using the keepachangelog format and providing concrete release notes.

Files:

  • CHANGELOG.md
**/*.md

📄 CodeRabbit Inference Engine (.github/copilot-instructions.md)

**/*.md: Markdown files should wrap lines after a word when a line exceeds 80 characters.
Use 2 spaces for indentation in Markdown files.

Files:

  • CHANGELOG.md
🧬 Code Graph Analysis (1)
CHANGELOG.md (1)
tests/Unit/Stubs/SMO.cs (1)
  • ServerPermissionSet (183-205)
⏰ 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
🔇 Additional comments (4)
CHANGELOG.md (1)

26-29: AI summary inconsistency: azure-pipelines.yml change is present, not removed.

The AI-generated summary says the azure-pipelines.yml entry was removed from Changed, but Lines 26–29 show it remains. Treat the code as source of truth.

source/Public/Get-SqlDscServerPermission.ps1 (3)

3-3: Help: SYNOPSIS correctly advertises login and server-role support.

Good clarity for the broadened behavior.


14-15: Help: Name parameter description updated to include server roles.

Consistent with the functional change.


61-64: Good reuse: unified splat for principal checks.

The shared parameter splat improves readability and reduces duplication.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

♻️ Duplicate comments (2)
CHANGELOG.md (1)

21-26: Minor: Adjust line breaks for 80-character limit.

Some lines exceed 80 characters. Reformat to comply with Markdown style guidelines.

Apply this diff to wrap long lines:

 - `Get-SqlDscServerPermission`
-  - Enhanced the command to support server roles in addition to logins by
-    utilizing `Test-SqlDscIsRole` alongside the existing `Test-SqlDscIsLogin`
-    check.
-  - The function now accepts both login principals and server role principals
-    as the `Name` parameter (issue [#2063](https://github.com/dsccommunity/SqlServerDsc/issues/2063)).
+  - Enhanced the command to support server roles in addition to logins
+    by utilizing `Test-SqlDscIsRole` alongside the existing
+    `Test-SqlDscIsLogin` check.
+  - The function now accepts both login principals and server role
+    principals as the `Name` parameter (issue
+    [#2063](https://github.com/dsccommunity/SqlServerDsc/issues/2063)).
tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1 (1)

228-347: Verify the function call verification logic addresses the optimization concern.

The current test implementation asserts exact invocation counts for both Test-SqlDscIsLogin and Test-SqlDscIsRole across different scenarios. Based on the past review comment, this approach may block future micro-optimizations like short-circuiting the role check when the login check succeeds.

However, reviewing the test scenarios more carefully, I notice the implementation actually does handle this correctly:

  • When login is found (lines 247-255): Only Test-SqlDscIsLogin is called, Test-SqlDscIsRole is called 0 times
  • When login is not found (lines 269-279): Both functions are called
  • When PrincipalType is specified: Only the relevant function is called

This suggests the implementation already includes the short-circuit optimization, and the tests properly validate this behavior.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 38082f7 and 8ff42a2.

📒 Files selected for processing (6)
  • CHANGELOG.md (1 hunks)
  • azure-pipelines.yml (1 hunks)
  • source/Public/Get-SqlDscServerPermission.ps1 (3 hunks)
  • tests/Integration/Commands/Assert-SqlDscLogin.Integration.Tests.ps1 (1 hunks)
  • tests/Integration/Commands/Get-SqlDscServerPermission.Integration.Tests.ps1 (1 hunks)
  • tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1 (4 hunks)
🧰 Additional context used
📓 Path-based instructions (12)
tests/**/*.ps1

📄 CodeRabbit Inference Engine (.github/copilot-instructions.md)

tests/**/*.ps1: All tests should use the Pester framework and use Pester v5.0 syntax.
Parameter validation should never be tested.
Test code should never be added outside of the Describe block.
There should only be one Pester Describe block per test file, and the name of the Describe block should be the same as the name of the public command, private function, or class-based resource being tested.
Each scenario or code path being tested should have its own Pester Context block that starts with the phrase 'When'.
Pester It block descriptions should start with the phrase 'Should'.
It blocks must always call the command or function being tested and result and outcomes should be kept in the same It block.
BeforeAll and BeforeEach blocks should never call the command or function being tested.
BeforeAll, BeforeEach, AfterAll and AfterEach blocks should be used inside the Context block as near as possible to the It block that will use the test data, test setup and teardown.
AfterAll block can be used to clean up any test data.
BeforeEach and AfterEach blocks should be used sparingly.
It is okay to duplicate code in BeforeAll and BeforeEach blocks that are used inside different Context blocks.
Use localized strings in the tests only when necessary.
Files that need to be mocked should be created in Pester's test drive using the $TestDrive variable.

Files:

  • tests/Integration/Commands/Assert-SqlDscLogin.Integration.Tests.ps1
  • tests/Integration/Commands/Get-SqlDscServerPermission.Integration.Tests.ps1
  • tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1
tests/Integration/Commands/*.Integration.Tests.ps1

📄 CodeRabbit Inference Engine (.github/copilot-instructions.md)

tests/Integration/Commands/*.Integration.Tests.ps1: Integration tests for public commands should be placed in tests/Integration/Commands and named after the command with the suffix .Integration.Tests.ps1.
All integration tests must use the provided code block prior to the first Describe block to set up the integration test environment.

Files:

  • tests/Integration/Commands/Assert-SqlDscLogin.Integration.Tests.ps1
  • tests/Integration/Commands/Get-SqlDscServerPermission.Integration.Tests.ps1
**/*.ps1

📄 CodeRabbit Inference Engine (.github/copilot-instructions.md)

**/*.ps1: All PowerShell files should use UTF8 without BOM.
All PowerShell files must end with a new line.
Try to limit PowerShell code lines to 120 characters.
Use 4 spaces for indentation in PowerShell files, never use tabs.
Use '#' for single line comments in PowerShell code.
Use comment-blocks for multiline comments with the format <# ... #> where the multiline text is indented 4 spaces.
Use descriptive, clear, and full names for all variables, parameters, and function names. All names must be more than 2 characters. No abbreviations should be used.
Use camelCase for local variable names in PowerShell.
Use Write-Error for error messages.
Use Write-Warning for warning messages.
Use Write-Information for informational messages.
Never use Write-Host.
Never use backtick as line continuation in code.
Use splatting for commands to reduce line length.
PowerShell reserved keywords should be in all lower case.
Single quotes should always be used to delimit string literals wherever possible. Double quoted string literals may only be used when string literals contain ($) expressions that need to be evaluated.
Hashtables properties should always be in PascalCase and be on a separate line.
When comparing a value to $null, $null should be on the left side of the comparison.

Files:

  • tests/Integration/Commands/Assert-SqlDscLogin.Integration.Tests.ps1
  • tests/Integration/Commands/Get-SqlDscServerPermission.Integration.Tests.ps1
  • source/Public/Get-SqlDscServerPermission.ps1
  • tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1
azure-pipelines.yml

📄 CodeRabbit Inference Engine (.github/copilot-instructions.md)

Integration test script files for public commands must be added to a group within the 'Integration_Test_Commands_SqlServer' stage in ./azure-pipelines.yml.

Files:

  • azure-pipelines.yml
source/Public/*.ps1

📄 CodeRabbit Inference Engine (.github/copilot-instructions.md)

source/Public/*.ps1: Public PowerShell commands should each have their own script file named after the command (with .ps1 extension) and be placed in the folder source/Public.
All public command names must have the noun prefixed with 'SqlDsc', e.g. {Verb}-SqlDsc{Noun}.

Files:

  • source/Public/Get-SqlDscServerPermission.ps1
source/{Public,Private,Classes}/*.ps1

📄 CodeRabbit Inference Engine (.github/copilot-instructions.md)

source/{Public,Private,Classes}/*.ps1: Comment-based help should always be before the function-statement for each public command and private function, and before the class-statement for each class-based resource. It should be in the format of a comment block and at least use the keywords: .SYNOPSIS, .DESCRIPTION, .PARAMETER, .EXAMPLE, and .NOTES.
Each comment-based help keyword should be indented with 4 spaces and each keyword's text should be indented 8 spaces.
The text for keyword .DESCRIPTION should be descriptive and must have a length greater than 40 characters. The .SYNOPSIS keyword text should be a short description.
A comment-based help must have at least one example, but preferably more examples to showcase all possible parameter sets and different parameter combinations.
Use PascalCase for function names and parameters in public commands, private functions, and class-based resources.

Files:

  • source/Public/Get-SqlDscServerPermission.ps1
source/{Public,Private}/*.ps1

📄 CodeRabbit Inference Engine (.github/copilot-instructions.md)

source/{Public,Private}/*.ps1: All message strings for Write-Debug, Write-Verbose, Write-Error, Write-Warning and other error messages in public commands and private functions should be localized using localized string keys.
All public command and private function names must follow the standard PowerShell Verb-Noun format.
All public command and private function names must use PowerShell approved verbs.
All public commands and private functions should always be advanced functions and have [CmdLetBinding()] attribute.
Public commands and private functions with no parameters should still have an empty parameter block param ().
Every parameter in public commands and private functions should include the [Parameter()] attribute.
A mandatory parameter in public commands and private functions should contain the decoration [Parameter(Mandatory = $true)], and non-mandatory parameters should not contain the Mandatory decoration.
Parameters attributes, datatype and its name should be on separate lines.
Parameters must be separated by a single, blank line.
Use Write-Verbose to output verbose output for actions a public command or private function does.
Use Write-Debug for debug output for processes within the script for user to see the decisions a command or private function does.

Files:

  • source/Public/Get-SqlDscServerPermission.ps1
tests/Unit/{Classes,Public,Private}/*.Tests.ps1

📄 CodeRabbit Inference Engine (.github/copilot-instructions.md)

Unit tests should be added for all public commands, private functions and class-based resources. Unit tests for class-based resources should be placed in tests/Unit/Classes, for public commands in tests/Unit/Public, and for private functions in tests/Unit/Private. The unit tests should be named after the item being tested with the suffix .Tests.ps1.

Files:

  • tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1
tests/Unit/Public/*.Tests.ps1

📄 CodeRabbit Inference Engine (.github/copilot-instructions.md)

tests/Unit/Public/*.Tests.ps1: All public commands should always have a test to validate parameter sets using the provided template.
All public commands should also include tests to validate parameter properties.

Files:

  • tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1
tests/Unit/**/*.ps1

📄 CodeRabbit Inference Engine (.github/copilot-instructions.md)

tests/Unit/**/*.ps1: Never test, mock or use Should -Invoke for Write-Verbose and Write-Debug.
Never use Should -Not -Throw in tests; instead, call the command directly.
All unit tests should use the provided code block prior to the Describe block to set up the test environment and load the correct module.

Files:

  • tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1
CHANGELOG.md

📄 CodeRabbit Inference Engine (.github/copilot-instructions.md)

The Unreleased section in CHANGELOG.md should always be updated when making changes to the codebase, using the keepachangelog format and providing concrete release notes.

Files:

  • CHANGELOG.md
**/*.md

📄 CodeRabbit Inference Engine (.github/copilot-instructions.md)

**/*.md: Markdown files should wrap lines after a word when a line exceeds 80 characters.
Use 2 spaces for indentation in Markdown files.

Files:

  • CHANGELOG.md
🧠 Learnings (14)
📚 Learning: 2025-08-03T09:50:27.001Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-03T09:50:27.001Z
Learning: Applies to tests/**/*.ps1 : AfterAll block can be used to clean up any test data.

Applied to files:

  • tests/Integration/Commands/Assert-SqlDscLogin.Integration.Tests.ps1
📚 Learning: 2025-08-03T09:50:27.001Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-03T09:50:27.001Z
Learning: Applies to tests/**/*.ps1 : BeforeAll, BeforeEach, AfterAll and AfterEach blocks should be used inside the Context block as near as possible to the It block that will use the test data, test setup and teardown.

Applied to files:

  • tests/Integration/Commands/Assert-SqlDscLogin.Integration.Tests.ps1
📚 Learning: 2025-08-03T09:50:27.001Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-03T09:50:27.001Z
Learning: Applies to tests/Integration/Commands/*.Integration.Tests.ps1 : All integration tests must use the provided code block prior to the first Describe block to set up the integration test environment.

Applied to files:

  • tests/Integration/Commands/Assert-SqlDscLogin.Integration.Tests.ps1
  • azure-pipelines.yml
📚 Learning: 2025-08-03T09:50:27.001Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-03T09:50:27.001Z
Learning: Applies to azure-pipelines.yml : Integration test script files for public commands must be added to a group within the 'Integration_Test_Commands_SqlServer' stage in ./azure-pipelines.yml.

Applied to files:

  • azure-pipelines.yml
  • tests/Integration/Commands/Get-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-03T09:50:27.001Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-03T09:50:27.001Z
Learning: Applies to tests/Integration/Commands/*.Integration.Tests.ps1 : Integration tests for public commands should be placed in tests/Integration/Commands and named after the command with the suffix .Integration.Tests.ps1.

Applied to files:

  • azure-pipelines.yml
  • tests/Integration/Commands/Get-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-03T09:50:27.001Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-03T09:50:27.001Z
Learning: Applies to tests/Unit/{Classes,Public,Private}/*.Tests.ps1 : Unit tests should be added for all public commands, private functions and class-based resources. Unit tests for class-based resources should be placed in tests/Unit/Classes, for public commands in tests/Unit/Public, and for private functions in tests/Unit/Private. The unit tests should be named after the item being tested with the suffix .Tests.ps1.

Applied to files:

  • azure-pipelines.yml
📚 Learning: 2025-08-03T09:50:27.001Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-03T09:50:27.001Z
Learning: Applies to tests/**/*.ps1 : It blocks must always call the command or function being tested and result and outcomes should be kept in the same It block.

Applied to files:

  • tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1
📚 Learning: 2025-08-03T09:50:27.001Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-03T09:50:27.001Z
Learning: Applies to tests/**/*.ps1 : BeforeEach and AfterEach blocks should be used sparingly.

Applied to files:

  • tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1
📚 Learning: 2025-08-03T09:50:27.001Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-03T09:50:27.001Z
Learning: Applies to tests/Unit/**/*.ps1 : Never use Should -Not -Throw in tests; instead, call the command directly.

Applied to files:

  • tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1
📚 Learning: 2025-08-03T09:50:27.001Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-03T09:50:27.001Z
Learning: Applies to tests/Unit/**/*.ps1 : Never test, mock or use Should -Invoke for Write-Verbose and Write-Debug.

Applied to files:

  • tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1
📚 Learning: 2025-08-03T09:50:27.001Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-03T09:50:27.001Z
Learning: Applies to tests/**/*.ps1 : Files that need to be mocked should be created in Pester's test drive using the $TestDrive variable.

Applied to files:

  • tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1
📚 Learning: 2025-08-03T09:50:27.001Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-03T09:50:27.001Z
Learning: Applies to tests/**/*.ps1 : BeforeAll and BeforeEach blocks should never call the command or function being tested.

Applied to files:

  • tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1
📚 Learning: 2025-08-03T09:50:27.001Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-03T09:50:27.001Z
Learning: Applies to tests/Unit/Public/*.Tests.ps1 : All public commands should also include tests to validate parameter properties.

Applied to files:

  • tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1
📚 Learning: 2025-08-03T09:50:27.001Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-03T09:50:27.001Z
Learning: Applies to tests/**/*.ps1 : Parameter validation should never be tested.

Applied to files:

  • tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1
🧬 Code Graph Analysis (5)
azure-pipelines.yml (1)
tests/Unit/Stubs/SMO.cs (1)
  • ServerPermissionSet (183-205)
tests/Integration/Commands/Get-SqlDscServerPermission.Integration.Tests.ps1 (1)
tests/Unit/Stubs/SMO.cs (5)
  • ServerPermissionSet (183-205)
  • DatabasePermissionSet (233-244)
  • ServerPermissionInfo (211-226)
  • ServerPermissionSet (187-197)
  • ServerPermissionSet (185-185)
source/Public/Get-SqlDscServerPermission.ps1 (1)
tests/Unit/Stubs/SMO.cs (1)
  • ServerPermissionSet (183-205)
tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1 (1)
tests/Unit/Stubs/SMO.cs (8)
  • ServerPermissionSet (183-205)
  • ServerPermissionInfo (211-226)
  • ServerPermissionSet (187-197)
  • ServerPermissionInfo (219-222)
  • ServerPermissionSet (185-185)
  • Server (277-348)
  • ServerPermissionInfo (213-217)
  • Microsoft.SqlServer.Management.Smo (11-1000)
CHANGELOG.md (1)
tests/Unit/Stubs/SMO.cs (1)
  • ServerPermissionSet (183-205)
⏰ 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 (16)
tests/Integration/Commands/Assert-SqlDscLogin.Integration.Tests.ps1 (1)

56-58: LGTM!

The AfterAll cleanup block correctly disconnects the server object after tests complete. This ensures proper resource cleanup and prevents potential connection leaks.

azure-pipelines.yml (1)

251-252: LGTM!

The new integration test is correctly placed in Group 2 of the integration test sequence, appropriately positioned after Assert-SqlDscLogin tests and before the uninstall tests.

source/Public/Get-SqlDscServerPermission.ps1 (2)

88-116: PrincipalType parameter logic is correct.

The implementation correctly handles the optional PrincipalType parameter, allowing callers to specify whether to check for logins, roles, or both. The conditional logic properly prevents redundant role checks when a login is found. This provides good flexibility while maintaining backward compatibility when the parameter is not specified.


2-6: Update .SYNOPSIS to clearly indicate server role support.

The synopsis should explicitly mention that the command supports both logins and server roles (not just "server role" in the general sense).

Apply this diff:

    .SYNOPSIS
-        Returns the current permissions for a SQL Server login or server role.
+        Returns the current permissions for a SQL Server login or a server role.

Likely an incorrect or invalid review comment.

tests/Integration/Commands/Get-SqlDscServerPermission.Integration.Tests.ps1 (6)

56-58: LGTM!

Proper cleanup with Disconnect-SqlDscDatabaseEngine ensures resources are released after test execution.


60-74: LGTM! Good coverage of SQL login scenarios.

Tests correctly validate permissions retrieval for SQL logins, including pipeline support.


76-91: LGTM! Comprehensive Windows login testing.

Tests properly cover different Windows login formats including domain accounts and built-in principals.


93-121: LGTM! Thorough server role testing.

Excellent coverage of both built-in server roles (sysadmin, public) and additional system roles (serveradmin, securityadmin).


147-169: LGTM! Comprehensive permission property validation.

Tests correctly verify that ServerPermissionInfo objects have the expected properties with valid values. The PermissionState validation correctly checks for all three possible states.


171-214: LGTM! Excellent PrincipalType parameter testing.

Comprehensive test coverage for the new PrincipalType parameter, including:

  • Valid type specifications
  • Multiple type specifications
  • Type mismatches with appropriate error handling
  • Both Stop and SilentlyContinue error actions

This thoroughly validates the new functionality.

tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1 (6)

61-64: LGTM: Mock setup correctly isolates login scenarios.

The addition of Test-SqlDscIsRole mock returning $false properly isolates the "principal does not exist" test scenario by ensuring both login and role checks fail.


88-88: LGTM: Clear context naming for login-specific tests.

Renaming the context from "When the principal exist" to "When the principal is a login" improves test clarity and aligns with the new role-based testing structure.


121-124: LGTM: Mock isolation for login test scenarios.

Adding Test-SqlDscIsRole mock returning $false correctly isolates the login path in the tests, ensuring the role check doesn't interfere with login-specific scenarios.


158-226: LGTM: Comprehensive server role testing coverage.

The new context provides thorough test coverage for server role scenarios including:

  • Proper mock setup with ViewServerState and ControlServer permissions
  • Both direct function calls and pipeline usage
  • Correct isolation using Test-SqlDscIsLogin and Test-SqlDscIsRole mocks

The test structure follows the established patterns and validates the expected behavior for server roles.


349-455: LGTM: Thorough parameter-driven test coverage.

The new test contexts provide comprehensive coverage for the PrincipalType parameter scenarios:

  • Login type with valid login principal
  • Role type with valid role principal
  • Login type with invalid principal (proper error handling)

The mock setups correctly simulate different permission sets (ConnectSql for logins, ViewServerState for roles) and the tests validate the expected behavior including error conditions.


457-510: LGTM: Complete parameter validation coverage.

The parameter validation tests comprehensively cover:

  • Parameter set validation with the new PrincipalType parameter
  • Mandatory parameter requirements for ServerObject and Name
  • Optional parameter validation for PrincipalType
  • Pipeline support for ServerObject
  • ValidateSet values for PrincipalType ('Login', 'Role')

All tests follow the coding guidelines for unit test structure and parameter validation.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

♻️ Duplicate comments (2)
CHANGELOG.md (2)

22-24: Wrapped lines comply with the 80-char guideline—thanks for addressing.

No further action needed here.


21-26: Promote explicit issue closure with a dedicated “Fixes #2063” sub-bullet.

Improves traceability and aligns with existing “fixes [#2106]” style elsewhere. Move the inline “(issue #2063)” to its own sub-bullet.

-  - The function now accepts both login principals and server role principals
-    as the `Name` parameter (issue [#2063](https://github.com/dsccommunity/SqlServerDsc/issues/2063)).
+  - The function now accepts both login principals and server role principals
+    as the `Name` parameter.
+  - Fixes [#2063](https://github.com/dsccommunity/SqlServerDsc/issues/2063).
📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8ff42a2 and 2611241.

📒 Files selected for processing (1)
  • CHANGELOG.md (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
CHANGELOG.md

📄 CodeRabbit Inference Engine (.github/copilot-instructions.md)

The Unreleased section in CHANGELOG.md should always be updated when making changes to the codebase, using the keepachangelog format and providing concrete release notes.

Files:

  • CHANGELOG.md
**/*.md

📄 CodeRabbit Inference Engine (.github/copilot-instructions.md)

**/*.md: Markdown files should wrap lines after a word when a line exceeds 80 characters.
Use 2 spaces for indentation in Markdown files.

Files:

  • CHANGELOG.md
🧬 Code Graph Analysis (1)
CHANGELOG.md (1)
tests/Unit/Stubs/SMO.cs (1)
  • ServerPermissionSet (183-205)
⏰ 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

@johlju johlju added the needs review The pull request needs a code review. label Aug 14, 2025
@johlju johlju force-pushed the fix/get-sqldscserverpermission branch from f335027 to a71b591 Compare September 1, 2025 07:09
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

♻️ Duplicate comments (1)
tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1 (1)

247-257: Relax exact invocation of role-check to avoid future coupling.

Asserting both Test-SqlDscIsLogin and Test-SqlDscIsRole are called exactly once (when no PrincipalType is specified) prevents short‑circuit optimizations (e.g., skip role check if login exists). Recommend only asserting the login call here; keep the separate scenario that proves role is called when login isn’t found.

             It 'Should call both Test-SqlDscIsLogin and Test-SqlDscIsRole' {
                 $null = Get-SqlDscServerPermission -ServerObject $mockServerObject -Name 'TestPrincipal' -ErrorAction 'SilentlyContinue'

                 Should -Invoke -CommandName Test-SqlDscIsLogin -ParameterFilter {
                     $ServerObject.Equals($mockServerObject) -and $Name -eq 'TestPrincipal'
                 } -Exactly -Times 1

-                Should -Invoke -CommandName Test-SqlDscIsRole -ParameterFilter {
-                    $ServerObject.Equals($mockServerObject) -and $Name -eq 'TestPrincipal'
-                } -Exactly -Times 1
+                # Intentionally not asserting exact invocation of Test-SqlDscIsRole to allow short-circuiting.
             }
             It 'Should call both Test-SqlDscIsLogin and Test-SqlDscIsRole' {
                 $null = Get-SqlDscServerPermission -ServerObject $mockServerObject -Name 'TestPrincipal' -ErrorAction 'SilentlyContinue'

                 Should -Invoke -CommandName Test-SqlDscIsLogin -ParameterFilter {
                     $ServerObject.Equals($mockServerObject) -and $Name -eq 'TestPrincipal'
                 } -Exactly -Times 1

-                Should -Invoke -CommandName Test-SqlDscIsRole -ParameterFilter {
-                    $ServerObject.Equals($mockServerObject) -and $Name -eq 'TestPrincipal'
-                } -Exactly -Times 1
+                Should -Invoke -CommandName Test-SqlDscIsRole -ParameterFilter {
+                    $ServerObject.Equals($mockServerObject) -and $Name -eq 'TestPrincipal'
+                } -Exactly -Times 1
             }

Also applies to: 271-281

🧹 Nitpick comments (4)
tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1 (1)

462-486: Minor test-structure nit: define -ForEach data in BeforeDiscovery.

To align with our Pester patterns, move the parameter‑set test data into a nearby BeforeDiscovery block.

-        It 'Should have the correct parameters in parameter set <MockParameterSetName>' -ForEach @(
-            @{
-                MockParameterSetName = '__AllParameterSets'
-                MockExpectedParameters = '[-ServerObject] <Server> [-Name] <string> [[-PrincipalType] <string[]>] [<CommonParameters>]'
-            }
-        ) {
+        BeforeDiscovery {
+            $mockParameterSetData = @(
+                @{
+                    MockParameterSetName   = '__AllParameterSets'
+                    MockExpectedParameters = '[-ServerObject] <Server> [-Name] <string> [[-PrincipalType] <string[]>] [<CommonParameters>]'
+                }
+            )
+        }
+
+        It 'Should have the correct parameters in parameter set <MockParameterSetName>' -ForEach $mockParameterSetData {
source/Public/Get-SqlDscServerPermission.ps1 (3)

68-76: Add ValidateNotNullOrEmpty for Name and ValidateCount for PrincipalType.

Prevents empty inputs and empty arrays, aligning with our parameter‑validation guidance.

         [Parameter(Mandatory = $true)]
         [System.String]
-        $Name,
+        [ValidateNotNullOrEmpty()]
+        $Name,
 
         [Parameter()]
         [ValidateSet('Login', 'Role')]
+        [ValidateCount(1,2)]
         [System.String[]]
         $PrincipalType

98-116: Skip role check when login already matched.

Micro‑optimization: avoid calling Test-SqlDscIsRole if $isLogin is true and both checks are enabled.

-        # Perform the appropriate checks
-        $isLogin = if ($checkLogin)
+        # Perform the appropriate checks
+        $isLogin = if ($checkLogin)
         {
             Test-SqlDscIsLogin @testSqlDscIsPrincipalParameters
         }
         else
         {
             $false
         }
 
-        $isRole = if ($checkRole)
-        {
-            Test-SqlDscIsRole @testSqlDscIsPrincipalParameters
-        }
-        else
-        {
-            $false
-        }
+        # Only check role if requested and not already found as login
+        $isRole = $false
+        if ($checkRole -and -not $isLogin)
+        {
+            $isRole = Test-SqlDscIsRole @testSqlDscIsPrincipalParameters
+        }

57-59: Mismatch in suppression comment text.

The PSUseOutputTypeCorrectly suppression justification mentions “[System.String[]]”, but the function outputs ServerPermissionInfo[]. Update the justification to avoid confusion.

-    [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseOutputTypeCorrectly', '', Justification = 'Because the rule does not understands that the command returns [System.String[]] when using , (comma) in the return statement')]
+    [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseOutputTypeCorrectly', '', Justification = 'Ensures Script Analyzer does not misinterpret the comma operator return as a mismatched type; output is [Microsoft.SqlServer.Management.Smo.ServerPermissionInfo[]].')]
📜 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 f335027 and a71b591.

📒 Files selected for processing (7)
  • CHANGELOG.md (1 hunks)
  • azure-pipelines.yml (0 hunks)
  • source/Public/Get-SqlDscServerPermission.ps1 (3 hunks)
  • source/Public/Test-SqlDscIsRole.ps1 (2 hunks)
  • tests/Integration/Commands/Assert-SqlDscLogin.Integration.Tests.ps1 (1 hunks)
  • tests/Integration/Commands/Get-SqlDscServerPermission.Integration.Tests.ps1 (1 hunks)
  • tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1 (4 hunks)
💤 Files with no reviewable changes (1)
  • azure-pipelines.yml
🚧 Files skipped from review as they are similar to previous changes (4)
  • tests/Integration/Commands/Assert-SqlDscLogin.Integration.Tests.ps1
  • source/Public/Test-SqlDscIsRole.ps1
  • tests/Integration/Commands/Get-SqlDscServerPermission.Integration.Tests.ps1
  • CHANGELOG.md
🧰 Additional context used
📓 Path-based instructions (13)
**/*.{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/Public/Get-SqlDscServerPermission.ps1
  • tests/Unit/Public/Get-SqlDscServerPermission.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/Public/Get-SqlDscServerPermission.ps1
  • tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1
source/**/*.ps1

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

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

Files:

  • source/Public/Get-SqlDscServerPermission.ps1

⚙️ CodeRabbit configuration file

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

Requirements

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

String Files

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

Key Naming Patterns

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

String Format

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

String IDs

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

Usage

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

Files:

  • source/Public/Get-SqlDscServerPermission.ps1
source/Public/*.ps1

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

source/Public/*.ps1: Place public commands in source/Public/{CommandName}.ps1
Separate reusable logic into private functions (keep public commands thin)

Files:

  • source/Public/Get-SqlDscServerPermission.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/Public/Get-SqlDscServerPermission.ps1
  • tests/Unit/Public/Get-SqlDscServerPermission.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/Public/Get-SqlDscServerPermission.ps1
  • tests/Unit/Public/Get-SqlDscServerPermission.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/Public/Get-SqlDscServerPermission.ps1
  • tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1
**/*.Tests.ps1

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

Follow test patterns strictly for maintainability in Pester tests

Files:

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

⚙️ CodeRabbit configuration file

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

Core Requirements

  • All public commands, private functions and classes must have unit tests
  • All public commands and class-based resources must have integration tests
  • Use Pester v5 syntax only
  • Test code only inside Describe blocks
  • Assertions only in It blocks
  • Never test verbose messages, debug messages or parameter binding behavior
  • Pass all mandatory parameters to avoid prompts

Requirements

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

Naming

  • One Describe block per file matching the tested entity name
  • Context descriptions start with 'When'
  • It descriptions start with 'Should', must not contain 'when'
  • Mock variables prefix: 'mock'

Structure & Scope

  • Public commands: Never use InModuleScope (unless retrieving localized strings)
  • Private functions/class resources: Always use InModuleScope
  • Each class method = separate Context block
  • Each scenario = separate Context block
  • Use nested Context blocks for complex scenarios
  • Mocking in BeforeAll (BeforeEach only when required)
  • Setup/teardown in BeforeAll,BeforeEach/AfterAll,AfterEach close to usage

Syntax Rules

  • PascalCase: Describe, Context, It, Should, BeforeAll, BeforeEach, AfterAll, AfterEach
  • 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 `InModule...

Files:

  • tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1
tests/Unit/Public/*.Tests.ps1

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

tests/Unit/Public/*.Tests.ps1: For public commands, never use InModuleScope (except when retrieving localized strings)
Place public command unit tests under tests/Unit/Public/{Name}.Tests.ps1

Files:

  • tests/Unit/Public/Get-SqlDscServerPermission.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/Public/Get-SqlDscServerPermission.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/Public/Get-SqlDscServerPermission.Tests.ps1
🧠 Learnings (19)
📚 Learning: 2025-08-17T10:13:30.079Z
Learnt from: johlju
PR: dsccommunity/SqlServerDsc#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/Public/Get-SqlDscServerPermission.Tests.ps1
📚 Learning: 2025-08-18T13:50:53.789Z
Learnt from: johlju
PR: dsccommunity/SqlServerDsc#2132
File: tests/Unit/Public/New-SqlDscLogin.Tests.ps1:0-0
Timestamp: 2025-08-18T13:50:53.789Z
Learning: In SqlServerDsc unit tests, SMO stub objects can be used to verify method calls like Create() on Login objects by adding mock verifications with Should -Invoke, providing more robust testing than just checking for no exceptions.

Applied to files:

  • tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1
📚 Learning: 2025-08-29T17:23:02.585Z
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.585Z
Learning: Applies to **/*.[Tt]ests.ps1 : Use assertions only inside It blocks

Applied to files:

  • tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1
📚 Learning: 2025-08-29T17:23:02.585Z
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.585Z
Learning: Applies to **/*.[Tt]ests.ps1 : Do not use Assert-MockCalled; use Should -Invoke instead

Applied to files:

  • tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1
📚 Learning: 2025-08-29T17:23:02.585Z
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.585Z
Learning: Applies to **/*.[Tt]ests.ps1 : Keep results and assertions in the same It block

Applied to files:

  • tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1
📚 Learning: 2025-08-29T17:19:40.951Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-29T17:19:40.951Z
Learning: Applies to **/*.Tests.ps1 : Follow test patterns strictly for maintainability in Pester tests

Applied to files:

  • tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1
📚 Learning: 2025-08-29T17:20:42.266Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-08-29T17:20:42.266Z
Learning: Applies to tests/Integration/**/*.ps1 : Always call Disconnect-SqlDscDatabaseEngine after Connect-SqlDscDatabaseEngine in integration tests

Applied to files:

  • tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1
📚 Learning: 2025-08-29T17:23:02.585Z
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.585Z
Learning: Applies to **/*.[Tt]ests.ps1 : Omit -MockWith when returning $null

Applied to files:

  • tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1
📚 Learning: 2025-08-29T17:23:02.585Z
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.585Z
Learning: Applies to **/*.[Tt]ests.ps1 : Never add an empty -MockWith block

Applied to files:

  • tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1
📚 Learning: 2025-08-29T17:23:02.585Z
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.585Z
Learning: Applies to **/*.[Tt]ests.ps1 : Never use Mock inside an InModuleScope block

Applied to files:

  • tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1
📚 Learning: 2025-08-29T17:23:02.585Z
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.585Z
Learning: Applies to **/*.[Tt]ests.ps1 : Do not use Should -Not -Throw; invoke commands directly

Applied to files:

  • tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1
📚 Learning: 2025-08-29T17:22:07.610Z
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.610Z
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/Public/Get-SqlDscServerPermission.Tests.ps1
📚 Learning: 2025-08-29T17:23:02.585Z
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.585Z
Learning: Applies to **/*.[Tt]ests.ps1 : Context descriptions start with 'When'

Applied to files:

  • tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1
📚 Learning: 2025-08-29T17:23:02.585Z
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.585Z
Learning: Applies to **/*.[Tt]ests.ps1 : Set $PSDefaultParameterValues for Mock:ModuleName, Should:ModuleName, and InModuleScope:ModuleName

Applied to files:

  • tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1
📚 Learning: 2025-08-29T17:24:39.268Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-unit-tests.instructions.md:0-0
Timestamp: 2025-08-29T17:24:39.268Z
Learning: Applies to tests/[u]Unit/**/*.[Tt]ests.ps1 : All public commands must have parameter set validation tests

Applied to files:

  • tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1
📚 Learning: 2025-08-16T13:22:15.230Z
Learnt from: johlju
PR: dsccommunity/SqlServerDsc#2134
File: tests/Unit/Public/Get-SqlDscLogin.Tests.ps1:78-93
Timestamp: 2025-08-16T13:22:15.230Z
Learning: In PowerShell unit tests for parameter validation in SqlServerDsc, accessing parameter attributes directly like `$cmd.Parameters['ParameterName'].Attributes.Mandatory` works correctly because PowerShell automatically iterates through the array and returns the property values. Additional filtering to ParameterAttribute is not necessary when the parameter structure is known and controlled.

Applied to files:

  • tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1
📚 Learning: 2025-08-29T17:24:39.268Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-unit-tests.instructions.md:0-0
Timestamp: 2025-08-29T17:24:39.268Z
Learning: Applies to tests/[u]Unit/**/*.[Tt]ests.ps1 : Use the provided Parameter Set Validation test template for single-parameter-set commands

Applied to files:

  • tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1
📚 Learning: 2025-08-29T17:24:39.268Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-unit-tests.instructions.md:0-0
Timestamp: 2025-08-29T17:24:39.268Z
Learning: Applies to tests/[u]Unit/**/*.[Tt]ests.ps1 : Add Parameter Properties tests (e.g., assert Mandatory on parameters) as shown in the template

Applied to files:

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

Applied to files:

  • tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1
🧬 Code graph analysis (1)
tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1 (1)
tests/Unit/Stubs/SMO.cs (7)
  • ServerPermissionSet (184-206)
  • ServerPermissionInfo (212-227)
  • ServerPermissionSet (188-198)
  • ServerPermissionInfo (214-218)
  • Microsoft (12-1048)
  • Microsoft (332-340)
  • ServerPermissionInfo (220-223)
⏰ 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 (10)
tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1 (8)

62-64: Mocks for role-check path are correct and scoped well.

Good use of explicit Test-SqlDscIsRole mocks to steer the principal-detection path in login-focused contexts.

Also applies to: 122-124


88-88: Context rename improves intent clarity.

“principal is a login” is clearer and aligns with added role scenarios.


158-195: Server-role scenario setup looks solid.

Inline EnumServerPermissions stub returns distinct permissions and states; role/login mocks are coherent with the scenario. Nice coverage.


197-209: Role result assertions are accurate.

Validates both entries and their flags succinctly.


211-225: Pipeline variant covered.

Covers pipeline binding for ServerObject for role path as well. LGTM.


295-303: Call-verification scenarios read well and align with PrincipalType semantics.

Clear separation for Login, Role, and combined types; proper use of Should -Invoke with ParameterFilter.

Also applies to: 317-325, 339-349


353-393: PrincipalType result-path tests are comprehensive.

Covers happy paths for Login/Role and the error path for mismatched type. Nicely mirrors the command’s branching.

Also applies to: 395-433, 437-457


507-513: ValidateSet checks look correct.

Covers both values and enforces the count.

source/Public/Get-SqlDscServerPermission.ps1 (2)

31-48: Help updates and examples correctly advertise server-role support.

Examples for role and PrincipalType are helpful and meet our help guidelines.


88-97: PrincipalType routing flags are clear and correct.

Simple, readable derivation of $checkLogin/$checkRole from user input.

…rameters, improving flexibility in permission checks and updating documentation for clarity.
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

♻️ Duplicate comments (1)
tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1 (1)

236-257: Relax exact call-count coupling to allow short‑circuit optimizations.

Asserting both Test-SqlDscIsLogin and Test-SqlDscIsRole are called exactly once bakes in the current implementation and blocks a future optimization where role check is skipped if login exists. Recommend either (A) remove the exact invocation assertion for Test-SqlDscIsRole here, or (B) split into two Its: one where login=$true and assert role is 0..1, and another where login=$false and assert role is 1.

-                Should -Invoke -CommandName Test-SqlDscIsRole -ParameterFilter {
-                    $ServerObject.Equals($mockServerObject) -and $Name -eq 'TestPrincipal'
-                } -Exactly -Times 1
+                # Allow future short-circuit optimization
+                Should -Invoke -CommandName Test-SqlDscIsRole -AtMost -Times 1

Also applies to: 271-281

🧹 Nitpick comments (6)
tests/Integration/Commands/Get-SqlDscServerPermission.Integration.Tests.ps1 (4)

26-30: Use required import pattern (Force + Stop) per integration test guidelines.

Import should be forced and fail fast.

-    Import-Module -Name $script:dscModuleName
+    Import-Module -Name $script:dscModuleName -Force -ErrorAction 'Stop'

53-58: Add -ErrorAction Stop to Connect/Disconnect for immediate surfacing of failures.

Aligns with integration test guidance.

-            $script:serverObject = Connect-SqlDscDatabaseEngine -InstanceName $script:instanceName -Credential $script:sqlAdminCredential
+            $script:serverObject = Connect-SqlDscDatabaseEngine -InstanceName $script:instanceName -Credential $script:sqlAdminCredential -ErrorAction 'Stop'
@@
-            Disconnect-SqlDscDatabaseEngine -ServerObject $script:serverObject
+            Disconnect-SqlDscDatabaseEngine -ServerObject $script:serverObject -ErrorAction 'Stop'

124-127: Avoid ExpectedMessage in Should -Throw (integration tests).

Per guidelines, don’t assert error text in integration tests; only assert that an error is thrown.

-                { Get-SqlDscServerPermission -ServerObject $script:serverObject -Name 'NonExistentLogin123' -ErrorAction 'Stop' } |
-                    Should -Throw -ExpectedMessage "*is not a login nor role*"
+                { Get-SqlDscServerPermission -ServerObject $script:serverObject -Name 'NonExistentLogin123' -ErrorAction 'Stop' } |
+                    Should -Throw
@@
-                { Get-SqlDscServerPermission -ServerObject $script:serverObject -Name 'NonExistentRole123' -ErrorAction 'Stop' } |
-                    Should -Throw -ExpectedMessage "*is not a login nor role*"
+                { Get-SqlDscServerPermission -ServerObject $script:serverObject -Name 'NonExistentRole123' -ErrorAction 'Stop' } |
+                    Should -Throw
@@
-                { Get-SqlDscServerPermission -ServerObject $script:serverObject -Name 'sa' -PrincipalType 'Role' -ErrorAction 'Stop' } |
-                    Should -Throw -ExpectedMessage "*is not a login nor role*"
+                { Get-SqlDscServerPermission -ServerObject $script:serverObject -Name 'sa' -PrincipalType 'Role' -ErrorAction 'Stop' } |
+                    Should -Throw
@@
-                { Get-SqlDscServerPermission -ServerObject $script:serverObject -Name 'sysadmin' -PrincipalType 'Login' -ErrorAction 'Stop' } |
-                    Should -Throw -ExpectedMessage "*is not a login nor role*"
+                { Get-SqlDscServerPermission -ServerObject $script:serverObject -Name 'sysadmin' -PrincipalType 'Login' -ErrorAction 'Stop' } |
+                    Should -Throw

Also applies to: 135-138, 193-201


216-251: Optional: add -ErrorAction Stop to object fetches for parity.

Not strictly required, but improves failure visibility when getting Login/Role objects.

-                $loginObject = Get-SqlDscLogin -ServerObject $script:serverObject -Name 'sa'
+                $loginObject = Get-SqlDscLogin -ServerObject $script:serverObject -Name 'sa' -ErrorAction 'Stop'
@@
-                $loginObject = Get-SqlDscLogin -ServerObject $script:serverObject -Name $windowsLogin
+                $loginObject = Get-SqlDscLogin -ServerObject $script:serverObject -Name $windowsLogin -ErrorAction 'Stop'
@@
-                $roleObject = Get-SqlDscRole -ServerObject $script:serverObject -Name 'sysadmin'
+                $roleObject = Get-SqlDscRole -ServerObject $script:serverObject -Name 'sysadmin' -ErrorAction 'Stop'
@@
-                $roleObject = Get-SqlDscRole -ServerObject $script:serverObject -Name 'public'
+                $roleObject = Get-SqlDscRole -ServerObject $script:serverObject -Name 'public' -ErrorAction 'Stop'

Also applies to: 255-291

source/Public/Get-SqlDscServerPermission.ps1 (2)

40-95: Add INPUTS section to comment-based help.

List pipeline-accepted types to meet help requirements.

     .OUTPUTS
         [Microsoft.SqlServer.Management.Smo.ServerPermissionInfo[]]
 
+    .INPUTS
+        Microsoft.SqlServer.Management.Smo.Server
+            Server connection object accepted from the pipeline (ByName set).
+
+        Microsoft.SqlServer.Management.Smo.Login
+            Login object accepted from the pipeline (Login set).
+
+        Microsoft.SqlServer.Management.Smo.ServerRole
+            Server role object accepted from the pipeline (ServerRole set).

132-186: Skip role check when login is confirmed (minor optimization + clarity).

Avoids redundant Test-SqlDscIsRole calls and reads clearer.

-            # Perform the appropriate checks
-            $isLogin = if ($checkLogin)
-            {
-                Test-SqlDscIsLogin @testSqlDscIsPrincipalParameters
-            }
-            else
-            {
-                $false
-            }
-
-            $isRole = if ($checkRole)
-            {
-                Test-SqlDscIsRole @testSqlDscIsPrincipalParameters
-            }
-            else
-            {
-                $false
-            }
+            # Perform the appropriate checks. Only check role if either role is requested
+            # or both are allowed AND it was not found as a login.
+            $isLogin = $checkLogin -and (Test-SqlDscIsLogin @testSqlDscIsPrincipalParameters)
+
+            $isRole = $false
+            if ($checkRole -and -not $isLogin)
+            {
+                $isRole = Test-SqlDscIsRole @testSqlDscIsPrincipalParameters
+            }
📜 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 a71b591 and a6e1913.

📒 Files selected for processing (4)
  • CHANGELOG.md (2 hunks)
  • source/Public/Get-SqlDscServerPermission.ps1 (2 hunks)
  • tests/Integration/Commands/Get-SqlDscServerPermission.Integration.Tests.ps1 (1 hunks)
  • tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1 (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • CHANGELOG.md
🧰 Additional context used
📓 Path-based instructions (19)
**/*.{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/Public/Get-SqlDscServerPermission.ps1
  • tests/Integration/Commands/Get-SqlDscServerPermission.Integration.Tests.ps1
  • tests/Unit/Public/Get-SqlDscServerPermission.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/Public/Get-SqlDscServerPermission.ps1
  • tests/Integration/Commands/Get-SqlDscServerPermission.Integration.Tests.ps1
  • tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1
source/**/*.ps1

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

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

Files:

  • source/Public/Get-SqlDscServerPermission.ps1

⚙️ CodeRabbit configuration file

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

Requirements

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

String Files

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

Key Naming Patterns

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

String Format

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

String IDs

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

Usage

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

Files:

  • source/Public/Get-SqlDscServerPermission.ps1
source/Public/*.ps1

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

source/Public/*.ps1: Place public commands in source/Public/{CommandName}.ps1
Separate reusable logic into private functions (keep public commands thin)

Files:

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

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

Follow test patterns strictly for maintainability in Pester tests

Files:

  • tests/Integration/Commands/Get-SqlDscServerPermission.Integration.Tests.ps1
  • tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1
**/*Integration.Tests.ps1

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

Always add and structure Integration tests according to the integration testing guidelines

Files:

  • tests/Integration/Commands/Get-SqlDscServerPermission.Integration.Tests.ps1
tests/Integration/**/*.ps1

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

tests/Integration/**/*.ps1: Use DSCSQLTEST (Database Engine), SSRS (Reporting Services), and PBIRS (Power BI Report Server) instance names in CI integration tests
If an integration test requires a SQL Server Database Engine, start the Windows service in BeforeAll and stop it in AfterAll
In integration tests requiring a SQL Server DB, use Connect-SqlDscDatabaseEngine with correct CI credentials to open the session
Always call Disconnect-SqlDscDatabaseEngine after Connect-SqlDscDatabaseEngine in integration tests

Files:

  • tests/Integration/Commands/Get-SqlDscServerPermission.Integration.Tests.ps1
tests/[iI]ntegration/[cC]ommands/*.[iI]ntegration.[tT]ests.ps1

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

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

Files:

  • tests/Integration/Commands/Get-SqlDscServerPermission.Integration.Tests.ps1
tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1

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

tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1: Do not use mocking in integration tests; run against a real environment
Ensure integration tests cover all scenarios and code paths
In CI, use Get-ComputerName for computer names
Avoid using ExpectedMessage with Should -Throw assertions in Pester
When calling commands in integration tests, pass -Force where applicable to avoid prompts
Use -ErrorAction Stop on commands in integration tests so failures surface immediately
Include the required setup block at the top of each integration test: the SuppressMessage param(), a BeforeDiscovery block that ensures DscResource.Test is available (or runs build.ps1 -Tasks 'noop' and imports it), and a BeforeAll block that sets $script:moduleName and imports the module under test with -Force -ErrorAction Stop

Files:

  • tests/Integration/Commands/Get-SqlDscServerPermission.Integration.Tests.ps1

⚙️ CodeRabbit configuration file

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

Requirements

  • Location Commands: tests/Integration/Commands/{CommandName}.Integration.Tests.ps1
  • Location Resources: tests/Integration/Resources/{ResourceName}.Integration.Tests.ps1
  • No mocking - real environment only
  • Cover all scenarios and code paths
  • Use Get-ComputerName for computer names in CI
  • Avoid ExpectedMessage for Should -Throw assertions
  • Only run integration tests in CI unless explicitly instructed.
  • Call commands with -Force parameter where applicable (avoids prompting).
  • Use -ErrorAction Stop on commands so failures surface immediately

Required Setup Block

[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification = 'Suppressing this rule because Script Analyzer does not understand Pester syntax.')]
param ()

BeforeDiscovery {
    try
    {
        if (-not (Get-Module -Name 'DscResource.Test'))
        {
            # Assumes dependencies have been resolved, so if this module is not available, run 'noop' task.
            if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable))
            {
                # Redirect all streams to $null, except the error stream (stream 2)
                & "$PSScriptRoot/../../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null
            }

            # If the dependencies have not been resolved, this will throw an error.
            Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop'
        }
    }
    catch [System.IO.FileNotFoundException]
    {
        throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks build" first.'
    }
}

BeforeAll {
    $script:moduleName = '{MyModuleName}'

    Import-Module -Name $script:moduleName -Force -ErrorAction 'Stop'
}

Files:

  • tests/Integration/Commands/Get-SqlDscServerPermission.Integration.Tests.ps1
**/*.[Tt]ests.ps1

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

**/*.[Tt]ests.ps1: All public commands, private functions and classes must have unit tests
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/Integration/Commands/Get-SqlDscServerPermission.Integration.Tests.ps1
  • tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1

⚙️ CodeRabbit configuration file

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

Core Requirements

  • All public commands, private functions and classes must have unit tests
  • All public commands and class-based resources must have integration tests
  • Use Pester v5 syntax only
  • Test code only inside Describe blocks
  • Assertions only in It blocks
  • Never test verbose messages, debug messages or parameter binding behavior
  • Pass all mandatory parameters to avoid prompts

Requirements

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

Naming

  • One Describe block per file matching the tested entity name
  • Context descriptions start with 'When'
  • It descriptions start with 'Should', must not contain 'when'
  • Mock variables prefix: 'mock'

Structure & Scope

  • Public commands: Never use InModuleScope (unless retrieving localized strings)
  • Private functions/class resources: Always use InModuleScope
  • Each class method = separate Context block
  • Each scenario = separate Context block
  • Use nested Context blocks for complex scenarios
  • Mocking in BeforeAll (BeforeEach only when required)
  • Setup/teardown in BeforeAll,BeforeEach/AfterAll,AfterEach close to usage

Syntax Rules

  • PascalCase: Describe, Context, It, Should, BeforeAll, BeforeEach, AfterAll, AfterEach
  • 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 `InModule...

Files:

  • tests/Integration/Commands/Get-SqlDscServerPermission.Integration.Tests.ps1
  • tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1
tests/Integration/Commands/*.Integration.Tests.ps1

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

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

Files:

  • tests/Integration/Commands/Get-SqlDscServerPermission.Integration.Tests.ps1
tests/Integration/**/*.Integration.Tests.ps1

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

Add integration tests for all public commands and resources

Files:

  • tests/Integration/Commands/Get-SqlDscServerPermission.Integration.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/Public/Get-SqlDscServerPermission.Tests.ps1
tests/Unit/Public/*.Tests.ps1

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

tests/Unit/Public/*.Tests.ps1: For public commands, never use InModuleScope (except when retrieving localized strings)
Place public command unit tests under tests/Unit/Public/{Name}.Tests.ps1

Files:

  • tests/Unit/Public/Get-SqlDscServerPermission.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/Public/Get-SqlDscServerPermission.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/Public/Get-SqlDscServerPermission.Tests.ps1
🧠 Learnings (25)
📚 Learning: 2025-08-29T17:20:42.266Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-08-29T17:20:42.266Z
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:

  • tests/Integration/Commands/Get-SqlDscServerPermission.Integration.Tests.ps1
  • tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1
📚 Learning: 2025-08-29T17:25:09.959Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines.instructions.md:0-0
Timestamp: 2025-08-29T17:25:09.959Z
Learning: Applies to tests/Integration/**/*.Integration.Tests.ps1 : Add integration tests for all public commands and resources

Applied to files:

  • tests/Integration/Commands/Get-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:22:07.610Z
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.610Z
Learning: Applies to tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1 : Include the required setup block at the top of each integration test: the SuppressMessage param(), a BeforeDiscovery block that ensures DscResource.Test is available (or runs build.ps1 -Tasks 'noop' and imports it), and a BeforeAll block that sets $script:moduleName and imports the module under test with -Force -ErrorAction Stop

Applied to files:

  • tests/Integration/Commands/Get-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:20:42.266Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-08-29T17:20:42.266Z
Learning: Applies to tests/Integration/**/*.ps1 : In integration tests requiring a SQL Server DB, use Connect-SqlDscDatabaseEngine with correct CI credentials to open the session

Applied to files:

  • tests/Integration/Commands/Get-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:19:40.951Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-29T17:19:40.951Z
Learning: Applies to **/*Integration.Tests.ps1 : Always add and structure Integration tests according to the integration testing guidelines

Applied to files:

  • tests/Integration/Commands/Get-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:22:07.610Z
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.610Z
Learning: Applies to tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1 : Ensure integration tests cover all scenarios and code paths

Applied to files:

  • tests/Integration/Commands/Get-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:20:42.266Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-08-29T17:20:42.266Z
Learning: Applies to tests/Integration/**/*.ps1 : Always call Disconnect-SqlDscDatabaseEngine after Connect-SqlDscDatabaseEngine in integration tests

Applied to files:

  • tests/Integration/Commands/Get-SqlDscServerPermission.Integration.Tests.ps1
  • tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1
📚 Learning: 2025-08-29T17:25:09.959Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines.instructions.md:0-0
Timestamp: 2025-08-29T17:25:09.959Z
Learning: Applies to tests/Integration/Commands/*.Integration.Tests.ps1 : Place command integration tests in tests/Integration/Commands/{CommandName}.Integration.Tests.ps1

Applied to files:

  • tests/Integration/Commands/Get-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:22:07.610Z
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.610Z
Learning: Applies to tests/[iI]ntegration/[cC]ommands/*.[iI]ntegration.[tT]ests.ps1 : Place command integration tests at tests/Integration/Commands/{CommandName}.Integration.Tests.ps1

Applied to files:

  • tests/Integration/Commands/Get-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:20:42.266Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-08-29T17:20:42.266Z
Learning: Applies to tests/Integration/**/*.ps1 : If an integration test requires a SQL Server Database Engine, start the Windows service in BeforeAll and stop it in AfterAll

Applied to files:

  • tests/Integration/Commands/Get-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:20:42.266Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-08-29T17:20:42.266Z
Learning: Applies to tests/Unit/**/*.ps1 : Unit tests must set $env:SqlServerDscCI = $true in BeforeAll and remove it in AfterAll

Applied to files:

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

Applied to files:

  • tests/Integration/Commands/Get-SqlDscServerPermission.Integration.Tests.ps1
  • tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1
📚 Learning: 2025-08-17T10:13:30.079Z
Learnt from: johlju
PR: dsccommunity/SqlServerDsc#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/Integration/Commands/Get-SqlDscServerPermission.Integration.Tests.ps1
  • tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1
📚 Learning: 2025-08-16T13:22:15.230Z
Learnt from: johlju
PR: dsccommunity/SqlServerDsc#2134
File: tests/Unit/Public/Get-SqlDscLogin.Tests.ps1:78-93
Timestamp: 2025-08-16T13:22:15.230Z
Learning: In PowerShell unit tests for parameter validation in SqlServerDsc, accessing parameter attributes directly like `$cmd.Parameters['ParameterName'].Attributes.Mandatory` works correctly because PowerShell automatically iterates through the array and returns the property values. Additional filtering to ParameterAttribute is not necessary when the parameter structure is known and controlled.

Applied to files:

  • tests/Integration/Commands/Get-SqlDscServerPermission.Integration.Tests.ps1
  • tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1
📚 Learning: 2025-08-29T17:23:02.585Z
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.585Z
Learning: Applies to **/*.[Tt]ests.ps1 : Use assertions only inside It blocks

Applied to files:

  • tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1
📚 Learning: 2025-08-29T17:23:02.585Z
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.585Z
Learning: Applies to **/*.[Tt]ests.ps1 : Keep results and assertions in the same It block

Applied to files:

  • tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1
📚 Learning: 2025-08-29T17:23:02.585Z
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.585Z
Learning: Applies to **/*.[Tt]ests.ps1 : Do not use Assert-MockCalled; use Should -Invoke instead

Applied to files:

  • tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1
📚 Learning: 2025-08-29T17:19:40.951Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-29T17:19:40.951Z
Learning: Applies to **/*.Tests.ps1 : Follow test patterns strictly for maintainability in Pester tests

Applied to files:

  • tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1
📚 Learning: 2025-08-29T17:23:02.585Z
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.585Z
Learning: Applies to **/*.[Tt]ests.ps1 : Omit -MockWith when returning $null

Applied to files:

  • tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1
📚 Learning: 2025-08-29T17:23:02.585Z
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.585Z
Learning: Applies to **/*.[Tt]ests.ps1 : Never add an empty -MockWith block

Applied to files:

  • tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1
📚 Learning: 2025-08-29T17:23:02.585Z
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.585Z
Learning: Applies to **/*.[Tt]ests.ps1 : Never use Mock inside an InModuleScope block

Applied to files:

  • tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1
📚 Learning: 2025-08-29T17:23:02.585Z
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.585Z
Learning: Applies to **/*.[Tt]ests.ps1 : Do not use Should -Not -Throw; invoke commands directly

Applied to files:

  • tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1
📚 Learning: 2025-08-29T17:22:07.610Z
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.610Z
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/Public/Get-SqlDscServerPermission.Tests.ps1
📚 Learning: 2025-08-29T17:23:02.585Z
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.585Z
Learning: Applies to **/*.[Tt]ests.ps1 : Context descriptions start with 'When'

Applied to files:

  • tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1
📚 Learning: 2025-08-29T17:23:02.585Z
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.585Z
Learning: Applies to **/*.[Tt]ests.ps1 : Set $PSDefaultParameterValues for Mock:ModuleName, Should:ModuleName, and InModuleScope:ModuleName

Applied to files:

  • tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1
🧬 Code graph analysis (3)
source/Public/Get-SqlDscServerPermission.ps1 (1)
tests/Unit/Stubs/SMO.cs (7)
  • ServerPermissionSet (184-206)
  • ServerPermissionInfo (212-227)
  • Microsoft (332-340)
  • ServerPermissionInfo (214-218)
  • ServerPermissionSet (188-198)
  • ServerPermissionInfo (220-223)
  • Login (379-532)
tests/Integration/Commands/Get-SqlDscServerPermission.Integration.Tests.ps1 (1)
tests/Unit/Stubs/SMO.cs (4)
  • ServerPermissionSet (184-206)
  • ServerPermissionInfo (212-227)
  • ServerPermissionSet (188-198)
  • ServerPermissionInfo (214-218)
tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1 (1)
tests/Unit/Stubs/SMO.cs (5)
  • ServerPermissionSet (184-206)
  • ServerPermissionSet (188-198)
  • ServerPermissionInfo (212-227)
  • Microsoft (332-340)
  • Microsoft (12-1048)
⏰ 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). (1)
  • GitHub Check: dsccommunity.SqlServerDsc (Build Package Module)
🔇 Additional comments (7)
tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1 (5)

52-86: Good negative-path coverage with localized error verification.

Mocks, localized message retrieval, and dual ErrorAction behaviors are exercised correctly. Nice adherence to guidelines (no InModuleScope mocking, no verbose tests).


88-156: Login-path happy cases look solid.

ScriptMethod stubbing for EnumServerPermissions yields deterministic objects; assertions are precise and readable. Pipeline variant is covered.


158-226: Great addition: server-role path coverage.

Covers role identification, permissions shape (ViewServerState/ControlServer), and pipeline input. This meaningfully validates the new capability.


328-349: Same coupling concern when PrincipalType includes both.

If the cmdlet later short-circuits upon finding a login, this test will fail. Consider asserting at most once for the secondary check.
[ suggest_optional_refactor ]

-                Should -Invoke -CommandName Test-SqlDscIsRole -ParameterFilter {
-                    $ServerObject.Equals($mockServerObject) -and $Name -eq 'TestPrincipal'
-                } -Exactly -Times 1
+                Should -Invoke -CommandName Test-SqlDscIsRole -AtMost -Times 1

547-628: Parameter-set validation is thorough and follows our patterns.

Checks for parameter strings, mandatory flags, pipeline acceptance, and ValidateSet are concise and aligned with previous tests in this repo.

source/Public/Get-SqlDscServerPermission.ps1 (2)

101-125: Public surface looks correct.

Parameter sets, types, and ValidateSet for PrincipalType align with the new behavior. Good use of pipeline input per set.


194-199: Error path and typed return are consistent with repo patterns.

Uses localized string, category, and error id; returns a typed array. All good.

…IntegrationTestRole_Persistent role, enhancing test coverage and accuracy.
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

Caution

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

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

133-136: Bug: $roleObject is undefined in BeforeEach

This call uses $roleObject but only $script:roleObject is set. Param binding will pass $null and can fail.

- Revoke-SqlDscServerPermission -ServerRole $roleObject -Permission 'ViewServerState' -Force -ErrorAction 'SilentlyContinue'
+ Revoke-SqlDscServerPermission -ServerRole $script:roleObject -Permission 'ViewServerState' -Force -ErrorAction 'SilentlyContinue'
♻️ Duplicate comments (1)
tests/Integration/Commands/Grant-SqlDscServerPermission.Integration.Tests.ps1 (1)

34-36: Prevent race after service start: wait for Running

Add an explicit wait so Connect doesn’t race the service startup.

 Start-Service -Name 'MSSQL$DSCSQLTEST' -Verbose -ErrorAction 'Stop'
+(Get-Service -Name 'MSSQL$DSCSQLTEST' -ErrorAction 'Stop').WaitForStatus('Running', [TimeSpan]::FromMinutes(1))
🧹 Nitpick comments (2)
source/Public/Grant-SqlDscServerPermission.ps1 (1)

109-109: Consistent permission list formatting (use ", " everywhere)

Join with a space after the comma to match the catch block and other commands.

- $verboseDescriptionMessage = $script:localizedData.ServerPermission_Grant_ShouldProcessVerboseDescription -f $principalName, $serverObject.InstanceName, ($Permission -join ',')
+ $verboseDescriptionMessage = $script:localizedData.ServerPermission_Grant_ShouldProcessVerboseDescription -f $principalName, $serverObject.InstanceName, ($Permission -join ', ')
source/Public/Deny-SqlDscServerPermission.ps1 (1)

94-94: Normalize permission list formatting (add a space after commas)

Align delimiter with Grant and ensure consistent output.

- $verboseDescriptionMessage = $script:localizedData.ServerPermission_Deny_ShouldProcessVerboseDescription -f $principalName, $serverObject.InstanceName, ($Permission -join ',')
+ $verboseDescriptionMessage = $script:localizedData.ServerPermission_Deny_ShouldProcessVerboseDescription -f $principalName, $serverObject.InstanceName, ($Permission -join ', ')
- $errorMessage = $script:localizedData.ServerPermission_Deny_FailedToDenyPermission -f $principalName, $serverObject.InstanceName, ($Permission -join ',')
+ $errorMessage = $script:localizedData.ServerPermission_Deny_FailedToDenyPermission -f $principalName, $serverObject.InstanceName, ($Permission -join ', ')

Also applies to: 113-113

📜 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 e97c1fd and b03149d.

📒 Files selected for processing (5)
  • source/Public/Deny-SqlDscServerPermission.ps1 (1 hunks)
  • source/Public/Grant-SqlDscServerPermission.ps1 (1 hunks)
  • source/Public/Revoke-SqlDscServerPermission.ps1 (1 hunks)
  • source/en-US/SqlServerDsc.strings.psd1 (2 hunks)
  • tests/Integration/Commands/Grant-SqlDscServerPermission.Integration.Tests.ps1 (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • source/Public/Revoke-SqlDscServerPermission.ps1
  • source/en-US/SqlServerDsc.strings.psd1
🧰 Additional context used
📓 Path-based instructions (15)
**/*.{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/Public/Deny-SqlDscServerPermission.ps1
  • source/Public/Grant-SqlDscServerPermission.ps1
  • tests/Integration/Commands/Grant-SqlDscServerPermission.Integration.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/Public/Deny-SqlDscServerPermission.ps1
  • source/Public/Grant-SqlDscServerPermission.ps1
  • tests/Integration/Commands/Grant-SqlDscServerPermission.Integration.Tests.ps1
source/**/*.ps1

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

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

Files:

  • source/Public/Deny-SqlDscServerPermission.ps1
  • source/Public/Grant-SqlDscServerPermission.ps1

⚙️ CodeRabbit configuration file

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

Requirements

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

String Files

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

Key Naming Patterns

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

String Format

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

String IDs

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

Usage

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

Files:

  • source/Public/Deny-SqlDscServerPermission.ps1
  • source/Public/Grant-SqlDscServerPermission.ps1
source/Public/*.ps1

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

source/Public/*.ps1: Place public commands in source/Public/{CommandName}.ps1
Separate reusable logic into private functions (keep public commands thin)

Files:

  • source/Public/Deny-SqlDscServerPermission.ps1
  • source/Public/Grant-SqlDscServerPermission.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/Public/Deny-SqlDscServerPermission.ps1
  • source/Public/Grant-SqlDscServerPermission.ps1
  • tests/Integration/Commands/Grant-SqlDscServerPermission.Integration.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/Public/Deny-SqlDscServerPermission.ps1
  • source/Public/Grant-SqlDscServerPermission.ps1
  • tests/Integration/Commands/Grant-SqlDscServerPermission.Integration.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/Public/Deny-SqlDscServerPermission.ps1
  • source/Public/Grant-SqlDscServerPermission.ps1
  • tests/Integration/Commands/Grant-SqlDscServerPermission.Integration.Tests.ps1
**/*.Tests.ps1

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

Follow test patterns strictly for maintainability in Pester tests

Files:

  • tests/Integration/Commands/Grant-SqlDscServerPermission.Integration.Tests.ps1
**/*Integration.Tests.ps1

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

Always add and structure Integration tests according to the integration testing guidelines

Files:

  • tests/Integration/Commands/Grant-SqlDscServerPermission.Integration.Tests.ps1
tests/Integration/**/*.ps1

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

tests/Integration/**/*.ps1: Use DSCSQLTEST (Database Engine), SSRS (Reporting Services), and PBIRS (Power BI Report Server) instance names in CI integration tests
If an integration test requires a SQL Server Database Engine, start the Windows service in BeforeAll and stop it in AfterAll
In integration tests requiring a SQL Server DB, use Connect-SqlDscDatabaseEngine with correct CI credentials to open the session
Always call Disconnect-SqlDscDatabaseEngine after Connect-SqlDscDatabaseEngine in integration tests

Files:

  • tests/Integration/Commands/Grant-SqlDscServerPermission.Integration.Tests.ps1
tests/[iI]ntegration/[cC]ommands/*.[iI]ntegration.[tT]ests.ps1

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

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

Files:

  • tests/Integration/Commands/Grant-SqlDscServerPermission.Integration.Tests.ps1
tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1

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

tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1: Do not use mocking in integration tests; run against a real environment
Ensure integration tests cover all scenarios and code paths
In CI, use Get-ComputerName for computer names
Avoid using ExpectedMessage with Should -Throw assertions in Pester
When calling commands in integration tests, pass -Force where applicable to avoid prompts
Use -ErrorAction Stop on commands in integration tests so failures surface immediately
Include the required setup block at the top of each integration test: the SuppressMessage param(), a BeforeDiscovery block that ensures DscResource.Test is available (or runs build.ps1 -Tasks 'noop' and imports it), and a BeforeAll block that sets $script:moduleName and imports the module under test with -Force -ErrorAction Stop

Files:

  • tests/Integration/Commands/Grant-SqlDscServerPermission.Integration.Tests.ps1

⚙️ CodeRabbit configuration file

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

Requirements

  • Location Commands: tests/Integration/Commands/{CommandName}.Integration.Tests.ps1
  • Location Resources: tests/Integration/Resources/{ResourceName}.Integration.Tests.ps1
  • No mocking - real environment only
  • Cover all scenarios and code paths
  • Use Get-ComputerName for computer names in CI
  • Avoid ExpectedMessage for Should -Throw assertions
  • Only run integration tests in CI unless explicitly instructed.
  • Call commands with -Force parameter where applicable (avoids prompting).
  • Use -ErrorAction Stop on commands so failures surface immediately

Required Setup Block

[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification = 'Suppressing this rule because Script Analyzer does not understand Pester syntax.')]
param ()

BeforeDiscovery {
    try
    {
        if (-not (Get-Module -Name 'DscResource.Test'))
        {
            # Assumes dependencies have been resolved, so if this module is not available, run 'noop' task.
            if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable))
            {
                # Redirect all streams to $null, except the error stream (stream 2)
                & "$PSScriptRoot/../../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null
            }

            # If the dependencies have not been resolved, this will throw an error.
            Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop'
        }
    }
    catch [System.IO.FileNotFoundException]
    {
        throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks build" first.'
    }
}

BeforeAll {
    $script:moduleName = '{MyModuleName}'

    Import-Module -Name $script:moduleName -Force -ErrorAction 'Stop'
}

Files:

  • tests/Integration/Commands/Grant-SqlDscServerPermission.Integration.Tests.ps1
**/*.[Tt]ests.ps1

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

**/*.[Tt]ests.ps1: All public commands, private functions and classes must have unit tests
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/Integration/Commands/Grant-SqlDscServerPermission.Integration.Tests.ps1

⚙️ CodeRabbit configuration file

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

Core Requirements

  • All public commands, private functions and classes must have unit tests
  • All public commands and class-based resources must have integration tests
  • Use Pester v5 syntax only
  • Test code only inside Describe blocks
  • Assertions only in It blocks
  • Never test verbose messages, debug messages or parameter binding behavior
  • Pass all mandatory parameters to avoid prompts

Requirements

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

Naming

  • One Describe block per file matching the tested entity name
  • Context descriptions start with 'When'
  • It descriptions start with 'Should', must not contain 'when'
  • Mock variables prefix: 'mock'

Structure & Scope

  • Public commands: Never use InModuleScope (unless retrieving localized strings)
  • Private functions/class resources: Always use InModuleScope
  • Each class method = separate Context block
  • Each scenario = separate Context block
  • Use nested Context blocks for complex scenarios
  • Mocking in BeforeAll (BeforeEach only when required)
  • Setup/teardown in BeforeAll,BeforeEach/AfterAll,AfterEach close to usage

Syntax Rules

  • PascalCase: Describe, Context, It, Should, BeforeAll, BeforeEach, AfterAll, AfterEach
  • 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 `InModule...

Files:

  • tests/Integration/Commands/Grant-SqlDscServerPermission.Integration.Tests.ps1
tests/Integration/Commands/*.Integration.Tests.ps1

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

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

Files:

  • tests/Integration/Commands/Grant-SqlDscServerPermission.Integration.Tests.ps1
tests/Integration/**/*.Integration.Tests.ps1

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

Add integration tests for all public commands and resources

Files:

  • tests/Integration/Commands/Grant-SqlDscServerPermission.Integration.Tests.ps1
🧠 Learnings (8)
📚 Learning: 2025-08-29T17:20:42.266Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-08-29T17:20:42.266Z
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:

  • tests/Integration/Commands/Grant-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:20:42.266Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-08-29T17:20:42.266Z
Learning: Applies to tests/Integration/**/*.ps1 : In integration tests requiring a SQL Server DB, use Connect-SqlDscDatabaseEngine with correct CI credentials to open the session

Applied to files:

  • tests/Integration/Commands/Grant-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:20:42.266Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-08-29T17:20:42.266Z
Learning: Applies to tests/Integration/**/*.ps1 : Always call Disconnect-SqlDscDatabaseEngine after Connect-SqlDscDatabaseEngine in integration tests

Applied to files:

  • tests/Integration/Commands/Grant-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:20:42.266Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-08-29T17:20:42.266Z
Learning: Applies to tests/Integration/**/*.ps1 : If an integration test requires a SQL Server Database Engine, start the Windows service in BeforeAll and stop it in AfterAll

Applied to files:

  • tests/Integration/Commands/Grant-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:20:42.266Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-08-29T17:20:42.266Z
Learning: Applies to tests/Unit/**/*.ps1 : Unit tests must set $env:SqlServerDscCI = $true in BeforeAll and remove it in AfterAll

Applied to files:

  • tests/Integration/Commands/Grant-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:22:07.610Z
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.610Z
Learning: Applies to tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1 : Include the required setup block at the top of each integration test: the SuppressMessage param(), a BeforeDiscovery block that ensures DscResource.Test is available (or runs build.ps1 -Tasks 'noop' and imports it), and a BeforeAll block that sets $script:moduleName and imports the module under test with -Force -ErrorAction Stop

Applied to files:

  • tests/Integration/Commands/Grant-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:22:07.610Z
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.610Z
Learning: Applies to tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1 : Use -ErrorAction Stop on commands in integration tests so failures surface immediately

Applied to files:

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

Applied to files:

  • tests/Integration/Commands/Grant-SqlDscServerPermission.Integration.Tests.ps1
🧬 Code graph analysis (3)
source/Public/Deny-SqlDscServerPermission.ps1 (1)
tests/Unit/Stubs/SMO.cs (6)
  • Revoke (346-348)
  • Microsoft (332-340)
  • Grant (342-344)
  • ServerPermissionInfo (212-227)
  • ServerPermissionSet (184-206)
  • ServerPermissionSet (188-198)
source/Public/Grant-SqlDscServerPermission.ps1 (1)
tests/Unit/Stubs/SMO.cs (7)
  • Grant (342-344)
  • ServerPermissionSet (184-206)
  • ServerPermissionInfo (212-227)
  • Grant (610-612)
  • ServerPermissionSet (188-198)
  • ServerPermissionInfo (214-218)
  • Microsoft (332-340)
tests/Integration/Commands/Grant-SqlDscServerPermission.Integration.Tests.ps1 (1)
tests/Unit/Stubs/SMO.cs (5)
  • ServerPermissionSet (184-206)
  • Grant (342-344)
  • ServerPermissionInfo (212-227)
  • Revoke (346-348)
  • ServerPermissionSet (188-198)
⏰ 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 (5)
source/Public/Grant-SqlDscServerPermission.ps1 (1)

135-142: Good error wrapping: preserve inner exception and use ErrorRecord

Creating an InvalidOperationException with the original exception as InnerException and passing the exception object into ErrorRecord is the right pattern. This improves diagnostics without changing the public surface.

source/Public/Deny-SqlDscServerPermission.ps1 (2)

115-121: Good error wrapping: preserve inner exception and use ErrorRecord

Same positive note as in Grant: inner exception + ErrorRecord improves troubleshootability.


120-120: Error ID prefix correct
‘DSDSP0001’ follows the verb-initial + SDSP (SQL DSC Server Permission) convention and aligns with the ServerPermission_Deny_FailedToDenyPermission localization key.

tests/Integration/Commands/Grant-SqlDscServerPermission.Integration.Tests.ps1 (2)

73-81: LGTM: robust permission verification

Filtering to the specific Grant entry and asserting a single match avoids ambiguity and matches SMO’s PermissionInfo shape.


66-66: The full parameter block will confirm whether a WithGrant switch exists. Once you have that output, we can determine if the test’s -WithGrant usage is valid or if the cmdlet needs updating.

…rameters for consistency. Improve try-finally block formatting for better readability.
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

Caution

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

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

151-158: Role test likely false-negative: ConnectSql not granted to role

You assert ConnectSql + ViewServerState for the role but only grant ViewServerState in BeforeAll. Fixed server roles don’t automatically confer explicit ConnectSql to custom roles, so the test can fail.

Apply:

-            $null = Grant-SqlDscServerPermission -ServerRole $roleObject -Permission @('ViewServerState') -Force -ErrorAction 'Stop'
+            $null = Grant-SqlDscServerPermission -ServerRole $roleObject -Permission @('ConnectSql', 'ViewServerState') -Force -ErrorAction 'Stop'
@@
-            $null = Revoke-SqlDscServerPermission -ServerRole $roleObject -Permission @('ViewServerState') -Force -ErrorAction 'SilentlyContinue'
+            $null = Revoke-SqlDscServerPermission -ServerRole $roleObject -Permission @('ConnectSql', 'ViewServerState') -Force -ErrorAction 'SilentlyContinue'

Also applies to: 160-172

♻️ Duplicate comments (1)
tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1 (1)

34-45: Solid setup; verify principal preconditions and note prior feedback is addressed

  • Service bring-up and the switch to -ErrorAction 'Stop' on Connect-SqlDscDatabaseEngine look good.
  • You rely on a pre-provisioned SQL login 'SqlAdmin' and a persistent role. Please verify their creation exists in repo to avoid order-coupling across tests.

Run to confirm principals are provisioned:

#!/usr/bin/env bash
# Check where SqlAdmin and SqlDscIntegrationTestRole_Persistent are created/ensured.
rg -n -C3 -i '\b(SqlAdmin|SqlDscIntegrationTestRole_Persistent)\b' tests scripts source
🧹 Nitpick comments (2)
tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1 (2)

52-56: Add -ErrorAction Stop to Disconnect for consistent failure surfacing

Disconnect should also fail fast.

Apply:

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

241-245: Add a mirror test for non-existent server role

Parity with the non-existent login case will strengthen coverage for role principals added by the PR.

Apply:

@@
     Context 'When testing non-existent principal' {
         It 'Should return false when testing permissions for non-existent login' {
@@
             $result | Should -BeFalse
         }
+
+        It 'Should return false when testing permissions for non-existent server role' {
+            # Construct a non-existent server role on the current server
+            $mockRole = [Microsoft.SqlServer.Management.Smo.ServerRole]::new($script:serverObject, 'NonExistentRole')
+
+            $result = Test-SqlDscServerPermission -ServerRole $mockRole -Grant -Permission @('ConnectSql') -ErrorAction 'Stop'
+
+            $result | Should -BeFalse
+        }
     }

I can add this test and push a commit if you prefer.

📜 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 b03149d and db2681f.

📒 Files selected for processing (1)
  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1 (8 hunks)
🧰 Additional context used
📓 Path-based instructions (13)
**/*.{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:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
**/*.Tests.ps1

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

Follow test patterns strictly for maintainability in Pester tests

Files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
**/*Integration.Tests.ps1

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

Always add and structure Integration tests according to the integration testing guidelines

Files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.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:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
tests/Integration/**/*.ps1

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

tests/Integration/**/*.ps1: Use DSCSQLTEST (Database Engine), SSRS (Reporting Services), and PBIRS (Power BI Report Server) instance names in CI integration tests
If an integration test requires a SQL Server Database Engine, start the Windows service in BeforeAll and stop it in AfterAll
In integration tests requiring a SQL Server DB, use Connect-SqlDscDatabaseEngine with correct CI credentials to open the session
Always call Disconnect-SqlDscDatabaseEngine after Connect-SqlDscDatabaseEngine in integration tests

Files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
tests/[iI]ntegration/[cC]ommands/*.[iI]ntegration.[tT]ests.ps1

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

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

Files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1

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

tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1: Do not use mocking in integration tests; run against a real environment
Ensure integration tests cover all scenarios and code paths
In CI, use Get-ComputerName for computer names
Avoid using ExpectedMessage with Should -Throw assertions in Pester
When calling commands in integration tests, pass -Force where applicable to avoid prompts
Use -ErrorAction Stop on commands in integration tests so failures surface immediately
Include the required setup block at the top of each integration test: the SuppressMessage param(), a BeforeDiscovery block that ensures DscResource.Test is available (or runs build.ps1 -Tasks 'noop' and imports it), and a BeforeAll block that sets $script:moduleName and imports the module under test with -Force -ErrorAction Stop

Files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1

⚙️ CodeRabbit configuration file

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

Requirements

  • Location Commands: tests/Integration/Commands/{CommandName}.Integration.Tests.ps1
  • Location Resources: tests/Integration/Resources/{ResourceName}.Integration.Tests.ps1
  • No mocking - real environment only
  • Cover all scenarios and code paths
  • Use Get-ComputerName for computer names in CI
  • Avoid ExpectedMessage for Should -Throw assertions
  • Only run integration tests in CI unless explicitly instructed.
  • Call commands with -Force parameter where applicable (avoids prompting).
  • Use -ErrorAction Stop on commands so failures surface immediately

Required Setup Block

[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification = 'Suppressing this rule because Script Analyzer does not understand Pester syntax.')]
param ()

BeforeDiscovery {
    try
    {
        if (-not (Get-Module -Name 'DscResource.Test'))
        {
            # Assumes dependencies have been resolved, so if this module is not available, run 'noop' task.
            if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable))
            {
                # Redirect all streams to $null, except the error stream (stream 2)
                & "$PSScriptRoot/../../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null
            }

            # If the dependencies have not been resolved, this will throw an error.
            Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop'
        }
    }
    catch [System.IO.FileNotFoundException]
    {
        throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks build" first.'
    }
}

BeforeAll {
    $script:moduleName = '{MyModuleName}'

    Import-Module -Name $script:moduleName -Force -ErrorAction 'Stop'
}

Files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
**/*.[Tt]ests.ps1

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

**/*.[Tt]ests.ps1: All public commands, private functions and classes must have unit tests
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/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1

⚙️ CodeRabbit configuration file

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

Core Requirements

  • All public commands, private functions and classes must have unit tests
  • All public commands and class-based resources must have integration tests
  • Use Pester v5 syntax only
  • Test code only inside Describe blocks
  • Assertions only in It blocks
  • Never test verbose messages, debug messages or parameter binding behavior
  • Pass all mandatory parameters to avoid prompts

Requirements

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

Naming

  • One Describe block per file matching the tested entity name
  • Context descriptions start with 'When'
  • It descriptions start with 'Should', must not contain 'when'
  • Mock variables prefix: 'mock'

Structure & Scope

  • Public commands: Never use InModuleScope (unless retrieving localized strings)
  • Private functions/class resources: Always use InModuleScope
  • Each class method = separate Context block
  • Each scenario = separate Context block
  • Use nested Context blocks for complex scenarios
  • Mocking in BeforeAll (BeforeEach only when required)
  • Setup/teardown in BeforeAll,BeforeEach/AfterAll,AfterEach close to usage

Syntax Rules

  • PascalCase: Describe, Context, It, Should, BeforeAll, BeforeEach, AfterAll, AfterEach
  • 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 `InModule...

Files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
tests/Integration/Commands/*.Integration.Tests.ps1

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

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

Files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.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:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
tests/Integration/**/*.Integration.Tests.ps1

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

Add integration tests for all public commands and resources

Files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.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:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.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:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
🧠 Learnings (10)
📚 Learning: 2025-08-29T17:20:42.266Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-08-29T17:20:42.266Z
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:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:20:42.266Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-08-29T17:20:42.266Z
Learning: Applies to tests/Unit/**/*.ps1 : Unit tests must set $env:SqlServerDscCI = $true in BeforeAll and remove it in AfterAll

Applied to files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:20:42.266Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-08-29T17:20:42.266Z
Learning: Applies to tests/Integration/**/*.ps1 : If an integration test requires a SQL Server Database Engine, start the Windows service in BeforeAll and stop it in AfterAll

Applied to files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:20:42.266Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-08-29T17:20:42.266Z
Learning: Applies to tests/Integration/**/*.ps1 : In integration tests requiring a SQL Server DB, use Connect-SqlDscDatabaseEngine with correct CI credentials to open the session

Applied to files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:20:42.266Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-08-29T17:20:42.266Z
Learning: Applies to tests/Integration/**/*.ps1 : Always call Disconnect-SqlDscDatabaseEngine after Connect-SqlDscDatabaseEngine in integration tests

Applied to files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-17T10:13:30.079Z
Learnt from: johlju
PR: dsccommunity/SqlServerDsc#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/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:22:07.610Z
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.610Z
Learning: Applies to tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1 : Include the required setup block at the top of each integration test: the SuppressMessage param(), a BeforeDiscovery block that ensures DscResource.Test is available (or runs build.ps1 -Tasks 'noop' and imports it), and a BeforeAll block that sets $script:moduleName and imports the module under test with -Force -ErrorAction Stop

Applied to files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:22:07.610Z
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.610Z
Learning: Applies to tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1 : Use -ErrorAction Stop on commands in integration tests so failures surface immediately

Applied to files:

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

Applied to files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:25:09.959Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines.instructions.md:0-0
Timestamp: 2025-08-29T17:25:09.959Z
Learning: Applies to tests/Integration/**/*.Integration.Tests.ps1 : Add integration tests for all public commands and resources

Applied to files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
🧬 Code graph analysis (1)
tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1 (1)
tests/Unit/Stubs/SMO.cs (7)
  • ServerPermissionSet (184-206)
  • Login (379-532)
  • ServerPermissionSet (188-198)
  • Microsoft (12-1048)
  • ServerPermissionInfo (212-227)
  • Microsoft (1086-1497)
  • Server (278-373)
⏰ 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
🔇 Additional comments (7)
tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1 (7)

32-32: Scope/tags LGTM

Describe header and version tags look correct for CI gating.


73-106: Grant checks for login look correct

Good coverage of positive/negative cases and pipeline input.


113-126: Ephemeral login scenario is clean and self-contained

Nice use of try/finally with Force and cleanup suppression.


133-145: ExactMatch paths are accurate

Covers both subset and exact parity.


181-187: Deny setup/teardown for login is correct

Cleans up after itself and uses -ErrorAction as recommended.


192-202: Deny assertions are precise

Good differentiation between existing and non-existing denied permission.


221-231: Grant WithGrant scenario is well-covered

Covers the WithGrant path for both presence and absence.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

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

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

151-153: Likely false positive: role test expects ConnectSql but it isn’t granted to the role

Server roles do not inherit CONNECT SQL from public; explicitly grant it in setup or adjust expected permissions to match setup.

Apply one of:

-            $null = Grant-SqlDscServerPermission -ServerRole $roleObject -Permission @('ViewServerState') -Force -ErrorAction 'Stop'
+            $null = Grant-SqlDscServerPermission -ServerRole $roleObject -Permission @('ConnectSql','ViewServerState') -Force -ErrorAction 'Stop'

Or update the assertions to only include 'ViewServerState'.

♻️ Duplicate comments (1)
tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1 (1)

37-45: Connection setup LGTM (and prior -ErrorAction Stop feedback addressed)

Using DSCSQLTEST, SqlAdmin credential, and -ErrorAction 'Stop' on Connect is correct and consistent with guidelines.

🧹 Nitpick comments (2)
tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1 (2)

32-32: Add companion integration tests for Get-SqlDscServerPermission per PR objective #2063

This file exercises Test-SqlDscServerPermission; please add/get-confirm the corresponding Get-SqlDscServerPermission integration tests (valid/invalid login and server role, including ByName and pipeline scenarios). I can generate a ready-to-drop test skeleton if helpful.


113-116: Avoid try/finally for cleanup; use scoped setup/teardown

Refactor the temporary-login test into its own Context with BeforeAll/AfterAll to meet test guidelines.

Apply:

-        It 'Should return true when testing for empty permission collection on principal with no additional permissions' {
-            # Create a temporary login for this test to ensure it has no additional permissions
-            $tempLoginName = 'TempTestLogin_' + (Get-Random)
-            $tempLoginObject = New-SqlDscLogin -ServerObject $script:serverObject -Name $tempLoginName -SqlLogin -SecurePassword (ConvertTo-SecureString -String 'TempPassword123!' -AsPlainText -Force) -Force -PassThru -ErrorAction 'Stop'
-
-            try
-            {
-                # Test that empty permission collection returns true when no permissions are set
-                $result = Test-SqlDscServerPermission -Login $tempLoginObject -Grant -Permission @() -ErrorAction 'Stop'
-                $result | Should -BeTrue
-            }
-            finally
-            {
-                # Clean up temporary login
-                Remove-SqlDscLogin -Login $tempLoginObject -Force -ErrorAction 'SilentlyContinue'
-            }
-        }
+        Context 'When testing empty permission collection on new login' {
+            BeforeAll {
+                $script:tempLoginName = 'TempTestLogin_' + (Get-Random)
+                $script:tempLoginObject = New-SqlDscLogin -ServerObject $script:serverObject -Name $script:tempLoginName -SqlLogin -SecurePassword (ConvertTo-SecureString -String 'TempPassword123!' -AsPlainText -Force) -Force -PassThru -ErrorAction 'Stop'
+            }
+
+            AfterAll {
+                Remove-SqlDscLogin -Login $script:tempLoginObject -Force -ErrorAction 'SilentlyContinue'
+            }
+
+            It 'Should return true when testing for empty permission collection on principal with no additional permissions' {
+                $result = Test-SqlDscServerPermission -Login $script:tempLoginObject -Grant -Permission @() -ErrorAction 'Stop'
+                $result | Should -BeTrue
+            }
+        }

Also applies to: 123-126

📜 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 db2681f and cb0d2c7.

📒 Files selected for processing (1)
  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1 (8 hunks)
🧰 Additional context used
📓 Path-based instructions (13)
**/*.{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:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
**/*.Tests.ps1

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

Follow test patterns strictly for maintainability in Pester tests

Files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
**/*Integration.Tests.ps1

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

Always add and structure Integration tests according to the integration testing guidelines

Files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.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:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
tests/Integration/**/*.ps1

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

tests/Integration/**/*.ps1: Use DSCSQLTEST (Database Engine), SSRS (Reporting Services), and PBIRS (Power BI Report Server) instance names in CI integration tests
If an integration test requires a SQL Server Database Engine, start the Windows service in BeforeAll and stop it in AfterAll
In integration tests requiring a SQL Server DB, use Connect-SqlDscDatabaseEngine with correct CI credentials to open the session
Always call Disconnect-SqlDscDatabaseEngine after Connect-SqlDscDatabaseEngine in integration tests

Files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
tests/[iI]ntegration/[cC]ommands/*.[iI]ntegration.[tT]ests.ps1

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

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

Files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1

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

tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1: Do not use mocking in integration tests; run against a real environment
Ensure integration tests cover all scenarios and code paths
In CI, use Get-ComputerName for computer names
Avoid using ExpectedMessage with Should -Throw assertions in Pester
When calling commands in integration tests, pass -Force where applicable to avoid prompts
Use -ErrorAction Stop on commands in integration tests so failures surface immediately
Include the required setup block at the top of each integration test: the SuppressMessage param(), a BeforeDiscovery block that ensures DscResource.Test is available (or runs build.ps1 -Tasks 'noop' and imports it), and a BeforeAll block that sets $script:moduleName and imports the module under test with -Force -ErrorAction Stop

Files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1

⚙️ CodeRabbit configuration file

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

Requirements

  • Location Commands: tests/Integration/Commands/{CommandName}.Integration.Tests.ps1
  • Location Resources: tests/Integration/Resources/{ResourceName}.Integration.Tests.ps1
  • No mocking - real environment only
  • Cover all scenarios and code paths
  • Use Get-ComputerName for computer names in CI
  • Avoid ExpectedMessage for Should -Throw assertions
  • Only run integration tests in CI unless explicitly instructed.
  • Call commands with -Force parameter where applicable (avoids prompting).
  • Use -ErrorAction Stop on commands so failures surface immediately

Required Setup Block

[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification = 'Suppressing this rule because Script Analyzer does not understand Pester syntax.')]
param ()

BeforeDiscovery {
    try
    {
        if (-not (Get-Module -Name 'DscResource.Test'))
        {
            # Assumes dependencies have been resolved, so if this module is not available, run 'noop' task.
            if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable))
            {
                # Redirect all streams to $null, except the error stream (stream 2)
                & "$PSScriptRoot/../../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null
            }

            # If the dependencies have not been resolved, this will throw an error.
            Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop'
        }
    }
    catch [System.IO.FileNotFoundException]
    {
        throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks build" first.'
    }
}

BeforeAll {
    $script:moduleName = '{MyModuleName}'

    Import-Module -Name $script:moduleName -Force -ErrorAction 'Stop'
}

Files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
**/*.[Tt]ests.ps1

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

**/*.[Tt]ests.ps1: All public commands, private functions and classes must have unit tests
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/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1

⚙️ CodeRabbit configuration file

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

Core Requirements

  • All public commands, private functions and classes must have unit tests
  • All public commands and class-based resources must have integration tests
  • Use Pester v5 syntax only
  • Test code only inside Describe blocks
  • Assertions only in It blocks
  • Never test verbose messages, debug messages or parameter binding behavior
  • Pass all mandatory parameters to avoid prompts

Requirements

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

Naming

  • One Describe block per file matching the tested entity name
  • Context descriptions start with 'When'
  • It descriptions start with 'Should', must not contain 'when'
  • Mock variables prefix: 'mock'

Structure & Scope

  • Public commands: Never use InModuleScope (unless retrieving localized strings)
  • Private functions/class resources: Always use InModuleScope
  • Each class method = separate Context block
  • Each scenario = separate Context block
  • Use nested Context blocks for complex scenarios
  • Mocking in BeforeAll (BeforeEach only when required)
  • Setup/teardown in BeforeAll,BeforeEach/AfterAll,AfterEach close to usage

Syntax Rules

  • PascalCase: Describe, Context, It, Should, BeforeAll, BeforeEach, AfterAll, AfterEach
  • 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 `InModule...

Files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
tests/Integration/Commands/*.Integration.Tests.ps1

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

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

Files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.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:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
tests/Integration/**/*.Integration.Tests.ps1

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

Add integration tests for all public commands and resources

Files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.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:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.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:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
🧠 Learnings (10)
📚 Learning: 2025-08-29T17:20:42.266Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-08-29T17:20:42.266Z
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:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:20:42.266Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-08-29T17:20:42.266Z
Learning: Applies to tests/Integration/**/*.ps1 : In integration tests requiring a SQL Server DB, use Connect-SqlDscDatabaseEngine with correct CI credentials to open the session

Applied to files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:20:42.266Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-08-29T17:20:42.266Z
Learning: Applies to tests/Integration/**/*.ps1 : Always call Disconnect-SqlDscDatabaseEngine after Connect-SqlDscDatabaseEngine in integration tests

Applied to files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:20:42.266Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-08-29T17:20:42.266Z
Learning: Applies to tests/Unit/**/*.ps1 : Unit tests must set $env:SqlServerDscCI = $true in BeforeAll and remove it in AfterAll

Applied to files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:20:42.266Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-08-29T17:20:42.266Z
Learning: Applies to tests/Integration/**/*.ps1 : If an integration test requires a SQL Server Database Engine, start the Windows service in BeforeAll and stop it in AfterAll

Applied to files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-17T10:13:30.079Z
Learnt from: johlju
PR: dsccommunity/SqlServerDsc#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/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:22:07.610Z
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.610Z
Learning: Applies to tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1 : Use -ErrorAction Stop on commands in integration tests so failures surface immediately

Applied to files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:22:07.610Z
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.610Z
Learning: Applies to tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1 : Include the required setup block at the top of each integration test: the SuppressMessage param(), a BeforeDiscovery block that ensures DscResource.Test is available (or runs build.ps1 -Tasks 'noop' and imports it), and a BeforeAll block that sets $script:moduleName and imports the module under test with -Force -ErrorAction Stop

Applied to files:

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

Applied to files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:25:09.959Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines.instructions.md:0-0
Timestamp: 2025-08-29T17:25:09.959Z
Learning: Applies to tests/Integration/**/*.Integration.Tests.ps1 : Add integration tests for all public commands and resources

Applied to files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
🧬 Code graph analysis (1)
tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1 (1)
tests/Unit/Stubs/SMO.cs (6)
  • ServerPermissionSet (184-206)
  • Login (379-532)
  • ServerPermissionInfo (212-227)
  • ServerPermissionSet (188-198)
  • Microsoft (12-1048)
  • Microsoft (1086-1497)
⏰ 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 (9)
tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1 (9)

34-36: Good: starting DSCSQLTEST service up-front

Aligned with integration test guidelines to control the named instance lifecycle.


54-55: Good: stopping DSCSQLTEST in teardown

Keeps CI runners lean and matches guidance.


73-73: Login grant path coverage looks solid

Covers positive/negative, pipeline input, single-permission, and unknown-permission cases with -ErrorAction 'Stop'.

Also applies to: 81-81, 89-89, 97-97, 105-105


133-134: ExactMatch negative case reads correctly

Ensures superset fails when ExactMatch is requested.


142-143: ExactMatch positive case is appropriate

Validates equality semantics for the granted set.


181-181: Deny/Revoke setup and cleanup for login is correct

Uses -Force and appropriate error actions.

Also applies to: 186-186


192-192: Deny checks for present/absent permissions look good

Covers both sides of the deny path.

Also applies to: 200-200


221-221: Grant-with-grant scenarios are well covered

Validates both existence and absence paths with -WithGrant.

Also applies to: 229-229


241-241: Non-existent login negative case is appropriate

Constructing an SMO Login against the server object to simulate absence is a good pattern.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

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

⚠️ Outside diff range comments (1)
source/Public/Test-SqlDscServerPermission.ps1 (1)

159-173: Restore $ErrorActionPreference in a finally block

If Get-SqlDscServerPermission throws, $ErrorActionPreference remains 'Stop' for the session. Restore it in finally and remove the inline restore.

Apply:

@@
-            $ErrorActionPreference = $originalErrorActionPreference
+            # Restored in finally.
@@
-        catch
+        catch
         {
             # If the principal doesn't exist or there's another error, return false
             Write-Verbose -Message (
                 $script:localizedData.ServerPermission_Test_TestFailed -f $principalName, $_.Exception.Message
             )
 
             return $false
         }
+        finally
+        {
+            if ($null -ne $originalErrorActionPreference)
+            {
+                $ErrorActionPreference = $originalErrorActionPreference
+            }
+        }
♻️ Duplicate comments (2)
tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1 (2)

44-45: Good: Connect uses -ErrorAction 'Stop'

This resolves the earlier suggestion and aligns with integration test guidelines.


168-175: Add negative test for non-existent server role

Mirror the non-existent login test to cover invalid role scenario.

         It 'Should return false when role permissions do not match desired state' {
             $roleObject = Get-SqlDscRole -ServerObject $script:serverObject -Name $script:testRoleName -ErrorAction 'Stop'
 
             $result = Test-SqlDscServerPermission -Verbose -ServerRole $roleObject -Grant -Permission @('CreateAnyDatabase') -ErrorAction 'Stop'
 
             $result | Should -BeFalse
         }
+
+        It 'Should return false when testing permissions for non-existent server role' {
+            $mockRole = [Microsoft.SqlServer.Management.Smo.ServerRole]::new($script:serverObject, 'NonExistentRole')
+
+            $result = Test-SqlDscServerPermission -ServerRole $mockRole -Grant -Permission @('ConnectSql') -ErrorAction 'Stop'
+
+            $result | Should -BeFalse
+        }
🧹 Nitpick comments (4)
source/Public/Test-SqlDscServerPermission.ps1 (2)

176-180: Use Write-Debug for internal diagnostics (“no permissions found”)

Per guidelines, internal diagnostics should be debug-level. Keep localization as-is.

-                # TODO: Make this a debug message
-                Write-Verbose -Message (
+                Write-Debug -Message (
                     $script:localizedData.ServerPermission_Test_NoPermissionsFound -f $principalName
                 )

195-201: Emit permission snapshot as debug and avoid JSON truncation

Switch to Write-Debug and specify -Depth to prevent truncated JSON.

-            # Output verbose information about current permissions as compressed JSON
-            $currentPermissionsJson = $currentPermissions | ConvertTo-Json -Compress
-            # TODO: Make this a debug message
-            Write-Verbose -Message (
+            # Output diagnostic information about current permissions as compressed JSON
+            $currentPermissionsJson = $currentPermissions | ConvertTo-Json -Compress -Depth 5
+            Write-Debug -Message (
                 $script:localizedData.ServerPermission_Test_CurrentPermissions -f $principalName, $currentPermissionsJson
             )
tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1 (2)

160-166: Duplicate/ambiguous It name and odd indentation

Two tests share the same description; rename for uniqueness and fix indentation.

-                It 'Should return true when role permissions match desired state' {
-            $roleObject = Get-SqlDscRole -ServerObject $script:serverObject -Name $script:testRoleName -ErrorAction 'Stop'
+        It 'Should return true when role permissions exactly match (ExactMatch)' {
+            $roleObject = Get-SqlDscRole -ServerObject $script:serverObject -Name $script:testRoleName -ErrorAction 'Stop'

152-158: Add pipeline test for ServerRole

Covers ValueFromPipeline for roles, mirroring the login pipeline test.

         It 'Should return true when role permissions match desired state' {
             $roleObject = Get-SqlDscRole -ServerObject $script:serverObject -Name $script:testRoleName -ErrorAction 'Stop'
 
             $result = Test-SqlDscServerPermission -Verbose -ServerRole $roleObject -Grant -Permission @('ConnectSql', 'ViewServerState') -ErrorAction 'Stop'
 
             $result | Should -BeTrue
         }
+
+        It 'Should accept ServerRole object from pipeline' {
+            $roleObject = Get-SqlDscRole -ServerObject $script:serverObject -Name $script:testRoleName -ErrorAction 'Stop'
+
+            $result = $roleObject | Test-SqlDscServerPermission -Grant -Permission @('ConnectSql') -ErrorAction 'Stop'
+
+            $result | Should -BeTrue
+        }
📜 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 8287508 and 1a3f34f.

📒 Files selected for processing (3)
  • source/Public/Test-SqlDscServerPermission.ps1 (2 hunks)
  • source/en-US/SqlServerDsc.strings.psd1 (1 hunks)
  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1 (7 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • source/en-US/SqlServerDsc.strings.psd1
🧰 Additional context used
📓 Path-based instructions (15)
**/*.{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/Public/Test-SqlDscServerPermission.ps1
  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.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/Public/Test-SqlDscServerPermission.ps1
  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
source/**/*.ps1

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

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

Files:

  • source/Public/Test-SqlDscServerPermission.ps1

⚙️ CodeRabbit configuration file

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

Requirements

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

String Files

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

Key Naming Patterns

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

String Format

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

String IDs

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

Usage

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

Files:

  • source/Public/Test-SqlDscServerPermission.ps1
source/Public/*.ps1

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

source/Public/*.ps1: Place public commands in source/Public/{CommandName}.ps1
Separate reusable logic into private functions (keep public commands thin)

Files:

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

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

Follow test patterns strictly for maintainability in Pester tests

Files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
**/*Integration.Tests.ps1

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

Always add and structure Integration tests according to the integration testing guidelines

Files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
tests/Integration/**/*.ps1

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

tests/Integration/**/*.ps1: Use DSCSQLTEST (Database Engine), SSRS (Reporting Services), and PBIRS (Power BI Report Server) instance names in CI integration tests
If an integration test requires a SQL Server Database Engine, start the Windows service in BeforeAll and stop it in AfterAll
In integration tests requiring a SQL Server DB, use Connect-SqlDscDatabaseEngine with correct CI credentials to open the session
Always call Disconnect-SqlDscDatabaseEngine after Connect-SqlDscDatabaseEngine in integration tests

Files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
tests/[iI]ntegration/[cC]ommands/*.[iI]ntegration.[tT]ests.ps1

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

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

Files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1

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

tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1: Do not use mocking in integration tests; run against a real environment
Ensure integration tests cover all scenarios and code paths
In CI, use Get-ComputerName for computer names
Avoid using ExpectedMessage with Should -Throw assertions in Pester
When calling commands in integration tests, pass -Force where applicable to avoid prompts
Use -ErrorAction Stop on commands in integration tests so failures surface immediately
Include the required setup block at the top of each integration test: the SuppressMessage param(), a BeforeDiscovery block that ensures DscResource.Test is available (or runs build.ps1 -Tasks 'noop' and imports it), and a BeforeAll block that sets $script:moduleName and imports the module under test with -Force -ErrorAction Stop

Files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1

⚙️ CodeRabbit configuration file

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

Requirements

  • Location Commands: tests/Integration/Commands/{CommandName}.Integration.Tests.ps1
  • Location Resources: tests/Integration/Resources/{ResourceName}.Integration.Tests.ps1
  • No mocking - real environment only
  • Cover all scenarios and code paths
  • Use Get-ComputerName for computer names in CI
  • Avoid ExpectedMessage for Should -Throw assertions
  • Only run integration tests in CI unless explicitly instructed.
  • Call commands with -Force parameter where applicable (avoids prompting).
  • Use -ErrorAction Stop on commands so failures surface immediately

Required Setup Block

[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification = 'Suppressing this rule because Script Analyzer does not understand Pester syntax.')]
param ()

BeforeDiscovery {
    try
    {
        if (-not (Get-Module -Name 'DscResource.Test'))
        {
            # Assumes dependencies have been resolved, so if this module is not available, run 'noop' task.
            if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable))
            {
                # Redirect all streams to $null, except the error stream (stream 2)
                & "$PSScriptRoot/../../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null
            }

            # If the dependencies have not been resolved, this will throw an error.
            Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop'
        }
    }
    catch [System.IO.FileNotFoundException]
    {
        throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks build" first.'
    }
}

BeforeAll {
    $script:moduleName = '{MyModuleName}'

    Import-Module -Name $script:moduleName -Force -ErrorAction 'Stop'
}

Files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
**/*.[Tt]ests.ps1

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

**/*.[Tt]ests.ps1: All public commands, private functions and classes must have unit tests
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/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1

⚙️ CodeRabbit configuration file

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

Core Requirements

  • All public commands, private functions and classes must have unit tests
  • All public commands and class-based resources must have integration tests
  • Use Pester v5 syntax only
  • Test code only inside Describe blocks
  • Assertions only in It blocks
  • Never test verbose messages, debug messages or parameter binding behavior
  • Pass all mandatory parameters to avoid prompts

Requirements

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

Naming

  • One Describe block per file matching the tested entity name
  • Context descriptions start with 'When'
  • It descriptions start with 'Should', must not contain 'when'
  • Mock variables prefix: 'mock'

Structure & Scope

  • Public commands: Never use InModuleScope (unless retrieving localized strings)
  • Private functions/class resources: Always use InModuleScope
  • Each class method = separate Context block
  • Each scenario = separate Context block
  • Use nested Context blocks for complex scenarios
  • Mocking in BeforeAll (BeforeEach only when required)
  • Setup/teardown in BeforeAll,BeforeEach/AfterAll,AfterEach close to usage

Syntax Rules

  • PascalCase: Describe, Context, It, Should, BeforeAll, BeforeEach, AfterAll, AfterEach
  • 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 `InModule...

Files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
tests/Integration/Commands/*.Integration.Tests.ps1

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

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

Files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
tests/Integration/**/*.Integration.Tests.ps1

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

Add integration tests for all public commands and resources

Files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
🧠 Learnings (11)
📓 Common learnings
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-08-29T17:20:42.266Z
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
📚 Learning: 2025-08-29T17:20:42.266Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-08-29T17:20:42.266Z
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:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:20:42.266Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-08-29T17:20:42.266Z
Learning: Applies to tests/Integration/**/*.ps1 : In integration tests requiring a SQL Server DB, use Connect-SqlDscDatabaseEngine with correct CI credentials to open the session

Applied to files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:20:42.266Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-08-29T17:20:42.266Z
Learning: Applies to tests/Integration/**/*.ps1 : Always call Disconnect-SqlDscDatabaseEngine after Connect-SqlDscDatabaseEngine in integration tests

Applied to files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:20:42.266Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-08-29T17:20:42.266Z
Learning: Applies to tests/Unit/**/*.ps1 : Unit tests must set $env:SqlServerDscCI = $true in BeforeAll and remove it in AfterAll

Applied to files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:20:42.266Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-08-29T17:20:42.266Z
Learning: Applies to tests/Integration/**/*.ps1 : If an integration test requires a SQL Server Database Engine, start the Windows service in BeforeAll and stop it in AfterAll

Applied to files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-17T10:13:30.079Z
Learnt from: johlju
PR: dsccommunity/SqlServerDsc#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/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:22:07.610Z
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.610Z
Learning: Applies to tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1 : Use -ErrorAction Stop on commands in integration tests so failures surface immediately

Applied to files:

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

Applied to files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:22:07.610Z
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.610Z
Learning: Applies to tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1 : Include the required setup block at the top of each integration test: the SuppressMessage param(), a BeforeDiscovery block that ensures DscResource.Test is available (or runs build.ps1 -Tasks 'noop' and imports it), and a BeforeAll block that sets $script:moduleName and imports the module under test with -Force -ErrorAction Stop

Applied to files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:25:09.959Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines.instructions.md:0-0
Timestamp: 2025-08-29T17:25:09.959Z
Learning: Applies to tests/Integration/**/*.Integration.Tests.ps1 : Add integration tests for all public commands and resources

Applied to files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
🧬 Code graph analysis (2)
source/Public/Test-SqlDscServerPermission.ps1 (1)
tests/Unit/Stubs/SMO.cs (4)
  • ServerPermissionSet (184-206)
  • ServerPermissionInfo (212-227)
  • ServerPermissionSet (188-198)
  • Microsoft (332-340)
tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1 (1)
tests/Unit/Stubs/SMO.cs (5)
  • ServerPermissionSet (184-206)
  • Microsoft (12-1048)
  • ServerPermissionSet (188-198)
  • ServerPermissionInfo (212-227)
  • Microsoft (1086-1497)
⏰ 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

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

♻️ Duplicate comments (2)
tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1 (2)

168-174: Add negative test for non-existent server role

Mirror the non-existent login test to cover invalid role scenario.

         It 'Should return false when role permissions do not match desired state' {
             $roleObject = Get-SqlDscRole -ServerObject $script:serverObject -Name $script:testRoleName -ErrorAction 'Stop'

             $result = Test-SqlDscServerPermission -Verbose -ServerRole $roleObject -Grant -Permission @('AlterAnyEndpoint') -ErrorAction 'Stop'

             $result | Should -BeFalse
         }
+
+        It 'Should return false when testing permissions for non-existent server role' {
+            $mockRole = [Microsoft.SqlServer.Management.Smo.ServerRole]::new($script:serverObject, 'NonExistentRole')
+            $result = Test-SqlDscServerPermission -ServerRole $mockRole -Grant -Permission @('ConnectSql') -ErrorAction 'Stop'
+            $result | Should -BeFalse
+        }

44-45: Connect uses -ErrorAction 'Stop' — resolved

Prior feedback about surfacing connection failures is addressed here. Thanks.

🧹 Nitpick comments (2)
tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1 (2)

34-45: Harness looks good; add -ErrorAction 'Stop' on Disconnect for consistency

Service start/stop and Connect use -ErrorAction 'Stop' as required. Add the same to Disconnect to surface failures consistently.

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

Also applies to: 54-55


110-119: Role-based test is misplaced under the login context

This ServerRole test should live under the role context for clarity and maintenance.

-        # cSpell:ignore securityadmin
-        It 'Should return true when testing for empty permission collection on principal with no additional permissions' {
-            # Get the built-in securityadmin server role which should have no explicit permissions
-            $securityAdminRole = Get-SqlDscRole -ServerObject $script:serverObject -Name 'securityadmin' -ErrorAction 'Stop'
-
-            # Test that empty permission collection returns true when no permissions are set
-            $result = Test-SqlDscServerPermission -ServerRole $securityAdminRole -Grant -Permission @() -ErrorAction 'Stop'
-
-            $result | Should -BeTrue
-        }
+        # (moved to role context)

Add under the role context (after Line 140):

        # cSpell:ignore securityadmin
        It 'Should return true for empty permission collection on built-in role without explicit grants' {
            $securityAdminRole = Get-SqlDscRole -ServerObject $script:serverObject -Name 'securityadmin' -ErrorAction 'Stop'
            $result = Test-SqlDscServerPermission -ServerRole $securityAdminRole -Grant -Permission @() -ErrorAction 'Stop'
            $result | Should -BeTrue
        }
📜 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 1a3f34f and 1f9aa40.

📒 Files selected for processing (1)
  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1 (7 hunks)
🧰 Additional context used
📓 Path-based instructions (13)
**/*.{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:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
**/*.Tests.ps1

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

Follow test patterns strictly for maintainability in Pester tests

Files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
**/*Integration.Tests.ps1

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

Always add and structure Integration tests according to the integration testing guidelines

Files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.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:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
tests/Integration/**/*.ps1

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

tests/Integration/**/*.ps1: Use DSCSQLTEST (Database Engine), SSRS (Reporting Services), and PBIRS (Power BI Report Server) instance names in CI integration tests
If an integration test requires a SQL Server Database Engine, start the Windows service in BeforeAll and stop it in AfterAll
In integration tests requiring a SQL Server DB, use Connect-SqlDscDatabaseEngine with correct CI credentials to open the session
Always call Disconnect-SqlDscDatabaseEngine after Connect-SqlDscDatabaseEngine in integration tests

Files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
tests/[iI]ntegration/[cC]ommands/*.[iI]ntegration.[tT]ests.ps1

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

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

Files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1

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

tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1: Do not use mocking in integration tests; run against a real environment
Ensure integration tests cover all scenarios and code paths
In CI, use Get-ComputerName for computer names
Avoid using ExpectedMessage with Should -Throw assertions in Pester
When calling commands in integration tests, pass -Force where applicable to avoid prompts
Use -ErrorAction Stop on commands in integration tests so failures surface immediately
Include the required setup block at the top of each integration test: the SuppressMessage param(), a BeforeDiscovery block that ensures DscResource.Test is available (or runs build.ps1 -Tasks 'noop' and imports it), and a BeforeAll block that sets $script:moduleName and imports the module under test with -Force -ErrorAction Stop

Files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1

⚙️ CodeRabbit configuration file

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

Requirements

  • Location Commands: tests/Integration/Commands/{CommandName}.Integration.Tests.ps1
  • Location Resources: tests/Integration/Resources/{ResourceName}.Integration.Tests.ps1
  • No mocking - real environment only
  • Cover all scenarios and code paths
  • Use Get-ComputerName for computer names in CI
  • Avoid ExpectedMessage for Should -Throw assertions
  • Only run integration tests in CI unless explicitly instructed.
  • Call commands with -Force parameter where applicable (avoids prompting).
  • Use -ErrorAction Stop on commands so failures surface immediately

Required Setup Block

[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification = 'Suppressing this rule because Script Analyzer does not understand Pester syntax.')]
param ()

BeforeDiscovery {
    try
    {
        if (-not (Get-Module -Name 'DscResource.Test'))
        {
            # Assumes dependencies have been resolved, so if this module is not available, run 'noop' task.
            if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable))
            {
                # Redirect all streams to $null, except the error stream (stream 2)
                & "$PSScriptRoot/../../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null
            }

            # If the dependencies have not been resolved, this will throw an error.
            Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop'
        }
    }
    catch [System.IO.FileNotFoundException]
    {
        throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks build" first.'
    }
}

BeforeAll {
    $script:moduleName = '{MyModuleName}'

    Import-Module -Name $script:moduleName -Force -ErrorAction 'Stop'
}

Files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
**/*.[Tt]ests.ps1

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

**/*.[Tt]ests.ps1: All public commands, private functions and classes must have unit tests
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/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1

⚙️ CodeRabbit configuration file

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

Core Requirements

  • All public commands, private functions and classes must have unit tests
  • All public commands and class-based resources must have integration tests
  • Use Pester v5 syntax only
  • Test code only inside Describe blocks
  • Assertions only in It blocks
  • Never test verbose messages, debug messages or parameter binding behavior
  • Pass all mandatory parameters to avoid prompts

Requirements

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

Naming

  • One Describe block per file matching the tested entity name
  • Context descriptions start with 'When'
  • It descriptions start with 'Should', must not contain 'when'
  • Mock variables prefix: 'mock'

Structure & Scope

  • Public commands: Never use InModuleScope (unless retrieving localized strings)
  • Private functions/class resources: Always use InModuleScope
  • Each class method = separate Context block
  • Each scenario = separate Context block
  • Use nested Context blocks for complex scenarios
  • Mocking in BeforeAll (BeforeEach only when required)
  • Setup/teardown in BeforeAll,BeforeEach/AfterAll,AfterEach close to usage

Syntax Rules

  • PascalCase: Describe, Context, It, Should, BeforeAll, BeforeEach, AfterAll, AfterEach
  • 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 `InModule...

Files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
tests/Integration/Commands/*.Integration.Tests.ps1

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

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

Files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.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:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
tests/Integration/**/*.Integration.Tests.ps1

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

Add integration tests for all public commands and resources

Files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.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:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.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:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
🧠 Learnings (11)
📓 Common learnings
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-08-29T17:20:42.266Z
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
📚 Learning: 2025-08-29T17:20:42.266Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-08-29T17:20:42.266Z
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:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:20:42.266Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-08-29T17:20:42.266Z
Learning: Applies to tests/Integration/**/*.ps1 : In integration tests requiring a SQL Server DB, use Connect-SqlDscDatabaseEngine with correct CI credentials to open the session

Applied to files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:20:42.266Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-08-29T17:20:42.266Z
Learning: Applies to tests/Integration/**/*.ps1 : Always call Disconnect-SqlDscDatabaseEngine after Connect-SqlDscDatabaseEngine in integration tests

Applied to files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:20:42.266Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-08-29T17:20:42.266Z
Learning: Applies to tests/Unit/**/*.ps1 : Unit tests must set $env:SqlServerDscCI = $true in BeforeAll and remove it in AfterAll

Applied to files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:20:42.266Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-08-29T17:20:42.266Z
Learning: Applies to tests/Integration/**/*.ps1 : If an integration test requires a SQL Server Database Engine, start the Windows service in BeforeAll and stop it in AfterAll

Applied to files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:25:09.959Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines.instructions.md:0-0
Timestamp: 2025-08-29T17:25:09.959Z
Learning: Applies to tests/Integration/**/*.Integration.Tests.ps1 : Add integration tests for all public commands and resources

Applied to files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:22:07.610Z
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.610Z
Learning: Applies to tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1 : Use -ErrorAction Stop on commands in integration tests so failures surface immediately

Applied to files:

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

Applied to files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:22:07.610Z
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.610Z
Learning: Applies to tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1 : Include the required setup block at the top of each integration test: the SuppressMessage param(), a BeforeDiscovery block that ensures DscResource.Test is available (or runs build.ps1 -Tasks 'noop' and imports it), and a BeforeAll block that sets $script:moduleName and imports the module under test with -Force -ErrorAction Stop

Applied to files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
🧬 Code graph analysis (1)
tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1 (1)
tests/Unit/Stubs/SMO.cs (2)
  • ServerPermissionSet (184-206)
  • ServerPermissionSet (188-198)
⏰ 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 (2)
tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1 (2)

32-49: Tests file already exists
The file tests/Integration/Commands/Get-SqlDscServerPermission.Integration.Tests.ps1 already defines the Describe block for Get-SqlDscServerPermission; the missing-tests comment can be removed.

Likely an incorrect or invalid review comment.


81-83: Invalid server-level permission name

'AlterAnyDatabase' is not a valid server-level permission. Use a valid one (e.g., AlterAnyEndpoint or AlterAnyAvailabilityGroup).

-            $result = Test-SqlDscServerPermission -Login $loginObject -Grant -Permission @('AlterAnyDatabase') -ErrorAction 'Stop'
+            $result = Test-SqlDscServerPermission -Login $loginObject -Grant -Permission @('AlterAnyEndpoint') -ErrorAction 'Stop'

Likely an incorrect or invalid review comment.

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

♻️ Duplicate comments (3)
tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1 (3)

243-253: Add negative test for non-existent server role (parity with login case)

Mirror the non-existent login test with a fake role to validate role path behavior.

         It 'Should return false when testing permissions for non-existent login' {
             # Create a mock login object that references a non-existent login
             # We need to use a real server object but with a non-existent login name
             $mockLogin = [Microsoft.SqlServer.Management.Smo.Login]::new($script:serverObject, 'NonExistentLogin')

             $result = Test-SqlDscServerPermission -Login $mockLogin -Grant -Permission @('ConnectSql') -ErrorAction 'Stop'

             $result | Should -BeFalse
         }
+
+        It 'Should return false when testing permissions for non-existent server role' {
+            # Create a role object that does not exist on the server
+            $mockRole = [Microsoft.SqlServer.Management.Smo.ServerRole]::new($script:serverObject, 'NonExistentRole')
+
+            $result = Test-SqlDscServerPermission -ServerRole $mockRole -Grant -Permission @('ConnectSql') -ErrorAction 'Stop'
+
+            $result | Should -BeFalse
+        }

133-135: Fix ExactMatch set: ViewAnyDefinition was never granted for the login

Including an ungranted permission will make this test fail.

-            $result = Test-SqlDscServerPermission -Login $loginObject -Grant -Permission @('ConnectSql', 'ViewServerState', 'ViewAnyDefinition') -ExactMatch -ErrorAction 'Stop'
+            $result = Test-SqlDscServerPermission -Login $loginObject -Grant -Permission @('ConnectSql', 'ViewServerState') -ExactMatch -ErrorAction 'Stop'

160-165: Fix role ExactMatch: CreateEndpoint was not granted

BeforeAll granted ConnectSql, ViewServerState, CreateAnyDatabase only.

-            $result = Test-SqlDscServerPermission -ServerRole $roleObject -Grant -Permission @('ConnectSql', 'ViewServerState', 'CreateEndpoint', 'CreateAnyDatabase') -ExactMatch -ErrorAction 'Stop'
+            $result = Test-SqlDscServerPermission -ServerRole $roleObject -Grant -Permission @('ConnectSql', 'ViewServerState', 'CreateAnyDatabase') -ExactMatch -ErrorAction 'Stop'
🧹 Nitpick comments (4)
tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1 (4)

34-45: Tighten setup/teardown: add -ErrorAction Stop on disconnect + fix minor comment

  • Ensure teardown failures surface.
  • Minor grammar nit in the comment.
-        # Starting the named instance SQL Server service prior to running tests.
+        # Start the named instance SQL Server service prior to running tests.

-        $mockSqlAdministratorUserName = 'SqlAdmin' # Using computer name as NetBIOS name throw exception.
+        $mockSqlAdministratorUserName = 'SqlAdmin' # Using computer name as NetBIOS name throws an exception.

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

Please confirm Disconnect-SqlDscDatabaseEngine supports -ErrorAction in this module version.

Also applies to: 51-56


110-119: Role test placed in login context; verify fixed-role enumeration behavior

  • Suggest moving this It-block under the role context for clarity.
  • Fixed server roles may surface implicit permissions differently across SQL versions; validate this stays stable on 2017/2019/2022 CI images.

124-126: Comment is misleading; only ViewServerState explains ExactMatch failure

The test fails because more than ConnectSql is granted (ViewServerState). Update the comment.

-            # Test with ExactMatch - should fail because ViewServerState and ViewAnyDefinition is also granted
+            # Test with ExactMatch - should fail because ViewServerState is also granted

152-158: Add pipeline test for ServerRole objects

Parity with the login pipeline test improves coverage of input bindings.

         It 'Should return true when role permissions match desired state' {
             $roleObject = Get-SqlDscRole -ServerObject $script:serverObject -Name $script:testRoleName -ErrorAction 'Stop'

             $result = Test-SqlDscServerPermission -ServerRole $roleObject -Grant -Permission @('ConnectSql', 'ViewServerState') -ErrorAction 'Stop'

             $result | Should -BeTrue
         }
+
+        It 'Should accept ServerRole object from pipeline' {
+            $roleObject = Get-SqlDscRole -ServerObject $script:serverObject -Name $script:testRoleName -ErrorAction 'Stop'
+
+            $result = $roleObject | Test-SqlDscServerPermission -Grant -Permission @('ConnectSql', 'ViewServerState') -ErrorAction 'Stop'
+
+            $result | Should -BeTrue
+        }
📜 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 1f9aa40 and 36d895f.

📒 Files selected for processing (2)
  • source/Public/Test-SqlDscServerPermission.ps1 (2 hunks)
  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1 (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • source/Public/Test-SqlDscServerPermission.ps1
🧰 Additional context used
📓 Path-based instructions (13)
**/*.{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:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
**/*.Tests.ps1

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

Follow test patterns strictly for maintainability in Pester tests

Files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
**/*Integration.Tests.ps1

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

Always add and structure Integration tests according to the integration testing guidelines

Files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.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:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
tests/Integration/**/*.ps1

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

tests/Integration/**/*.ps1: Use DSCSQLTEST (Database Engine), SSRS (Reporting Services), and PBIRS (Power BI Report Server) instance names in CI integration tests
If an integration test requires a SQL Server Database Engine, start the Windows service in BeforeAll and stop it in AfterAll
In integration tests requiring a SQL Server DB, use Connect-SqlDscDatabaseEngine with correct CI credentials to open the session
Always call Disconnect-SqlDscDatabaseEngine after Connect-SqlDscDatabaseEngine in integration tests

Files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
tests/[iI]ntegration/[cC]ommands/*.[iI]ntegration.[tT]ests.ps1

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

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

Files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1

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

tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1: Do not use mocking in integration tests; run against a real environment
Ensure integration tests cover all scenarios and code paths
In CI, use Get-ComputerName for computer names
Avoid using ExpectedMessage with Should -Throw assertions in Pester
When calling commands in integration tests, pass -Force where applicable to avoid prompts
Use -ErrorAction Stop on commands in integration tests so failures surface immediately
Include the required setup block at the top of each integration test: the SuppressMessage param(), a BeforeDiscovery block that ensures DscResource.Test is available (or runs build.ps1 -Tasks 'noop' and imports it), and a BeforeAll block that sets $script:moduleName and imports the module under test with -Force -ErrorAction Stop

Files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1

⚙️ CodeRabbit configuration file

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

Requirements

  • Location Commands: tests/Integration/Commands/{CommandName}.Integration.Tests.ps1
  • Location Resources: tests/Integration/Resources/{ResourceName}.Integration.Tests.ps1
  • No mocking - real environment only
  • Cover all scenarios and code paths
  • Use Get-ComputerName for computer names in CI
  • Avoid ExpectedMessage for Should -Throw assertions
  • Only run integration tests in CI unless explicitly instructed.
  • Call commands with -Force parameter where applicable (avoids prompting).
  • Use -ErrorAction Stop on commands so failures surface immediately

Required Setup Block

[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification = 'Suppressing this rule because Script Analyzer does not understand Pester syntax.')]
param ()

BeforeDiscovery {
    try
    {
        if (-not (Get-Module -Name 'DscResource.Test'))
        {
            # Assumes dependencies have been resolved, so if this module is not available, run 'noop' task.
            if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable))
            {
                # Redirect all streams to $null, except the error stream (stream 2)
                & "$PSScriptRoot/../../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null
            }

            # If the dependencies have not been resolved, this will throw an error.
            Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop'
        }
    }
    catch [System.IO.FileNotFoundException]
    {
        throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks build" first.'
    }
}

BeforeAll {
    $script:moduleName = '{MyModuleName}'

    Import-Module -Name $script:moduleName -Force -ErrorAction 'Stop'
}

Files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
**/*.[Tt]ests.ps1

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

**/*.[Tt]ests.ps1: All public commands, private functions and classes must have unit tests
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/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1

⚙️ CodeRabbit configuration file

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

Core Requirements

  • All public commands, private functions and classes must have unit tests
  • All public commands and class-based resources must have integration tests
  • Use Pester v5 syntax only
  • Test code only inside Describe blocks
  • Assertions only in It blocks
  • Never test verbose messages, debug messages or parameter binding behavior
  • Pass all mandatory parameters to avoid prompts

Requirements

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

Naming

  • One Describe block per file matching the tested entity name
  • Context descriptions start with 'When'
  • It descriptions start with 'Should', must not contain 'when'
  • Mock variables prefix: 'mock'

Structure & Scope

  • Public commands: Never use InModuleScope (unless retrieving localized strings)
  • Private functions/class resources: Always use InModuleScope
  • Each class method = separate Context block
  • Each scenario = separate Context block
  • Use nested Context blocks for complex scenarios
  • Mocking in BeforeAll (BeforeEach only when required)
  • Setup/teardown in BeforeAll,BeforeEach/AfterAll,AfterEach close to usage

Syntax Rules

  • PascalCase: Describe, Context, It, Should, BeforeAll, BeforeEach, AfterAll, AfterEach
  • 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 `InModule...

Files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
tests/Integration/Commands/*.Integration.Tests.ps1

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

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

Files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.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:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
tests/Integration/**/*.Integration.Tests.ps1

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

Add integration tests for all public commands and resources

Files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.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:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.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:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
🧠 Learnings (13)
📚 Learning: 2025-08-29T17:20:42.266Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-08-29T17:20:42.266Z
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:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:20:42.266Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-08-29T17:20:42.266Z
Learning: Applies to tests/Integration/**/*.ps1 : In integration tests requiring a SQL Server DB, use Connect-SqlDscDatabaseEngine with correct CI credentials to open the session

Applied to files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:20:42.266Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-08-29T17:20:42.266Z
Learning: Applies to tests/Integration/**/*.ps1 : Always call Disconnect-SqlDscDatabaseEngine after Connect-SqlDscDatabaseEngine in integration tests

Applied to files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:20:42.266Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-08-29T17:20:42.266Z
Learning: Applies to tests/Integration/**/*.ps1 : If an integration test requires a SQL Server Database Engine, start the Windows service in BeforeAll and stop it in AfterAll

Applied to files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:20:42.266Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-08-29T17:20:42.266Z
Learning: Applies to tests/Unit/**/*.ps1 : Unit tests must set $env:SqlServerDscCI = $true in BeforeAll and remove it in AfterAll

Applied to files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:25:09.959Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines.instructions.md:0-0
Timestamp: 2025-08-29T17:25:09.959Z
Learning: Applies to tests/Integration/**/*.Integration.Tests.ps1 : Add integration tests for all public commands and resources

Applied to files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:22:07.610Z
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.610Z
Learning: Applies to tests/[iI]ntegration/[cC]ommands/*.[iI]ntegration.[tT]ests.ps1 : Place command integration tests at tests/Integration/Commands/{CommandName}.Integration.Tests.ps1

Applied to files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:22:07.610Z
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.610Z
Learning: Applies to tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1 : Include the required setup block at the top of each integration test: the SuppressMessage param(), a BeforeDiscovery block that ensures DscResource.Test is available (or runs build.ps1 -Tasks 'noop' and imports it), and a BeforeAll block that sets $script:moduleName and imports the module under test with -Force -ErrorAction Stop

Applied to files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:22:07.610Z
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.610Z
Learning: Applies to tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1 : When calling commands in integration tests, pass -Force where applicable to avoid prompts

Applied to files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:25:09.959Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines.instructions.md:0-0
Timestamp: 2025-08-29T17:25:09.959Z
Learning: Applies to tests/Integration/Commands/*.Integration.Tests.ps1 : Place command integration tests in tests/Integration/Commands/{CommandName}.Integration.Tests.ps1

Applied to files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:22:07.610Z
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.610Z
Learning: Applies to tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1 : Use -ErrorAction Stop on commands in integration tests so failures surface immediately

Applied to files:

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

Applied to files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
🧬 Code graph analysis (1)
tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1 (1)
tests/Unit/Stubs/SMO.cs (4)
  • ServerPermissionSet (184-206)
  • Microsoft (12-1048)
  • Microsoft (1086-1497)
  • ServerPermissionSet (188-198)
⏰ 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). (5)
  • GitHub Check: dsccommunity.SqlServerDsc (Quality Test and Unit Test Determine DSC Resource Test Requirements)
  • GitHub Check: dsccommunity.SqlServerDsc (Quality Test and Unit Test Unit)
  • GitHub Check: dsccommunity.SqlServerDsc (Quality Test and Unit Test HQRM)
  • GitHub Check: dsccommunity.SqlServerDsc (Build Package Module)
  • GitHub Check: PSScriptAnalyzer
🔇 Additional comments (5)
tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1 (5)

32-32: Suite tags and naming look good

Placement and tags align with integration test guidelines.


70-108: Login grant/deny happy-path coverage looks solid

Good use of -ErrorAction 'Stop' and cleanup with Revoke in AfterAll.


152-158: Nice: role happy-path (subset) test

Covers the role flow with a subset match; concise and correct.


168-182: Role negative paths look good

Both non-match and non-exact-match cases are covered.


185-211: Deny and WithGrant scenarios (login) are covered well

Good separation of deny and grant-with-grant paths; clean setup/teardown.

…ead of enum values for consistency and clarity
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (3)
tests/Integration/Commands/Deny-SqlDscServerPermission.Integration.Tests.ps1 (3)

37-45: Avoid hardcoded credentials; support CI-provided secrets with safe fallback.
Hardcoding 'SqlAdmin'/'P@ssw0rd1' in repo is a security smell (even in tests). Prefer env-driven creds, with current values as fallback to avoid breaking local runs.

-        $script:mockInstanceName = 'DSCSQLTEST'
-
-        $mockSqlAdministratorUserName = 'SqlAdmin' # Using computer name as NetBIOS name throw exception.
-        $mockSqlAdministratorPassword = ConvertTo-SecureString -String 'P@ssw0rd1' -AsPlainText -Force
-
-        $script:mockSqlAdminCredential = [System.Management.Automation.PSCredential]::new($mockSqlAdministratorUserName, $mockSqlAdministratorPassword)
-
-        $script:serverObject = Connect-SqlDscDatabaseEngine -InstanceName $script:mockInstanceName -Credential $script:mockSqlAdminCredential
+        $script:mockInstanceName = 'DSCSQLTEST'
+
+        $ciAdminUser = $env:SQLDSC_CI_SQLADMIN_USERNAME
+        $ciAdminPassword = $env:SQLDSC_CI_SQLADMIN_PASSWORD
+
+        if ($ciAdminUser -and $ciAdminPassword)
+        {
+            $securePassword = ConvertTo-SecureString -String $ciAdminPassword -AsPlainText -Force
+            $script:mockSqlAdminCredential = [System.Management.Automation.PSCredential]::new($ciAdminUser, $securePassword)
+        }
+        else
+        {
+            # Fallback for local or non-CI runs.
+            $fallbackUserName = 'SqlAdmin' # Using computer name as NetBIOS name throws exception.
+            $fallbackPassword = ConvertTo-SecureString -String 'P@ssw0rd1' -AsPlainText -Force
+            $script:mockSqlAdminCredential = [System.Management.Automation.PSCredential]::new($fallbackUserName, $fallbackPassword)
+        }
+
+        $script:serverObject = Connect-SqlDscDatabaseEngine -InstanceName $script:mockInstanceName -Credential $script:mockSqlAdminCredential -ErrorAction 'Stop'

44-49: Reintroduce precondition checks for persistent login/role to remove test-order dependency.
This suite assumes previous tests created resources. Guard with clear preconditions so isolated runs fail fast with actionable guidance.

         # Use persistent test login and role created by earlier integration tests
         $script:testLoginName = 'IntegrationTestSqlLogin'
         $script:testRoleName = 'SqlDscIntegrationTestRole_Persistent'
+
+        try
+        {
+            $null = Get-SqlDscLogin -ServerObject $script:serverObject -Name $script:testLoginName -ErrorAction 'Stop'
+        }
+        catch
+        {
+            throw "Persistent test login '$($script:testLoginName)' not found. Ensure the setup integration test has run or create it before executing this suite."
+        }
+
+        try
+        {
+            $null = Get-SqlDscRole -ServerObject $script:serverObject -Name $script:testRoleName -ErrorAction 'Stop'
+        }
+        catch
+        {
+            throw "Persistent test server role '$($script:testRoleName)' not found. Ensure the setup integration test has run or create it before executing this suite."
+        }

94-108: Add a pipeline test for -ServerRole to mirror the -Login pipeline case.
Improves parity across parameter sets.

     Context 'When denying server permissions to role' {
@@
         It 'Should deny ViewServerState permission to role' {
@@
             $result | Should -BeTrue
         }
+
+        It 'Should accept ServerRole from pipeline' {
+            $roleObject = Get-SqlDscRole -ServerObject $script:serverObject -Name $script:testRoleName -ErrorAction 'Stop'
+
+            $null = $roleObject | Deny-SqlDscServerPermission -Permission @('ViewServerState') -Force -ErrorAction 'Stop'
+
+            $result = Test-SqlDscServerPermission -ServerRole $roleObject -Deny -Permission @('ViewServerState') -ErrorAction 'Stop'
+            $result | Should -BeTrue
+        }
📜 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 36d895f and fad7990.

📒 Files selected for processing (1)
  • tests/Integration/Commands/Deny-SqlDscServerPermission.Integration.Tests.ps1 (5 hunks)
🧰 Additional context used
📓 Path-based instructions (13)
**/*.{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:

  • tests/Integration/Commands/Deny-SqlDscServerPermission.Integration.Tests.ps1
**/*.Tests.ps1

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

Follow test patterns strictly for maintainability in Pester tests

Files:

  • tests/Integration/Commands/Deny-SqlDscServerPermission.Integration.Tests.ps1
**/*Integration.Tests.ps1

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

Always add and structure Integration tests according to the integration testing guidelines

Files:

  • tests/Integration/Commands/Deny-SqlDscServerPermission.Integration.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:

  • tests/Integration/Commands/Deny-SqlDscServerPermission.Integration.Tests.ps1
tests/Integration/**/*.ps1

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

tests/Integration/**/*.ps1: Use DSCSQLTEST (Database Engine), SSRS (Reporting Services), and PBIRS (Power BI Report Server) instance names in CI integration tests
If an integration test requires a SQL Server Database Engine, start the Windows service in BeforeAll and stop it in AfterAll
In integration tests requiring a SQL Server DB, use Connect-SqlDscDatabaseEngine with correct CI credentials to open the session
Always call Disconnect-SqlDscDatabaseEngine after Connect-SqlDscDatabaseEngine in integration tests

Files:

  • tests/Integration/Commands/Deny-SqlDscServerPermission.Integration.Tests.ps1
tests/[iI]ntegration/[cC]ommands/*.[iI]ntegration.[tT]ests.ps1

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

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

Files:

  • tests/Integration/Commands/Deny-SqlDscServerPermission.Integration.Tests.ps1
tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1

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

tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1: Do not use mocking in integration tests; run against a real environment
Ensure integration tests cover all scenarios and code paths
In CI, use Get-ComputerName for computer names
Avoid using ExpectedMessage with Should -Throw assertions in Pester
When calling commands in integration tests, pass -Force where applicable to avoid prompts
Use -ErrorAction Stop on commands in integration tests so failures surface immediately
Include the required setup block at the top of each integration test: the SuppressMessage param(), a BeforeDiscovery block that ensures DscResource.Test is available (or runs build.ps1 -Tasks 'noop' and imports it), and a BeforeAll block that sets $script:moduleName and imports the module under test with -Force -ErrorAction Stop

Files:

  • tests/Integration/Commands/Deny-SqlDscServerPermission.Integration.Tests.ps1

⚙️ CodeRabbit configuration file

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

Requirements

  • Location Commands: tests/Integration/Commands/{CommandName}.Integration.Tests.ps1
  • Location Resources: tests/Integration/Resources/{ResourceName}.Integration.Tests.ps1
  • No mocking - real environment only
  • Cover all scenarios and code paths
  • Use Get-ComputerName for computer names in CI
  • Avoid ExpectedMessage for Should -Throw assertions
  • Only run integration tests in CI unless explicitly instructed.
  • Call commands with -Force parameter where applicable (avoids prompting).
  • Use -ErrorAction Stop on commands so failures surface immediately

Required Setup Block

[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification = 'Suppressing this rule because Script Analyzer does not understand Pester syntax.')]
param ()

BeforeDiscovery {
    try
    {
        if (-not (Get-Module -Name 'DscResource.Test'))
        {
            # Assumes dependencies have been resolved, so if this module is not available, run 'noop' task.
            if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable))
            {
                # Redirect all streams to $null, except the error stream (stream 2)
                & "$PSScriptRoot/../../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null
            }

            # If the dependencies have not been resolved, this will throw an error.
            Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop'
        }
    }
    catch [System.IO.FileNotFoundException]
    {
        throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks build" first.'
    }
}

BeforeAll {
    $script:moduleName = '{MyModuleName}'

    Import-Module -Name $script:moduleName -Force -ErrorAction 'Stop'
}

Files:

  • tests/Integration/Commands/Deny-SqlDscServerPermission.Integration.Tests.ps1
**/*.[Tt]ests.ps1

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

**/*.[Tt]ests.ps1: All public commands, private functions and classes must have unit tests
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/Integration/Commands/Deny-SqlDscServerPermission.Integration.Tests.ps1

⚙️ CodeRabbit configuration file

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

Core Requirements

  • All public commands, private functions and classes must have unit tests
  • All public commands and class-based resources must have integration tests
  • Use Pester v5 syntax only
  • Test code only inside Describe blocks
  • Assertions only in It blocks
  • Never test verbose messages, debug messages or parameter binding behavior
  • Pass all mandatory parameters to avoid prompts

Requirements

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

Naming

  • One Describe block per file matching the tested entity name
  • Context descriptions start with 'When'
  • It descriptions start with 'Should', must not contain 'when'
  • Mock variables prefix: 'mock'

Structure & Scope

  • Public commands: Never use InModuleScope (unless retrieving localized strings)
  • Private functions/class resources: Always use InModuleScope
  • Each class method = separate Context block
  • Each scenario = separate Context block
  • Use nested Context blocks for complex scenarios
  • Mocking in BeforeAll (BeforeEach only when required)
  • Setup/teardown in BeforeAll,BeforeEach/AfterAll,AfterEach close to usage

Syntax Rules

  • PascalCase: Describe, Context, It, Should, BeforeAll, BeforeEach, AfterAll, AfterEach
  • 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 `InModule...

Files:

  • tests/Integration/Commands/Deny-SqlDscServerPermission.Integration.Tests.ps1
tests/Integration/Commands/*.Integration.Tests.ps1

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

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

Files:

  • tests/Integration/Commands/Deny-SqlDscServerPermission.Integration.Tests.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:

  • tests/Integration/Commands/Deny-SqlDscServerPermission.Integration.Tests.ps1
tests/Integration/**/*.Integration.Tests.ps1

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

Add integration tests for all public commands and resources

Files:

  • tests/Integration/Commands/Deny-SqlDscServerPermission.Integration.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:

  • tests/Integration/Commands/Deny-SqlDscServerPermission.Integration.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:

  • tests/Integration/Commands/Deny-SqlDscServerPermission.Integration.Tests.ps1
🧠 Learnings (11)
📚 Learning: 2025-08-29T17:20:42.266Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-08-29T17:20:42.266Z
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:

  • tests/Integration/Commands/Deny-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:20:42.266Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-08-29T17:20:42.266Z
Learning: Applies to tests/Integration/**/*.ps1 : If an integration test requires a SQL Server Database Engine, start the Windows service in BeforeAll and stop it in AfterAll

Applied to files:

  • tests/Integration/Commands/Deny-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:20:42.266Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-08-29T17:20:42.266Z
Learning: Applies to tests/Integration/**/*.ps1 : Always call Disconnect-SqlDscDatabaseEngine after Connect-SqlDscDatabaseEngine in integration tests

Applied to files:

  • tests/Integration/Commands/Deny-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:20:42.266Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-08-29T17:20:42.266Z
Learning: Applies to tests/Unit/**/*.ps1 : Unit tests must set $env:SqlServerDscCI = $true in BeforeAll and remove it in AfterAll

Applied to files:

  • tests/Integration/Commands/Deny-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:20:42.266Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-08-29T17:20:42.266Z
Learning: Applies to tests/Integration/**/*.ps1 : In integration tests requiring a SQL Server DB, use Connect-SqlDscDatabaseEngine with correct CI credentials to open the session

Applied to files:

  • tests/Integration/Commands/Deny-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:22:07.610Z
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.610Z
Learning: Applies to tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1 : Include the required setup block at the top of each integration test: the SuppressMessage param(), a BeforeDiscovery block that ensures DscResource.Test is available (or runs build.ps1 -Tasks 'noop' and imports it), and a BeforeAll block that sets $script:moduleName and imports the module under test with -Force -ErrorAction Stop

Applied to files:

  • tests/Integration/Commands/Deny-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-17T10:13:30.079Z
Learnt from: johlju
PR: dsccommunity/SqlServerDsc#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/Integration/Commands/Deny-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:22:07.610Z
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.610Z
Learning: Applies to tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1 : Do not use mocking in integration tests; run against a real environment

Applied to files:

  • tests/Integration/Commands/Deny-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:20:42.266Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-08-29T17:20:42.266Z
Learning: Applies to tests/Stubs/SMO.cs : After changing SMO.cs (SMO stubs), run tests in a new PowerShell session

Applied to files:

  • tests/Integration/Commands/Deny-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:20:42.266Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-08-29T17:20:42.266Z
Learning: Applies to tests/Unit/**/*.ps1 : In unit tests, use SMO stub types from SMO.cs and never mock real SMO types

Applied to files:

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

Applied to files:

  • tests/Integration/Commands/Deny-SqlDscServerPermission.Integration.Tests.ps1
🧬 Code graph analysis (1)
tests/Integration/Commands/Deny-SqlDscServerPermission.Integration.Tests.ps1 (1)
tests/Unit/Stubs/SMO.cs (8)
  • Microsoft (1086-1497)
  • ServerPermissionSet (184-206)
  • Microsoft (12-1048)
  • Server (278-373)
  • Service (1149-1181)
  • Login (379-532)
  • Database (558-617)
  • Microsoft (1499-1653)
⏰ 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
🔇 Additional comments (6)
tests/Integration/Commands/Deny-SqlDscServerPermission.Integration.Tests.ps1 (6)

32-32: LGTM: multi-version tags are correct and consistent with CI matrix.


61-63: LGTM: idempotent cleanup before assertions.
Using Revoke with -ErrorAction 'SilentlyContinue' is appropriate for pre-test state reset.


78-79: LGTM: Deny + Test path for ViewAnyDatabase (login) is correct.


89-90: LGTM: pipeline acceptance for -Login parameter set.


100-107: LGTM: role denial path validated.


110-117: Incorrect suggestion: no other integration tests depend on AlterTrace denial
Grep of the integration suite shows “AlterTrace” only in the README and this Deny-SqlDscServerPermission test—no other .Tests.ps1 references it—so there’s no need to reorder or isolate this side-effect.

Likely an incorrect or invalid review comment.

…add pipeline support for ServerRole in Test-SqlDscServerPermission.
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

♻️ Duplicate comments (5)
tests/Integration/Commands/Deny-SqlDscServerPermission.Integration.Tests.ps1 (2)

34-36: Make SQL service start idempotent and wait for Running.

Avoid starting an already running service and race conditions; check status first and wait until Running.

Apply:

-        # Starting the named instance SQL Server service prior to running tests.
-        Start-Service -Name 'MSSQL$DSCSQLTEST' -Verbose -ErrorAction 'Stop'
+        # Ensure the named instance SQL Server service is running prior to tests.
+        $svc = Get-Service -Name 'MSSQL$DSCSQLTEST' -ErrorAction 'Stop'
+        if ($svc.Status -ne 'Running')
+        {
+            Start-Service -Name 'MSSQL$DSCSQLTEST' -Verbose -ErrorAction 'Stop'
+            $svc.WaitForStatus('Running', [System.TimeSpan]::FromSeconds(60))
+        }

51-56: Tighten teardown: fail on disconnect errors; stop service idempotently and wait for Stopped.

Prevents false greens and flakiness between suites.

Apply:

-        Disconnect-SqlDscDatabaseEngine -ServerObject $script:serverObject
-
-        # Stop the named instance SQL Server service to save memory on the build worker.
-        Stop-Service -Name 'MSSQL$DSCSQLTEST' -Verbose -ErrorAction 'Stop'
+        Disconnect-SqlDscDatabaseEngine -ServerObject $script:serverObject -ErrorAction 'Stop'
+
+        # Stop the named instance SQL Server service to save memory on the build worker.
+        $svc = Get-Service -Name 'MSSQL$DSCSQLTEST' -ErrorAction 'Continue'
+        if ($svc -and $svc.Status -eq 'Running')
+        {
+            Stop-Service -Name 'MSSQL$DSCSQLTEST' -Verbose -ErrorAction 'Stop'
+            $svc.WaitForStatus('Stopped', [System.TimeSpan]::FromSeconds(60))
+        }
tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1 (3)

168-175: Add negative scenario for non-existent server role.

Mirror the non-existent login test to cover role path.

Apply (insert at end of the role Context):

         It 'Should return false when role permissions do not exact match desired state' {
             $roleObject = Get-SqlDscRole -ServerObject $script:serverObject -Name $script:testRoleName -ErrorAction 'Stop'

             $result = Test-SqlDscServerPermission -ServerRole $roleObject -Grant -Permission @('ViewServerState') -ExactMatch -ErrorAction 'Stop'

             $result | Should -BeFalse
         }
+
+        It 'Should return false when testing permissions for non-existent server role' {
+            $mockRole = [Microsoft.SqlServer.Management.Smo.ServerRole]::new($script:serverObject, 'NonExistentRole')
+
+            $result = Test-SqlDscServerPermission -ServerRole $mockRole -Grant -Permission @('ConnectSql') -ErrorAction 'Stop'
+
+            $result | Should -BeFalse
+        }

133-135: ExactMatch includes an ungranted permission (ViewAnyDefinition).

Trim to the granted set so the test is valid.

Apply:

-            $result = Test-SqlDscServerPermission -Login $loginObject -Grant -Permission @('ConnectSql', 'ViewServerState', 'ViewAnyDefinition') -ExactMatch -ErrorAction 'Stop'
+            $result = Test-SqlDscServerPermission -Login $loginObject -Grant -Permission @('ConnectSql', 'ViewServerState') -ExactMatch -ErrorAction 'Stop'

160-166: Role ExactMatch includes CreateEndpoint which wasn't granted.

Remove CreateEndpoint to match the granted set.

Apply:

-            $result = Test-SqlDscServerPermission -ServerRole $roleObject -Grant -Permission @('ConnectSql', 'ViewServerState', 'CreateEndpoint', 'CreateAnyDatabase') -ExactMatch -ErrorAction 'Stop'
+            $result = Test-SqlDscServerPermission -ServerRole $roleObject -Grant -Permission @('ConnectSql', 'ViewServerState', 'CreateAnyDatabase') -ExactMatch -ErrorAction 'Stop'
🧹 Nitpick comments (3)
tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1 (3)

34-36: Make SQL service start idempotent and wait for Running.

Avoid start failures and racing the connect.

Apply:

-        # Starting the named instance SQL Server service prior to running tests.
-        Start-Service -Name 'MSSQL$DSCSQLTEST' -Verbose -ErrorAction 'Stop'
+        # Ensure the named instance SQL Server service is running prior to tests.
+        $svc = Get-Service -Name 'MSSQL$DSCSQLTEST' -ErrorAction 'Stop'
+        if ($svc.Status -ne 'Running')
+        {
+            Start-Service -Name 'MSSQL$DSCSQLTEST' -Verbose -ErrorAction 'Stop'
+            $svc.WaitForStatus('Running', [System.TimeSpan]::FromSeconds(60))
+        }

51-56: Harden teardown: add -ErrorAction Stop and wait for service Stopped.

Improves reliability between suites.

Apply:

-        Disconnect-SqlDscDatabaseEngine -ServerObject $script:serverObject
-
-        # Stop the named instance SQL Server service to save memory on the build worker.
-        Stop-Service -Name 'MSSQL$DSCSQLTEST' -Verbose -ErrorAction 'Stop'
+        Disconnect-SqlDscDatabaseEngine -ServerObject $script:serverObject -ErrorAction 'Stop'
+
+        # Stop the named instance SQL Server service to save memory on the build worker.
+        $svc = Get-Service -Name 'MSSQL$DSCSQLTEST' -ErrorAction 'Continue'
+        if ($svc -and $svc.Status -eq 'Running')
+        {
+            Stop-Service -Name 'MSSQL$DSCSQLTEST' -Verbose -ErrorAction 'Stop'
+            $svc.WaitForStatus('Stopped', [System.TimeSpan]::FromSeconds(60))
+        }

124-126: Fix comment to reflect actual additional permission.

Only ViewServerState is additionally granted here.

Apply:

-            # Test with ExactMatch - should fail because ViewServerState and ViewAnyDefinition is also granted
+            # Test with ExactMatch - should fail because ViewServerState is also granted
📜 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 fad7990 and 785a500.

📒 Files selected for processing (3)
  • tests/Integration/Commands/Deny-SqlDscServerPermission.Integration.Tests.ps1 (5 hunks)
  • tests/Integration/Commands/Revoke-SqlDscServerPermission.Integration.Tests.ps1 (4 hunks)
  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1 (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/Integration/Commands/Revoke-SqlDscServerPermission.Integration.Tests.ps1
🧰 Additional context used
📓 Path-based instructions (13)
**/*.{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:

  • tests/Integration/Commands/Deny-SqlDscServerPermission.Integration.Tests.ps1
  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
**/*.Tests.ps1

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

Follow test patterns strictly for maintainability in Pester tests

Files:

  • tests/Integration/Commands/Deny-SqlDscServerPermission.Integration.Tests.ps1
  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
**/*Integration.Tests.ps1

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

Always add and structure Integration tests according to the integration testing guidelines

Files:

  • tests/Integration/Commands/Deny-SqlDscServerPermission.Integration.Tests.ps1
  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.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:

  • tests/Integration/Commands/Deny-SqlDscServerPermission.Integration.Tests.ps1
  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
tests/Integration/**/*.ps1

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

tests/Integration/**/*.ps1: Use DSCSQLTEST (Database Engine), SSRS (Reporting Services), and PBIRS (Power BI Report Server) instance names in CI integration tests
If an integration test requires a SQL Server Database Engine, start the Windows service in BeforeAll and stop it in AfterAll
In integration tests requiring a SQL Server DB, use Connect-SqlDscDatabaseEngine with correct CI credentials to open the session
Always call Disconnect-SqlDscDatabaseEngine after Connect-SqlDscDatabaseEngine in integration tests

Files:

  • tests/Integration/Commands/Deny-SqlDscServerPermission.Integration.Tests.ps1
  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
tests/[iI]ntegration/[cC]ommands/*.[iI]ntegration.[tT]ests.ps1

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

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

Files:

  • tests/Integration/Commands/Deny-SqlDscServerPermission.Integration.Tests.ps1
  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1

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

tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1: Do not use mocking in integration tests; run against a real environment
Ensure integration tests cover all scenarios and code paths
In CI, use Get-ComputerName for computer names
Avoid using ExpectedMessage with Should -Throw assertions in Pester
When calling commands in integration tests, pass -Force where applicable to avoid prompts
Use -ErrorAction Stop on commands in integration tests so failures surface immediately
Include the required setup block at the top of each integration test: the SuppressMessage param(), a BeforeDiscovery block that ensures DscResource.Test is available (or runs build.ps1 -Tasks 'noop' and imports it), and a BeforeAll block that sets $script:moduleName and imports the module under test with -Force -ErrorAction Stop

Files:

  • tests/Integration/Commands/Deny-SqlDscServerPermission.Integration.Tests.ps1
  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1

⚙️ CodeRabbit configuration file

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

Requirements

  • Location Commands: tests/Integration/Commands/{CommandName}.Integration.Tests.ps1
  • Location Resources: tests/Integration/Resources/{ResourceName}.Integration.Tests.ps1
  • No mocking - real environment only
  • Cover all scenarios and code paths
  • Use Get-ComputerName for computer names in CI
  • Avoid ExpectedMessage for Should -Throw assertions
  • Only run integration tests in CI unless explicitly instructed.
  • Call commands with -Force parameter where applicable (avoids prompting).
  • Use -ErrorAction Stop on commands so failures surface immediately

Required Setup Block

[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification = 'Suppressing this rule because Script Analyzer does not understand Pester syntax.')]
param ()

BeforeDiscovery {
    try
    {
        if (-not (Get-Module -Name 'DscResource.Test'))
        {
            # Assumes dependencies have been resolved, so if this module is not available, run 'noop' task.
            if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable))
            {
                # Redirect all streams to $null, except the error stream (stream 2)
                & "$PSScriptRoot/../../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null
            }

            # If the dependencies have not been resolved, this will throw an error.
            Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop'
        }
    }
    catch [System.IO.FileNotFoundException]
    {
        throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks build" first.'
    }
}

BeforeAll {
    $script:moduleName = '{MyModuleName}'

    Import-Module -Name $script:moduleName -Force -ErrorAction 'Stop'
}

Files:

  • tests/Integration/Commands/Deny-SqlDscServerPermission.Integration.Tests.ps1
  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
**/*.[Tt]ests.ps1

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

**/*.[Tt]ests.ps1: All public commands, private functions and classes must have unit tests
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/Integration/Commands/Deny-SqlDscServerPermission.Integration.Tests.ps1
  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1

⚙️ CodeRabbit configuration file

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

Core Requirements

  • All public commands, private functions and classes must have unit tests
  • All public commands and class-based resources must have integration tests
  • Use Pester v5 syntax only
  • Test code only inside Describe blocks
  • Assertions only in It blocks
  • Never test verbose messages, debug messages or parameter binding behavior
  • Pass all mandatory parameters to avoid prompts

Requirements

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

Naming

  • One Describe block per file matching the tested entity name
  • Context descriptions start with 'When'
  • It descriptions start with 'Should', must not contain 'when'
  • Mock variables prefix: 'mock'

Structure & Scope

  • Public commands: Never use InModuleScope (unless retrieving localized strings)
  • Private functions/class resources: Always use InModuleScope
  • Each class method = separate Context block
  • Each scenario = separate Context block
  • Use nested Context blocks for complex scenarios
  • Mocking in BeforeAll (BeforeEach only when required)
  • Setup/teardown in BeforeAll,BeforeEach/AfterAll,AfterEach close to usage

Syntax Rules

  • PascalCase: Describe, Context, It, Should, BeforeAll, BeforeEach, AfterAll, AfterEach
  • 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 `InModule...

Files:

  • tests/Integration/Commands/Deny-SqlDscServerPermission.Integration.Tests.ps1
  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
tests/Integration/Commands/*.Integration.Tests.ps1

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

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

Files:

  • tests/Integration/Commands/Deny-SqlDscServerPermission.Integration.Tests.ps1
  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.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:

  • tests/Integration/Commands/Deny-SqlDscServerPermission.Integration.Tests.ps1
  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
tests/Integration/**/*.Integration.Tests.ps1

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

Add integration tests for all public commands and resources

Files:

  • tests/Integration/Commands/Deny-SqlDscServerPermission.Integration.Tests.ps1
  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.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:

  • tests/Integration/Commands/Deny-SqlDscServerPermission.Integration.Tests.ps1
  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.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:

  • tests/Integration/Commands/Deny-SqlDscServerPermission.Integration.Tests.ps1
  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
🧠 Learnings (18)
📓 Common learnings
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-08-29T17:20:42.266Z
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
📚 Learning: 2025-08-29T17:20:42.266Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-08-29T17:20:42.266Z
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:

  • tests/Integration/Commands/Deny-SqlDscServerPermission.Integration.Tests.ps1
  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:20:42.266Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-08-29T17:20:42.266Z
Learning: Applies to tests/Integration/**/*.ps1 : If an integration test requires a SQL Server Database Engine, start the Windows service in BeforeAll and stop it in AfterAll

Applied to files:

  • tests/Integration/Commands/Deny-SqlDscServerPermission.Integration.Tests.ps1
  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:20:42.266Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-08-29T17:20:42.266Z
Learning: Applies to tests/Integration/**/*.ps1 : Always call Disconnect-SqlDscDatabaseEngine after Connect-SqlDscDatabaseEngine in integration tests

Applied to files:

  • tests/Integration/Commands/Deny-SqlDscServerPermission.Integration.Tests.ps1
  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:20:42.266Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-08-29T17:20:42.266Z
Learning: Applies to tests/Unit/**/*.ps1 : Unit tests must set $env:SqlServerDscCI = $true in BeforeAll and remove it in AfterAll

Applied to files:

  • tests/Integration/Commands/Deny-SqlDscServerPermission.Integration.Tests.ps1
  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:20:42.266Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-08-29T17:20:42.266Z
Learning: Applies to tests/Integration/**/*.ps1 : In integration tests requiring a SQL Server DB, use Connect-SqlDscDatabaseEngine with correct CI credentials to open the session

Applied to files:

  • tests/Integration/Commands/Deny-SqlDscServerPermission.Integration.Tests.ps1
  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:22:07.610Z
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.610Z
Learning: Applies to tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1 : Include the required setup block at the top of each integration test: the SuppressMessage param(), a BeforeDiscovery block that ensures DscResource.Test is available (or runs build.ps1 -Tasks 'noop' and imports it), and a BeforeAll block that sets $script:moduleName and imports the module under test with -Force -ErrorAction Stop

Applied to files:

  • tests/Integration/Commands/Deny-SqlDscServerPermission.Integration.Tests.ps1
  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-17T10:13:30.079Z
Learnt from: johlju
PR: dsccommunity/SqlServerDsc#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/Integration/Commands/Deny-SqlDscServerPermission.Integration.Tests.ps1
  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:22:07.610Z
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.610Z
Learning: Applies to tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1 : Do not use mocking in integration tests; run against a real environment

Applied to files:

  • tests/Integration/Commands/Deny-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:20:42.266Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-08-29T17:20:42.266Z
Learning: Applies to tests/Stubs/SMO.cs : After changing SMO.cs (SMO stubs), run tests in a new PowerShell session

Applied to files:

  • tests/Integration/Commands/Deny-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:20:42.266Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-08-29T17:20:42.266Z
Learning: Applies to tests/Unit/**/*.ps1 : In unit tests, use SMO stub types from SMO.cs and never mock real SMO types

Applied to files:

  • tests/Integration/Commands/Deny-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:23:02.585Z
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.585Z
Learning: Applies to **/*.[Tt]ests.ps1 : Avoid try/catch/finally for cleanup; use AfterAll or AfterEach

Applied to files:

  • tests/Integration/Commands/Deny-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:22:07.610Z
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.610Z
Learning: Applies to tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1 : Use -ErrorAction Stop on commands in integration tests so failures surface immediately

Applied to files:

  • tests/Integration/Commands/Deny-SqlDscServerPermission.Integration.Tests.ps1
  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:23:02.585Z
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.585Z
Learning: Applies to **/*.[Tt]ests.ps1 : Use BeforeEach and AfterEach sparingly

Applied to files:

  • tests/Integration/Commands/Deny-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:23:02.585Z
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.585Z
Learning: Applies to **/*.[Tt]ests.ps1 : Place setup/teardown in BeforeAll/BeforeEach and AfterAll/AfterEach close to their usage

Applied to files:

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

Applied to files:

  • tests/Integration/Commands/Deny-SqlDscServerPermission.Integration.Tests.ps1
  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:25:09.959Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines.instructions.md:0-0
Timestamp: 2025-08-29T17:25:09.959Z
Learning: Applies to tests/Integration/**/*.Integration.Tests.ps1 : Add integration tests for all public commands and resources

Applied to files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
📚 Learning: 2025-08-29T17:22:07.610Z
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.610Z
Learning: Applies to tests/[iI]ntegration/[cC]ommands/*.[iI]ntegration.[tT]ests.ps1 : Place command integration tests at tests/Integration/Commands/{CommandName}.Integration.Tests.ps1

Applied to files:

  • tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1
🧬 Code graph analysis (2)
tests/Integration/Commands/Deny-SqlDscServerPermission.Integration.Tests.ps1 (1)
tests/Unit/Stubs/SMO.cs (9)
  • Microsoft (1086-1497)
  • ServerPermissionSet (184-206)
  • Microsoft (12-1048)
  • Server (278-373)
  • Service (1149-1181)
  • Login (379-532)
  • DatabasePermissionSet (234-245)
  • Database (558-617)
  • Microsoft (1499-1653)
tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1 (1)
tests/Unit/Stubs/SMO.cs (3)
  • ServerPermissionSet (184-206)
  • Microsoft (12-1048)
  • Microsoft (1086-1497)
⏰ 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
🔇 Additional comments (6)
tests/Integration/Commands/Deny-SqlDscServerPermission.Integration.Tests.ps1 (3)

37-43: Setup values LGTM.

Instance name and PSCredential construction align with integration test patterns.


58-93: Login deny flow looks solid.

Cleanup revokes, deny, and validations use correct switches and assertions.


95-129: Role deny scenarios and pipeline coverage look good.

Good coverage for role principal and pipeline input; assertions are appropriate.

tests/Integration/Commands/Test-SqlDscServerPermission.Integration.Tests.ps1 (3)

42-45: Connect call uses -ErrorAction Stop — good.


152-158: Role grant happy-path assertion LGTM.


251-260: Non-existent login scenario LGTM.

…d error handling in Deny-SqlDscServerPermission tests
@johlju johlju requested a review from Copilot September 5, 2025 10:55
Copy link

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

This PR enhances the Get-SqlDscServerPermission command to support server roles in addition to logins by adding Test-SqlDscIsRole checks alongside existing Test-SqlDscIsLogin functionality. The command now accepts both login principals and server role principals as the Name parameter while maintaining backward compatibility.

Key Changes

  • Enhanced Get-SqlDscServerPermission to support both logins and server roles via dual principal type checking
  • Added comprehensive unit and integration tests covering login, server role, and mixed parameter set scenarios
  • Updated localization strings and error handling to improve debugging with more descriptive messages

Reviewed Changes

Copilot reviewed 51 out of 51 changed files in this pull request and generated 9 comments.

Show a summary per file
File Description
source/Public/Get-SqlDscServerPermission.ps1 Enhanced to support Login/ServerRole parameter sets and dual principal type checking
tests/Unit/Public/Get-SqlDscServerPermission.Tests.ps1 Added comprehensive unit tests for new parameter sets and role functionality
tests/Integration/Commands/Get-SqlDscServerPermission.Integration.Tests.ps1 Added new integration test file covering real-world login and role scenarios
source/en-US/SqlServerDsc.strings.psd1 Added debug messages for better troubleshooting of permission operations
Multiple test files Updated test setup patterns, removed SQL 2016 tags, and standardized module import

Copy link
Member Author

@johlju johlju left a comment

Choose a reason for hiding this comment

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

:lgtm:

@johlju reviewed 5 of 12 files at r6, 33 of 39 files at r7, 2 of 6 files at r8, 4 of 6 files at r9, 1 of 3 files at r10, 1 of 2 files at r12, 2 of 3 files at r14, 1 of 1 files at r15, 1 of 1 files at r16, 1 of 1 files at r17, all commit messages.
Reviewable status: all files reviewed, 1 unresolved discussion (waiting on @johlju)

@johlju johlju merged commit 59c5c40 into dsccommunity:main Sep 5, 2025
43 of 44 checks passed
@johlju johlju deleted the fix/get-sqldscserverpermission branch September 5, 2025 18:37
@johlju johlju removed the needs review The pull request needs a code review. label Sep 5, 2025
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.

Get-SqlDscServerPermission: Should be able to return permissions for a server role

2 participants