Skip to content

Conversation

@dan-hughes
Copy link
Contributor

@dan-hughes dan-hughes commented Aug 7, 2025

Pull Request (PR) description

Run ScriptAnalyzer on all ps1/psm1 files in source.

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).
  • Documentation added/updated in README.md.
  • Comment-based help added/updated.
  • Localization strings added/updated in all localization files as appropriate.
  • Examples appropriately added/updated.
  • Unit tests added/updated. See DSC Community Testing Guidelines.
  • Integration tests added/updated (where possible). See DSC Community Testing Guidelines.
  • New/changed code adheres to DSC Community Style Guidelines.

This change is Reviewable

@coderabbitai
Copy link

coderabbitai bot commented Aug 7, 2025

Walkthrough

Updates PSSA test discovery to include both .ps1 and .psm1 source files, refactors test mapping and descriptive text in the PSSA test script, simplifies suppressed-rule parsing and output formatting, adds an Unreleased changelog entry, and fixes a comment typo in DscResource.Test.psm1.

Changes

Cohort / File(s) Change Summary
Test Discovery & Mapping
source/Tests/QA/PSSAResource.common.v5.Tests.ps1
Discovery now collects *.psm1 and *.ps1 using Get-ChildItem -File -Recurse into a strongly-typed List[System.Object] via AddRange; mapping refactored from moduleFiles/moduleFileToTest to sourceFiles/sourceFileToTest with a DescriptiveName PSCustomObject; Describe/When text updated; suppressed-rule parsing converted to a foreach loop; output formatting simplified to Format-Table -AutoSize -Wrap.
Changelog Update
CHANGELOG.md
Added "Target all source files [#163]" under Unreleased → Changed.
Comment Typo Fix
source/DscResource.Test.psm1
Fixed comment text ("it is must be left here" → "it must be left here"); no functional changes.

Sequence Diagram(s)

sequenceDiagram
    participant Runner as TestRunner
    participant FS as FileSystem
    participant PSSA as PSSALinter

    rect rgb(240,248,255)
    Note over Runner,FS: Discovery phase (includes .psm1 and .ps1)
    Runner->>FS: Get-ChildItem -Recurse -File *.psm1 / *.ps1
    FS-->>Runner: Source file list
    end

    loop For each source file
        Runner->>Runner: Build PSCustomObject { File, DescriptiveName }
        Runner->>PSSA: Invoke HQRM rules on file
        PSSA-->>Runner: Lint results
    end

    rect rgb(245,245,245)
    Note over Runner: Aggregate results and format (Format-Table -AutoSize -Wrap)
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Assessment against linked issues

Objective Addressed Explanation
Expand PSSA HQRM Test to target all source files, including Classes, Enums, Private, Public, and PSM1 files (#163)

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 a9ae23d and 746ce73.

📒 Files selected for processing (1)
  • CHANGELOG.md (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • CHANGELOG.md
✨ 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.

@dan-hughes
Copy link
Contributor Author

On hold until #161 merged.

@dan-hughes
Copy link
Contributor Author

@johlju, exclusions are added to build.yml.

Tested against SqlServerDsc and WSManDsc locally, which did find some issues.

@johlju
Copy link
Member

johlju commented Aug 8, 2025

Why did this previously fail running on the built module *.psm1 and MOF-based resource *.psm1 which I would seem had been better? 🤔 You might have mentioned it before, but can you remind me? 🙂

@dan-hughes
Copy link
Contributor Author

dan-hughes commented Aug 8, 2025

Looking at the history, it never did run against built module. Just *.psm1 files in source.

EDIT: It must have been another test.

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 9b940b5 and 0d990cc.

📒 Files selected for processing (4)
  • CHANGELOG.md (1 hunks)
  • azure-pipelines.yml (0 hunks)
  • source/DscResource.Test.psm1 (1 hunks)
  • source/Tests/QA/ExampleFiles.common.v4.Tests.ps1 (1 hunks)
💤 Files with no reviewable changes (1)
  • azure-pipelines.yml
🧰 Additional context used
🪛 LanguageTool
CHANGELOG.md

[grammar] ~10-~10: Use correct spacing
Context: ...pec/v2.0.0.html). ## [Unreleased] ### Fixed - Add ability to filter out files in `Exam...

(QB_NEW_EN_OTHER_ERROR_IDS_5)


[grammar] ~12-~12: Use correct spacing
Context: ... files in ExampleFiles.common.v4 #120. ### Removed - Remove ModuleBuilder patch. ...

(QB_NEW_EN_OTHER_ERROR_IDS_5)


[grammar] ~16-~16: Use correct spacing
Context: ...). ### Removed - Remove ModuleBuilder patch. ### Changed - `PSSAResource.common.v5.Tests...

(QB_NEW_EN_OTHER_ERROR_IDS_5)


[grammar] ~21-~21: Use correct spacing
Context: ...Tests` - Target all source files #163. ## [0.17.2] - 2025-02-28 ### Fixed - Now ...

(QB_NEW_EN_OTHER_ERROR_IDS_5)

🔇 Additional comments (2)
CHANGELOG.md (1)

18-21: Changelog entry clearly documents scope expansion.

The “Changed” entry for PSSAResource targeting all source files (issue #163) is clear and aligned with the PR.

source/Tests/QA/ExampleFiles.common.v4.Tests.ps1 (1)

31-31: Good: examples are now filtered via repository exclusions.

This aligns with the new ability to filter out example files and should reduce false positives.

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

🔭 Outside diff range comments (1)
source/Tests/QA/PSSAResource.common.v5.Tests.ps1 (1)

121-131: Undefined variable \$dscResourcesPsm1File will break test discovery

$invokeScriptAnalyzerParameters.Path = $dscResourcesPsm1File.FullName refers to a variable that is no longer created after the switch from module to source files.
Accessing .FullName on $null throws before the Context block overrides the path, so the whole Describe fails early.

-            Path                = $dscResourcesPsm1File.FullName
+            # Initial value is unused once overridden below, keep it safe.
+            Path                = $null

Or create an appropriate placeholder variable derived from $sourceFiles.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0d990cc and 61aa076.

📒 Files selected for processing (1)
  • source/Tests/QA/PSSAResource.common.v5.Tests.ps1 (6 hunks)

Copy link
Member

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

Reviewed 2 of 5 files at r2, 1 of 2 files at r3, 2 of 2 files at r4, all commit messages.
Reviewable status: all files reviewed, 4 unresolved discussions (waiting on @dan-hughes)

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 (1)
source/DscResource.Test.psm1 (1)

2-2: Typo fix applied; good to go.

The grammar correction matches the earlier suggestion and improves clarity. No functional impact.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 61aa076 and 961a5d5.

📒 Files selected for processing (2)
  • CHANGELOG.md (1 hunks)
  • source/DscResource.Test.psm1 (1 hunks)
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: johlju
PR: dsccommunity/DscResource.Test#167
File: source/Private/Test-FileContainsClassResource.ps1:44-56
Timestamp: 2025-08-09T19:29:36.323Z
Learning: In the DscResource.Test repository, DSC resource attributes are consistently written as `[DscResource(...)]` rather than using variations like `[DscResourceAttribute()]` or fully qualified names like `[Microsoft.PowerShell.DesiredStateConfiguration.DscResource()]`. The Test-FileContainsClassResource function should focus on detecting the standard `[DscResource(...)]` pattern that is actually used in the codebase.
📚 Learning: 2025-08-09T19:29:36.323Z
Learnt from: johlju
PR: dsccommunity/DscResource.Test#167
File: source/Private/Test-FileContainsClassResource.ps1:44-56
Timestamp: 2025-08-09T19:29:36.323Z
Learning: In the DscResource.Test repository, DSC resource attributes are consistently written as `[DscResource(...)]` rather than using variations like `[DscResourceAttribute()]` or fully qualified names like `[Microsoft.PowerShell.DesiredStateConfiguration.DscResource()]`. The Test-FileContainsClassResource function should focus on detecting the standard `[DscResource(...)]` pattern that is actually used in the codebase.

Applied to files:

  • source/DscResource.Test.psm1
  • CHANGELOG.md
🪛 LanguageTool
CHANGELOG.md

[grammar] ~25-~25: Use correct spacing
Context: ...Tests` - Target all source files #163. ## [0.17.2] - 2025-02-28 ### Fixed - Now ...

(QB_NEW_EN_OTHER_ERROR_IDS_5)

⏰ 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). (6)
  • GitHub Check: dsccommunity.DscResource.Test (Test Test Windows (PS))
  • GitHub Check: dsccommunity.DscResource.Test (Test Test Windows (WPS))
  • GitHub Check: dsccommunity.DscResource.Test (Test Integration)
  • GitHub Check: dsccommunity.DscResource.Test (Test Test Linux)
  • GitHub Check: dsccommunity.DscResource.Test (Test Test macOS)
  • GitHub Check: dsccommunity.DscResource.Test (Build Package Module)

@codecov
Copy link

codecov bot commented Aug 10, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 80%. Comparing base (8cd2b14) to head (746ce73).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files

Impacted file tree graph

@@         Coverage Diff         @@
##           main   #164   +/-   ##
===================================
  Coverage    80%    80%           
===================================
  Files        42     42           
  Lines       550    550           
===================================
  Hits        443    443           
  Misses      107    107           
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@johlju
Copy link
Member

johlju commented Aug 10, 2025

Waiting for your response on a code rabbit comment before merging. Also, running these tests on the built module would make module's class types etc. available when parsing the script, that will not be the case when scanning the source files as suggested here. Do you think this will be a problem? 🤔

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

🔭 Outside diff range comments (1)
source/Tests/QA/PSSAResource.common.v5.Tests.ps1 (1)

129-129: Remove stale variable reference for Path

$dscResourcesPsm1File isn’t defined; Path is set per-file later anyway. Drop the initial assignment to avoid confusion.

-            Path                = $dscResourcesPsm1File.FullName
+            # Path is assigned per file in the Context block below.
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 961a5d5 and 29d5340.

📒 Files selected for processing (1)
  • source/Tests/QA/PSSAResource.common.v5.Tests.ps1 (6 hunks)
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: johlju
PR: dsccommunity/DscResource.Test#167
File: source/Private/Test-FileContainsClassResource.ps1:44-56
Timestamp: 2025-08-09T19:29:36.323Z
Learning: In the DscResource.Test repository, DSC resource attributes are consistently written as `[DscResource(...)]` rather than using variations like `[DscResourceAttribute()]` or fully qualified names like `[Microsoft.PowerShell.DesiredStateConfiguration.DscResource()]`. The Test-FileContainsClassResource function should focus on detecting the standard `[DscResource(...)]` pattern that is actually used in the codebase.
📚 Learning: 2025-08-09T19:29:36.323Z
Learnt from: johlju
PR: dsccommunity/DscResource.Test#167
File: source/Private/Test-FileContainsClassResource.ps1:44-56
Timestamp: 2025-08-09T19:29:36.323Z
Learning: In the DscResource.Test repository, DSC resource attributes are consistently written as `[DscResource(...)]` rather than using variations like `[DscResourceAttribute()]` or fully qualified names like `[Microsoft.PowerShell.DesiredStateConfiguration.DscResource()]`. The Test-FileContainsClassResource function should focus on detecting the standard `[DscResource(...)]` pattern that is actually used in the codebase.

Applied to files:

  • source/Tests/QA/PSSAResource.common.v5.Tests.ps1
🔇 Additional comments (2)
source/Tests/QA/PSSAResource.common.v5.Tests.ps1 (2)

84-85: Good: faster enumeration with -Filter and two passes

Switching to two Get-ChildItem calls with -Filter and using AddRange is a solid perf win over -Include on large trees. Nice.


124-124: Add “PS Script Analyzer on Source Files” tag for consistency

After searching the repo, the only references to
Common Tests - PS Script Analyzer on Resource Files live in the two Pester test files (PSSAResource.common.v5.Tests.ps1 and PSSAResource.common.v4.Tests.ps1), and no CI workflows or scripts explicitly target that tag. It’s safe to add the new tag here so that the Describe title and tag list align:

-Describe 'Common Tests - PS Script Analyzer on Source Files' -Tag @('DscPSSA', 'Common Tests - PS Script Analyzer on Resource Files') {
+Describe 'Common Tests - PS Script Analyzer on Source Files' -Tag @('DscPSSA', 'Common Tests - PS Script Analyzer on Source Files', 'Common Tests - PS Script Analyzer on Resource Files') {

@dan-hughes dan-hughes marked this pull request as ready for review August 10, 2025 11:49
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

🔭 Outside diff range comments (1)
source/Tests/QA/PSSAResource.common.v5.Tests.ps1 (1)

145-149: Avoid placeholder Path in hashtable; set Path only here

You overwrite Path here per file. Remove the initial Path assignment from $invokeScriptAnalyzerParameters to reduce confusion and potential nulls.

Example init (outside this block, replacing the earlier hashtable build):

$invokeScriptAnalyzerParameters = @{
    IncludeDefaultRules = $true
    IncludeRule         = @($PSSA_rule_config.required_rules + $PSSA_rule_config.flagged_rules + $PSSA_rule_config.ignore_rules)
    ErrorVariable       = 'MyErrors'
    # Path set per test file below
}
♻️ Duplicate comments (3)
source/Tests/QA/PSSAResource.common.v5.Tests.ps1 (3)

82-82: Prefer strongly-typed file list

Use List[System.IO.FileInfo] for type-safety and minor perf gains (avoids boxing), since you always store FileInfo objects.

-    $sourceFiles = [System.Collections.Generic.List[System.Object]]::new()
+    $sourceFiles = [System.Collections.Generic.List[System.IO.FileInfo]]::new()

158-169: Clearer quote stripping without regex

The current regex works but is hard to read and removes only a single leading/trailing quote. Trim whitespace then strip both ' and " using .Trim with a char array; it’s clearer and idempotent.

-                # Remove any starting or trailing ' and ".
-                $newItem = $rule -replace '^["'']|["'']$', ''
+                # Remove any surrounding whitespace and leading/trailing quote characters (' or ").
+                $newItem = $rule.Trim().Trim(@([char]39, [char]34))

209-213: Anchor prefix removal and escape dot

Ensure only the leading “DscResource.AnalyzerRules\” prefix is removed; escape the dot to avoid unintended matches.

-                Format-Table -AutoSize -Wrap -Property @{
+                Format-Table -AutoSize -Wrap -Property @{
                     Name       = 'RuleName'
-                    Expression = { $_.RuleName -replace 'DscResource.AnalyzerRules\\' }
+                    Expression = { $_.RuleName -replace '^DscResource\.AnalyzerRules\\' }
                 }, Severity, ScriptName, Line, Message |
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 29d5340 and fe3c27b.

📒 Files selected for processing (1)
  • source/Tests/QA/PSSAResource.common.v5.Tests.ps1 (6 hunks)
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: johlju
PR: dsccommunity/DscResource.Test#167
File: source/Private/Test-FileContainsClassResource.ps1:44-56
Timestamp: 2025-08-09T19:29:36.323Z
Learning: In the DscResource.Test repository, DSC resource attributes are consistently written as `[DscResource(...)]` rather than using variations like `[DscResourceAttribute()]` or fully qualified names like `[Microsoft.PowerShell.DesiredStateConfiguration.DscResource()]`. The Test-FileContainsClassResource function should focus on detecting the standard `[DscResource(...)]` pattern that is actually used in the codebase.
📚 Learning: 2025-08-09T19:29:36.323Z
Learnt from: johlju
PR: dsccommunity/DscResource.Test#167
File: source/Private/Test-FileContainsClassResource.ps1:44-56
Timestamp: 2025-08-09T19:29:36.323Z
Learning: In the DscResource.Test repository, DSC resource attributes are consistently written as `[DscResource(...)]` rather than using variations like `[DscResourceAttribute()]` or fully qualified names like `[Microsoft.PowerShell.DesiredStateConfiguration.DscResource()]`. The Test-FileContainsClassResource function should focus on detecting the standard `[DscResource(...)]` pattern that is actually used in the codebase.

Applied to files:

  • source/Tests/QA/PSSAResource.common.v5.Tests.ps1
🔇 Additional comments (3)
source/Tests/QA/PSSAResource.common.v5.Tests.ps1 (3)

84-85: LGTM: fast enumeration with -Filter + AddRange

Good switch to -Filter and AddRange; matches perf feedback and scales better on large trees.


97-105: LGTM: emit PSCustomObject for Pester -ForEach

Using [PSCustomObject] with File and DescriptiveName simplifies downstream binding and presentation.


154-154: LGTM: custom rule selection

Filtering custom rules via -like 'DscResource.AnalyzerRules*' is correct and keeps output focused.

Copy link
Member

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

Just a tiny comment, and need rebase - resolve the CodeRabbit comments if they are not relevant.

Reviewed 3 of 3 files at r5, 1 of 1 files at r7, all commit messages.
Reviewable status: all files reviewed, 10 unresolved discussions (waiting on @dan-hughes)


source/Tests/QA/PSSAResource.common.v5.Tests.ps1 line 102 at r7 (raw file):

        $descriptiveName = Get-RelativePathFromModuleRoot -FilePath $file.FullName -ModuleRootFilePath $resolvedProjectPath

        [PSCustomObject]@{

Space after the accelarator

Suggestion:

[PSCustomObject] @{

Copy link
Contributor Author

@dan-hughes dan-hughes left a comment

Choose a reason for hiding this comment

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

Reviewable status: 3 of 5 files reviewed, 8 unresolved discussions (waiting on @johlju)


source/Tests/QA/PSSAResource.common.v5.Tests.ps1 line 102 at r7 (raw file):

Previously, johlju (Johan Ljunggren) wrote…

Space after the accelarator

Done.

@dan-hughes
Copy link
Contributor Author

@johlju, all done.

@dan-hughes
Copy link
Contributor Author

@johlju, ready to go. Tested against SqlServerDsc. It found a few things there.

Copy link
Member

@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 2 of 2 files at r10, all commit messages.
Reviewable status: all files reviewed, 7 unresolved discussions (waiting on @dan-hughes)

@johlju
Copy link
Member

johlju commented Sep 1, 2025

This seems to work when running in SqlServerDsc (and fixing the code it fails on). I thought this would parse classes and see types that were not available, but seems it ignores SQL Server types which is good.

@johlju johlju merged commit 21dc7fb into dsccommunity:main Sep 1, 2025
11 of 12 checks passed
@dan-hughes dan-hughes deleted the test-ps1-files branch September 1, 2025 17:27
@dan-hughes
Copy link
Contributor Author

This seems to work when running in SqlServerDsc (and fixing the code it fails on). I thought this would parse classes and see types that were not available, but seems it ignores SQL Server types which is good.

Types in classes seem to be resolved when the module is imported. This is the one difference compared to script based resources.

This is what makes the localization tests a little interesting.

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.

PSSA HQRM Test should target all source files

2 participants