Skip to content

Conversation

@johlju
Copy link
Member

@johlju johlju commented Dec 9, 2025

Pull Request (PR) description

  • Added public command Get-SqlDscBackupFileList to read the list of database
    files contained in a SQL Server backup file. Useful for planning file
    relocations during restore operations (issue #2026).
  • Added public command Test-SqlDscBackupFile to verify the integrity of a
    SQL Server backup file (issue #2026).
  • Added public command Restore-SqlDscDatabase to restore SQL Server databases
    from backup files. Supports full, differential, transaction log, and file
    restores with options for file relocation (both simple path-based and
    explicit RelocateFile objects), point-in-time recovery, NoRecovery/Standby
    modes, and various performance tuning options (issue #2026).
  • Added public command Backup-SqlDscDatabase. Supports full, differential,
    and transaction log backups with options for compression, copy-only, checksum,
    and retention (issue #2365).

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

coderabbitai bot commented Dec 9, 2025

Walkthrough

Adds three public cmdlets for backup inspection, verification, and restore, a BackupFileSpec class, localization strings, extensive unit and integration tests, SMO test stubs, and CI/workflow updates; removes the Backup-SqlDscDatabase export and tweaks one OutputType attribute.

Changes

Cohort / File(s) Summary
New Public Commands
source/Public/Get-SqlDscBackupFileList.ps1, source/Public/Test-SqlDscBackupFile.ps1, source/Public/Restore-SqlDscDatabase.ps1
Added Get-SqlDscBackupFileList (reads .bak file file-list -> BackupFileSpec[]), Test-SqlDscBackupFile (invokes SMO.SqlVerify -> boolean), and Restore-SqlDscDatabase (rich restore cmdlet: restore types, relocation options, point-in-time, NoRecovery/Standby, ReplaceDatabase, PassThru, ShouldProcess).
Removed/Modified Export
source/Public/Backup-SqlDscDatabase.ps1
Removed an empty [OutputType()] attribute; function keeps [OutputType([Microsoft.SqlServer.Management.Smo.Database])]. Backup-SqlDscDatabase removed from exported surface.
New Class
source/Classes/002.BackupFileSpec.ps1
Added BackupFileSpec class with properties LogicalName, PhysicalName, Type, FileGroupName, Size, MaxSize and default + parameterized constructors.
Localization
source/en-US/SqlServerDsc.strings.psd1
Added localized strings for Restore-SqlDscDatabase, Test-SqlDscBackupFile, and Get-SqlDscBackupFileList (ShouldProcess messages, statuses, and errors).
Integration Tests & CI
azure-pipelines.yml, tests/Integration/Commands/Get-SqlDscBackupFileList.Integration.Tests.ps1, tests/Integration/Commands/Test-SqlDscBackupFile.Integration.Tests.ps1, tests/Integration/Commands/Restore-SqlDscDatabase.Integration.Tests.ps1, tests/Integration/Commands/README.md
Added three integration test scripts, wired them into CI pipeline, and documented new tests.
Unit Tests
tests/Unit/Classes/BackupFileSpec.Tests.ps1, tests/Unit/Public/Get-SqlDscBackupFileList.Tests.ps1, tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1, tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1
Added Pester unit tests covering constructors, parameter validation, mocked SMO interactions, and many restore scenarios.
SMO Test Stubs & Test Fixes
tests/Unit/Stubs/SMO.cs, tests/Unit/Public/Add-SqlDscFileGroup.Tests.ps1
Extended SMO stub with RestoreActionType, RelocateFile, RelocateFileList, and Restore (mock methods/properties); adjusted some unit tests to capture call results instead of Should -Not -Throw. Note: SMO.cs contains duplicated API definitions in the stub.
CI Type Loading Fixes
.github/workflows/code-analysis.yml, .github/workflows/code-analysis-built-module.yml, tests/QA/ScriptAnalyzer.Tests.ps1
Add-Type call for SMO stubs now includes -ReferencedAssemblies 'System.Data','System.Xml' to satisfy compilation/runtime for SMO stub.

Sequence Diagram(s)

sequenceDiagram
    autonumber
    actor User
    participant PS as PowerShell cmdlet
    participant FS as FileSystem
    participant SMO as SMO.Restore
    participant SQL as SQL Engine

    User->>PS: Invoke Restore-SqlDscDatabase(params, backupPath)
    alt simple relocation
        PS->>SMO: Create Restore + add BackupDeviceItem(backupPath)
        PS->>SMO: Call ReadFileList (via Get-SqlDscBackupFileList)
        SMO-->>PS: DataTable -> PS maps to BackupFileSpec[]
        PS->>PS: Build RelocateFile entries from DataFilePath/LogFilePath
        PS->>SMO: Add RelocateFiles
    else explicit relocation
        PS->>SMO: Add provided RelocateFile[] to Restore
    end
    PS->>SMO: Configure restore options (Action, NoRecovery, Standby, FileNumber, ToPointInTime, etc.)
    PS->>SQL: SMO.SqlVerify or SMO.SqlRestore invoked
    SQL-->>SMO: Return status/result
    SMO-->>PS: Success or throw error
    PS-->>User: Output restored Database object if -PassThru or raise terminating error
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

  • Areas needing careful review:
    • Restore-SqlDscDatabase: parameter-set validation and mutual exclusions (NoRecovery vs Standby, ReplaceDatabase logic).
    • Relocation handling: simple DataFilePath/LogFilePath mapping vs explicit RelocateFile[] handling and validation.
    • Point-in-time/stop-mark option parsing and conversions to SMO properties.
    • Error handling and localized messages (string keys usage).
    • SMO stub (tests/Unit/Stubs/SMO.cs): duplicated API definitions and correctness of mock behaviors.

Possibly related PRs

Pre-merge checks

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately and specifically describes the main addition to the changeset: a new Restore-SqlDscDatabase command for database restoration.
Description check ✅ Passed The description is well-related to the changeset, detailing four new public commands (Get-SqlDscBackupFileList, Test-SqlDscBackupFile, Restore-SqlDscDatabase, Backup-SqlDscDatabase) with their purposes and linked issues.
Linked Issues check ✅ Passed The PR addresses issue #2026 by implementing Restore-SqlDscDatabase with support for full, differential, log, and file restores; file relocation via simple paths and RelocateFile objects; point-in-time recovery; and NoRecovery/Standby modes, fulfilling the primary coding objectives.
Out of Scope Changes check ✅ Passed All changes align with the stated objectives: three new backup/restore commands, supporting infrastructure (BackupFileSpec class, localization strings, SMO stubs), and comprehensive unit/integration tests. No unrelated modifications detected.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@johlju johlju added the needs review The pull request needs a code review. label Dec 9, 2025
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

🧹 Nitpick comments (8)
source/Public/Restore-SqlDscDatabase.ps1 (2)

191-313: Prefer ::new() over New-Object for SMO types

To align with the module’s guideline of using static ::new() for .NET types, consider replacing the New-Object calls for SMO classes with the static constructor form. This is slightly more idiomatic and avoids reflection overhead.

For example:

-                # Create the restore object
-                $restore = New-Object -TypeName 'Microsoft.SqlServer.Management.Smo.Restore'
+                # Create the restore object
+                $restore = [Microsoft.SqlServer.Management.Smo.Restore]::new()
...
-                # Create and add the backup device
-                $backupDevice = New-Object -TypeName 'Microsoft.SqlServer.Management.Smo.BackupDeviceItem' -ArgumentList $BackupFile, 'File'
+                # Create and add the backup device
+                $backupDevice = [Microsoft.SqlServer.Management.Smo.BackupDeviceItem]::new(
+                    $BackupFile,
+                    [Microsoft.SqlServer.Management.Smo.DeviceType]::File
+                )
...
-                        $relocateFileObject = New-Object -TypeName 'Microsoft.SqlServer.Management.Smo.RelocateFile' -ArgumentList $logicalName, $newPhysicalName
+                        $relocateFileObject = [Microsoft.SqlServer.Management.Smo.RelocateFile]::new(
+                            $logicalName,
+                            $newPhysicalName
+                        )

Also applies to: 402-435, 473-475


506-531: Optionally validate point-in-time and mark options for non-log restores

The comment-based help documents ToPointInTime, StopAtMarkName, and StopBeforeMarkName as log-restore options, but they can currently be used with any RestoreType. SMO/SQL Server will ultimately reject invalid combinations, but adding an early validation would give clearer, localized errors and catch misuse sooner.

For example:

-                # Point-in-time recovery options
-                if ($PSBoundParameters.ContainsKey('ToPointInTime'))
+                # Point-in-time recovery options (only valid for log restores)
+                if ($PSBoundParameters.ContainsKey('ToPointInTime'))
                 {
+                    if ($RestoreType -ne 'Log')
+                    {
+                        $errorMessage = $script:localizedData.Restore_SqlDscDatabase_ToPointInTimeInvalidForRestoreType -f $RestoreType
+
+                        $PSCmdlet.ThrowTerminatingError(
+                            [System.Management.Automation.ErrorRecord]::new(
+                                [System.ArgumentException]::new($errorMessage),
+                                'RSDD0007',
+                                [System.Management.Automation.ErrorCategory]::InvalidArgument,
+                                $Name
+                            )
+                        )
+                    }
+
                     $restore.ToPointInTime = $ToPointInTime.ToString('yyyy-MM-ddTHH:mm:ss')
                 }

and similarly for StopAtMarkName/StopBeforeMarkName. This is not required for correctness, but would make the API behavior more self-documenting.

tests/Unit/Public/Get-SqlDscBackupFileList.Tests.ps1 (1)

86-108: Consider adding parameter set validation test.

Per coding guidelines, all public commands require parameter set validation tests. Add a test to verify the parameter set structure:

+        It 'Should have the correct parameters in parameter set <ExpectedParameterSetName>' -ForEach @(
+            @{
+                ExpectedParameterSetName = '__AllParameterSets'
+                ExpectedParameters = '[-ServerObject] <Server> [-BackupFile] <string> [[-FileNumber] <int>] [<CommonParameters>]'
+            }
+        ) {
+            $result = (Get-Command -Name 'Get-SqlDscBackupFileList').ParameterSets |
+                Where-Object -FilterScript { $_.Name -eq $ExpectedParameterSetName } |
+                Select-Object -Property @(
+                    @{ Name = 'ParameterSetName'; Expression = { $_.Name } },
+                    @{ Name = 'ParameterListAsString'; Expression = { $_.ToString() } }
+                )
+            $result.ParameterSetName | Should -Be $ExpectedParameterSetName
+            $result.ParameterListAsString | Should -Be $ExpectedParameters
+        }
tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1 (1)

88-108: Consider adding parameter set validation test.

Per coding guidelines, all public commands require parameter set validation tests. Add a test to verify the parameter set structure:

+        It 'Should have the correct parameters in parameter set <ExpectedParameterSetName>' -ForEach @(
+            @{
+                ExpectedParameterSetName = '__AllParameterSets'
+                ExpectedParameters = '[-ServerObject] <Server> [-BackupFile] <string> [[-FileNumber] <int>] [<CommonParameters>]'
+            }
+        ) {
+            $result = (Get-Command -Name 'Test-SqlDscBackupFile').ParameterSets |
+                Where-Object -FilterScript { $_.Name -eq $ExpectedParameterSetName } |
+                Select-Object -Property @(
+                    @{ Name = 'ParameterSetName'; Expression = { $_.Name } },
+                    @{ Name = 'ParameterListAsString'; Expression = { $_.ToString() } }
+                )
+            $result.ParameterSetName | Should -Be $ExpectedParameterSetName
+            $result.ParameterListAsString | Should -Be $ExpectedParameters
+        }
source/Public/Get-SqlDscBackupFileList.ps1 (1)

96-112: Consider using a more efficient array construction pattern.

The current $result += $fileSpec pattern creates a new array on each iteration. For better performance with larger file lists, consider using [System.Collections.Generic.List[BackupFileSpec]] or collecting via pipeline:

-            # Convert DataTable rows to BackupFileSpec objects
-            $result = @()
-
-            foreach ($row in $fileList.Rows)
+            # Convert DataTable rows to BackupFileSpec objects
+            $result = foreach ($row in $fileList.Rows)
             {
-                $fileSpec = [BackupFileSpec]::new(
+                [BackupFileSpec]::new(
                     $row['LogicalName'],
                     $row['PhysicalName'],
                     $row['Type'],
                     $row['FileGroupName'],
                     [System.Int64] $row['Size'],
                     [System.Int64] $row['MaxSize']
                 )
-
-                $result += $fileSpec
             }
 
             return $result

This is a minor optimization since backup file lists are typically small.

source/Public/Test-SqlDscBackupFile.ps1 (1)

76-79: Prefer ::new() over New-Object for .NET types.

Per coding guidelines, use the ::new() static method instead of New-Object for .NET types.

Apply this diff:

-            $restore = New-Object -TypeName 'Microsoft.SqlServer.Management.Smo.Restore'
+            $restore = [Microsoft.SqlServer.Management.Smo.Restore]::new()

             # Create and add the backup device
-            $backupDevice = New-Object -TypeName 'Microsoft.SqlServer.Management.Smo.BackupDeviceItem' -ArgumentList $BackupFile, 'File'
+            $backupDevice = [Microsoft.SqlServer.Management.Smo.BackupDeviceItem]::new($BackupFile, 'File')
tests/Unit/Classes/BackupFileSpec.Tests.ps1 (2)

51-60: Test structure relies on cross-block state; consider consolidation.

The first It block creates the instance, and the second It block asserts its type. While this works due to $script: scoping, Pester best practices recommend keeping assertions in the same It block as the operation being tested. Consider consolidating:

-        It 'Should be able to instantiate with default constructor' {
-            $script:mockBackupFileSpecInstance = InModuleScope -ScriptBlock {
-                [BackupFileSpec]::new()
-            }
-        }
-
-        It 'Should be of the correct type' {
-            $mockBackupFileSpecInstance | Should -Not -BeNullOrEmpty
-            $mockBackupFileSpecInstance.GetType().Name | Should -Be 'BackupFileSpec'
-        }
+        It 'Should be able to instantiate with default constructor and be of the correct type' {
+            $mockBackupFileSpecInstance = InModuleScope -ScriptBlock {
+                [BackupFileSpec]::new()
+            }
+
+            $mockBackupFileSpecInstance | Should -Not -BeNullOrEmpty
+            $mockBackupFileSpecInstance.GetType().Name | Should -Be 'BackupFileSpec'
+        }

62-71: Same consolidation opportunity for parameterized constructor tests.

-        It 'Should be able to instantiate with all parameters' {
-            $script:mockBackupFileSpecInstanceWithParams = InModuleScope -ScriptBlock {
-                [BackupFileSpec]::new('MyDatabase', 'C:\Data\MyDatabase.mdf', 'D', 'PRIMARY', 10485760, 1073741824)
-            }
-        }
-
-        It 'Should be of the correct type when instantiated with parameters' {
-            $mockBackupFileSpecInstanceWithParams | Should -Not -BeNullOrEmpty
-            $mockBackupFileSpecInstanceWithParams.GetType().Name | Should -Be 'BackupFileSpec'
-        }
+        It 'Should be able to instantiate with all parameters and be of the correct type' {
+            $mockBackupFileSpecInstanceWithParams = InModuleScope -ScriptBlock {
+                [BackupFileSpec]::new('MyDatabase', 'C:\Data\MyDatabase.mdf', 'D', 'PRIMARY', 10485760, 1073741824)
+            }
+
+            $mockBackupFileSpecInstanceWithParams | Should -Not -BeNullOrEmpty
+            $mockBackupFileSpecInstanceWithParams.GetType().Name | Should -Be 'BackupFileSpec'
+        }

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

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c8b881f and 2b0e8fc.

📒 Files selected for processing (1)
  • tests/Unit/Stubs/SMO.cs (2 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**

⚙️ CodeRabbit configuration file

**: # DSC Community Guidelines

Terminology

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

Build & Test Workflow Requirements

  • Run PowerShell script files from repository root
  • Setup build and test environment (once per pwsh session): ./build.ps1 -Tasks noop
  • Build project before running tests: ./build.ps1 -Tasks build
  • Always run tests in new pwsh session: Invoke-Pester -Path @({test paths}) -Output Detailed

File Organization

  • Public commands: source/Public/{CommandName}.ps1
  • Private functions: source/Private/{FunctionName}.ps1
  • Classes: source/Classes/{DependencyGroupNumber}.{ClassName}.ps1
  • Enums: source/Enum/{DependencyGroupNumber}.{EnumName}.ps1
  • Unit tests: tests/Unit/{Classes|Public|Private}/{Name}.Tests.ps1
  • Integration tests: tests/Integration/Commands/{CommandName}.Integration.Tests.ps1

Requirements

  • Follow instructions over existing code patterns
  • Follow PowerShell style and test guideline instructions strictly
  • Always update CHANGELOG.md Unreleased section
  • Localize all strings using string keys; remove any orphaned string keys
  • Check DscResource.Common before creating private functions
  • Separate reusable logic into private functions
  • DSC resources should always be created as class-based resources
  • Add unit tests for all commands/functions/resources
  • Add integration tests for all public commands and resources

Files:

  • tests/Unit/Stubs/SMO.cs
🧠 Learnings (6)
📓 Common learnings
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-11-27T17:58:02.422Z
Learning: Applies to **/tests/Integration/**/*.ps1 : Integration tests: use `Connect-SqlDscDatabaseEngine` for SQL Server DB session with correct CI credentials, and always follow with `Disconnect-SqlDscDatabaseEngine`
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-11-27T17:58:02.422Z
Learning: Applies to **/*.ps1 : Format public commands as `{Verb}-SqlDsc{Noun}` following PowerShell naming conventions
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-11-27T17:58:02.422Z
Learning: Applies to **/tests/**/*.tests.ps1 : Add `$env:SqlServerDscCI = $true` in `BeforeAll` block and remove in `AfterAll` block of unit tests
Learnt from: dan-hughes
Repo: dsccommunity/UpdateServicesDsc PR: 85
File: source/en-US/UpdateServicesDsc.strings.psd1:1-2
Timestamp: 2025-10-04T21:33:23.022Z
Learning: In UpdateServicesDsc (and similar DSC modules), the module-level localization file (source/en-US/<ModuleName>.strings.psd1) can be empty when DSC resources have their own localization files in source/DSCResources/<ResourceName>/en-US/DSC_<ResourceName>.strings.psd1. Automated tests verify localization completeness for resources. Don't flag empty module-level localization files as issues when resources have separate localization.
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-11-27T17:58:02.422Z
Learning: Applies to **/resources/**/*.ps1 : Add `InstanceName`, `ServerName`, and `Credential` to `$this.ExcludeDscProperties` in Database Engine resources
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-mof-resources.instructions.md:0-0
Timestamp: 2025-11-27T17:59:01.508Z
Learning: Applies to source/DSCResources/**/*.psm1 : Import localized strings using `Get-LocalizedData` at the module top level
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-mof-resources.instructions.md:0-0
Timestamp: 2025-11-27T17:59:01.508Z
Learning: Applies to source/DSCResources/**/*.psm1 : Use names returned from `Get-UICulture` for additional language folder names in DSC resources
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-11-27T17:59:27.205Z
Learning: Applies to **/*.[Tt]ests.ps1 : All public commands and class-based resources must have integration tests
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-11-27T17:58:02.422Z
Learning: Applies to **/tests/**/*.tests.ps1 : When unit tests test classes or commands containing SMO types like `[Microsoft.SqlServer.Management.Smo.*]`, ensure they are properly stubbed in SMO.cs
📚 Learning: 2025-11-27T17:58:02.422Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-11-27T17:58:02.422Z
Learning: Applies to **/tests/**/*.tests.ps1 : When unit tests test classes or commands containing SMO types like `[Microsoft.SqlServer.Management.Smo.*]`, ensure they are properly stubbed in SMO.cs

Applied to files:

  • tests/Unit/Stubs/SMO.cs
📚 Learning: 2025-11-27T17:58:02.422Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-11-27T17:58:02.422Z
Learning: Applies to **/tests/**/*.tests.ps1 : In unit tests: use SMO stub types from SMO.cs, never mock SMO types

Applied to files:

  • tests/Unit/Stubs/SMO.cs
📚 Learning: 2025-11-27T17:58:02.422Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-11-27T17:58:02.422Z
Learning: After changing SMO stub types in SMO.cs, run tests in a new PowerShell session for changes to take effect

Applied to files:

  • tests/Unit/Stubs/SMO.cs
📚 Learning: 2025-11-27T17:58:02.422Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-11-27T17:58:02.422Z
Learning: Applies to **/tests/**/*.tests.ps1 : Load SMO stub types in unit test files using `Add-Type -Path "$PSScriptRoot/../Stubs/SMO.cs"`

Applied to files:

  • tests/Unit/Stubs/SMO.cs
📚 Learning: 2025-08-17T10:13:30.079Z
Learnt from: johlju
Repo: dsccommunity/SqlServerDsc PR: 2136
File: source/Public/Remove-SqlDscLogin.ps1:104-108
Timestamp: 2025-08-17T10:13:30.079Z
Learning: In SqlServerDsc unit tests, SMO object stubs (like Login objects) should have properly mocked Parent properties with correct Server stub types and valid InstanceName values, rather than handling null Parent scenarios in production code.

Applied to files:

  • tests/Unit/Stubs/SMO.cs
🪛 GitHub Actions: Code analysis (built module)
tests/Unit/Stubs/SMO.cs

[error] 7-7: Add-Type failed: The type or namespace name 'Data' does not exist in the namespace 'System' (are you missing an assembly reference?).

🪛 GitHub Actions: Code analysis (source)
tests/Unit/Stubs/SMO.cs

[error] 7-7: Add-Type failed: The type or namespace name 'Data' does not exist in the namespace 'System' (are you missing an assembly reference?). Command: Add-Type -Path './tests/Unit/Stubs/SMO.cs'

⏰ 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 (3)
tests/Unit/Stubs/SMO.cs (3)

1696-1708: LGTM!

The RestoreActionType enum is properly defined with appropriate values for database restore operations.


1710-1734: LGTM!

The RelocateFile and RelocateFileList classes are correctly implemented following the stub's patterns. The constructors and properties match the SMO API structure.


1736-1816: Well-structured mock class, but blocked by DataTable dependency.

The Restore class is well-designed with comprehensive mock tracking properties and test hooks. The implementation follows the same pattern as the Backup class and provides good testing capabilities.

However, the use of System.Data.DataTable at lines 1779 and 1805 is causing the compilation failure flagged in the comment for line 7. Once that issue is resolved, this class will be ready.

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

🧹 Nitpick comments (3)
tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1 (1)

88-123: Tighten parameter property assertions for mandatory/optional parameters.

The parameter property tests work, but using Should -Contain $true / -Not -Contain $true on Attributes.Mandatory is slightly indirect. To match the project’s unit-test style, consider asserting directly on the boolean:

-        It 'Should have mandatory ServerObject parameter' {
-            $result = (Get-Command -Name 'Test-SqlDscBackupFile').Parameters['ServerObject']
-            $result.Attributes.Mandatory | Should -Contain $true
-        }
+        It 'Should have mandatory ServerObject parameter' {
+            $result = (Get-Command -Name 'Test-SqlDscBackupFile').Parameters['ServerObject']
+            $result.Attributes.Mandatory | Should -BeTrue
+        }

-        It 'Should have mandatory BackupFile parameter' {
-            $result = (Get-Command -Name 'Test-SqlDscBackupFile').Parameters['BackupFile']
-            $result.Attributes.Mandatory | Should -Contain $true
-        }
+        It 'Should have mandatory BackupFile parameter' {
+            $result = (Get-Command -Name 'Test-SqlDscBackupFile').Parameters['BackupFile']
+            $result.Attributes.Mandatory | Should -BeTrue
+        }

-        It 'Should have optional FileNumber parameter' {
-            $result = (Get-Command -Name 'Test-SqlDscBackupFile').Parameters['FileNumber']
-            $result.Attributes.Mandatory | Should -Not -Contain $true
-        }
+        It 'Should have optional FileNumber parameter' {
+            $result = (Get-Command -Name 'Test-SqlDscBackupFile').Parameters['FileNumber']
+            $result.Attributes.Mandatory | Should -BeFalse
+        }

This aligns more closely with the recommended “Parameter property tests should verify mandatory parameter attributes using Should -BeTrue assertions”.

As per coding guidelines for unit tests, parameter property checks should use direct -BeTrue/-BeFalse assertions.

source/Public/Test-SqlDscBackupFile.ps1 (1)

69-113: Consider using ::new() instead of New-Object for SMO instances.

The core logic and error handling look solid:

  • Localized Write-Debug messages before/after SqlVerify.
  • Proper construction of an ErrorRecord and use of $PSCmdlet.ThrowTerminatingError() in the catch block.

To align more closely with the module’s preferred .NET construction pattern, you could replace New-Object with static ::new() calls for the SMO types:

-            # Create the restore object for verification
-            $restore = New-Object -TypeName 'Microsoft.SqlServer.Management.Smo.Restore'
+            # Create the restore object for verification
+            $restore = [Microsoft.SqlServer.Management.Smo.Restore]::new()
@@
-            # Create and add the backup device
-            $backupDevice = New-Object -TypeName 'Microsoft.SqlServer.Management.Smo.BackupDeviceItem' -ArgumentList $BackupFile, 'File'
+            # Create and add the backup device
+            $backupDevice = [Microsoft.SqlServer.Management.Smo.BackupDeviceItem]::new($BackupFile, 'File')

This is a style/consistency improvement rather than a functional change.

As per coding guidelines, using ::new() for .NET types is preferred over New-Object.

tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1 (1)

325-413: Add explicit parameter property tests for mandatory parameters.

Parameter set validation and valid-values checks here are good, but the guidelines also call for explicit tests of mandatory attributes. For Restore-SqlDscDatabase, consider adding tests like:

It 'Should have ServerObject as a mandatory parameter in ServerObject parameter set' {
    $parameterInfo = (Get-Command -Name 'Restore-SqlDscDatabase').Parameters['ServerObject']
    $parameterInfo.Attributes.Mandatory | Should -BeTrue
}

It 'Should have Name as a mandatory parameter in ServerObject parameter set' {
    $parameterInfo = (Get-Command -Name 'Restore-SqlDscDatabase').Parameters['Name']
    $parameterInfo.Attributes.Mandatory | Should -BeTrue
}

It 'Should have BackupFile as a mandatory parameter in all parameter sets' {
    $parameterInfo = (Get-Command -Name 'Restore-SqlDscDatabase').Parameters['BackupFile']
    $parameterInfo.Attributes.Mandatory | Should -BeTrue
}

It 'Should have DatabaseObject as a mandatory parameter in DatabaseObject parameter sets' {
    $parameterInfo = (Get-Command -Name 'Restore-SqlDscDatabase').Parameters['DatabaseObject']
    $parameterInfo.Attributes.Mandatory | Should -BeTrue
}

You can scope or group these as needed, but having at least a few direct mandatory/optional checks will bring this file fully in line with the unit-test parameter property guidelines.

As per coding guidelines for tests, unit tests should include parameter property checks using Get-Command and Should -BeTrue for mandatory parameters.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2b0e8fc and 4dc245a.

📒 Files selected for processing (8)
  • .github/workflows/code-analysis-built-module.yml (1 hunks)
  • .github/workflows/code-analysis.yml (1 hunks)
  • source/Public/Get-SqlDscBackupFileList.ps1 (1 hunks)
  • source/Public/Restore-SqlDscDatabase.ps1 (1 hunks)
  • source/Public/Test-SqlDscBackupFile.ps1 (1 hunks)
  • tests/Unit/Classes/BackupFileSpec.Tests.ps1 (1 hunks)
  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1 (1 hunks)
  • tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1 (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • source/Public/Get-SqlDscBackupFileList.ps1
  • tests/Unit/Classes/BackupFileSpec.Tests.ps1
  • source/Public/Restore-SqlDscDatabase.ps1
🧰 Additional context used
📓 Path-based instructions (11)
**/*.ps1

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

**/*.ps1: Format public commands as {Verb}-SqlDsc{Noun} following PowerShell naming conventions
Format private functions as {Verb}-{Noun} following PowerShell naming conventions

Files:

  • tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1
  • source/Public/Test-SqlDscBackupFile.ps1
  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
**/*.[Tt]ests.ps1

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

**/*.[Tt]ests.ps1: All public commands, private functions and classes must have unit tests
All public commands and class-based resources must have integration tests
Use Pester v5 syntax only
Test code only inside Describe blocks
Assertions only in It blocks
Never test verbose messages, debug messages or parameter binding behavior
Pass all mandatory parameters to avoid prompts
Inside It blocks, assign unused return objects to $null (unless part of 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
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'
Public commands: Never use InModuleScope (unless retrieving localized strings or creating an object using an internal class)
Private functions/class resources: Always use InModuleScope
Each class method = separate 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
Spacing between blocks, arrange, act, and assert for readability
PascalCase: Describe, Context, It, Should, BeforeAll, BeforeEach, AfterAll, AfterEach
Use -BeTrue/-BeFalse never -Be $true/-Be $false
Never use Assert-MockCalled, use Should -Invoke instead
No Should -Not -Throw - invoke commands directly
Never add an empty -MockWith block
Omit -MockWith when returning $null
Set $PSDefaultParameterValues for Mock:ModuleName, Should:ModuleName, InModuleScope:ModuleName
Omit -ModuleName parameter on Pester commands
Never use Mock inside InModuleScope-block
Never use param() inside -MockWith scriptblock...

Files:

  • tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1
  • tests/Unit/Public/Restore-SqlDscDatabase.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 or creating an object using an internal class)
  • 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
  • Spacing between blocks, arrange, act, and assert for readability

Syntax Rules

  • PascalCase: Describe, Context, It, Should, BeforeAll, BeforeEach, AfterAll, AfterEach
  • Use -BeTrue/-BeFalse never -Be $true/-Be $false
  • Never use Assert-MockCalled, use Should -Invoke instead
  • No Should -Not -Throw - invoke commands directly
  • Never add an empty -MockWith block
  • Omit -MockWith when returning $null
  • Set $PSDefaultParameterValues for Mock:ModuleName, Should:ModuleName, `...

Files:

  • tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1
  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
tests/Unit/Public/*.[Tt]ests.ps1

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

Public commands: tests/Unit/Public/{Name}.Tests.ps1

Files:

  • tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1
  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
tests/[Uu]nit/**/*.[Tt]ests.ps1

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

tests/[Uu]nit/**/*.[Tt]ests.ps1: Test with localized strings using InModuleScope -ScriptBlock { $script:localizedData.Key }
Mock files using the $TestDrive variable (path to the test drive)
All public commands require parameter set validation tests
Use the exact setup block with BeforeDiscovery, BeforeAll, and AfterAll blocks including DscResource.Test module import and PSDefaultParameterValues configuration
Parameter set validation tests should use Get-Command with Where-Object filtering and Should assertions to verify ParameterSetName and ParameterListAsString
Parameter property tests should verify mandatory parameter attributes using Get-Command Parameters and Should -BeTrue assertions

Files:

  • tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1
  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1

⚙️ CodeRabbit configuration file

tests/[Uu]nit/**/*.[Tt]ests.ps1: # Unit Tests Guidelines

  • Test with localized strings: Use InModuleScope -ScriptBlock { $script:localizedData.Key }
  • Mock files: Use $TestDrive variable (path to the test drive)
  • All public commands require parameter set validation tests
  • After modifying classes, always run tests in new session (for changes to take effect)

Test Setup Requirements

Use this exact setup block before Describe:

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

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

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

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

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

    $PSDefaultParameterValues['InModuleScope:ModuleName'] = $script:moduleName
    $PSDefaultParameterValues['Mock:ModuleName'] = $script:moduleName
    $PSDefaultParameterValues['Should:ModuleName'] = $script:moduleName
}

AfterAll {
    $PSDefaultParameterValues.Remove('InModuleScope:ModuleName')
    $PSDefaultParameterValues.Remove('Mock:ModuleNam...

Files:

  • tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1
  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
tests/Unit/**/*.Tests.ps1

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

Unit tests should be located in tests/Unit/{Classes|Public|Private}/{Name}.Tests.ps1

Files:

  • tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1
  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
**/*.{ps1,psm1,psd1}

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

**/*.{ps1,psm1,psd1}: Use descriptive names with 3+ characters and no abbreviations for functions, parameters, variables, keywords, and classes
Use PascalCase with Verb-Noun format for function names, using approved PowerShell verbs
Use PascalCase for parameter names
Use camelCase for variable names
Use lower-case for keywords
Use PascalCase for class names
Include scope for script/global/environment variables using $script:, $global:, or $env: prefixes
Use 4 spaces for indentation, not tabs
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))
Avoid spaces on empty lines
Limit lines to 120 characters
Place opening brace on a new line, except for variable assignments
Add one newline after opening brace
Add two newlines after closing brace (one if followed by another brace or continuation)
Use single quotes unless variable expansion is needed (e.g., 'text' vs "text $variable")
Use single-line array syntax for simple arrays: @('one', 'two', 'three')
Use multi-line array syntax with each element on a separate line with proper indentation
Do not use the unary comma operator (,) in return statements to force an array
Use empty hashtable syntax: @{}
Place each hashtable property on a separate line with proper indentation
Use PascalCase for hashtable properties
Use single-line comment format # Comment (capitalized, on own line)
Use multi-line comment format <# Comment #> with opening and closing brackets on own lines and indented text
Never include commented-out code
Always add comment-based help to all functions and scripts with SYNOPSIS, DESCRIPTION (40+ chars), PARAMETER, and EXAMPLE sections before function/class declaration
Use comment-based help indentation with keywords at 4 spaces and text at 8 spaces
Include examples in comment-based help for all parameter sets and combinations
In comment-based help INPUTS sec...

Files:

  • tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1
  • source/Public/Test-SqlDscBackupFile.ps1
  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
**/*.{ps1,psm1}

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

Use $PSCmdlet.ThrowTerminatingError() for terminating errors (except in classes), use relevant error category, and in try-catch include exception with localized message

Files:

  • tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1
  • source/Public/Test-SqlDscBackupFile.ps1
  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
**

⚙️ CodeRabbit configuration file

**: # DSC Community Guidelines

Terminology

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

Build & Test Workflow Requirements

  • Run PowerShell script files from repository root
  • Setup build and test environment (once per pwsh session): ./build.ps1 -Tasks noop
  • Build project before running tests: ./build.ps1 -Tasks build
  • Always run tests in new pwsh session: Invoke-Pester -Path @({test paths}) -Output Detailed

File Organization

  • Public commands: source/Public/{CommandName}.ps1
  • Private functions: source/Private/{FunctionName}.ps1
  • Classes: source/Classes/{DependencyGroupNumber}.{ClassName}.ps1
  • Enums: source/Enum/{DependencyGroupNumber}.{EnumName}.ps1
  • Unit tests: tests/Unit/{Classes|Public|Private}/{Name}.Tests.ps1
  • Integration tests: tests/Integration/Commands/{CommandName}.Integration.Tests.ps1

Requirements

  • Follow instructions over existing code patterns
  • Follow PowerShell style and test guideline instructions strictly
  • Always update CHANGELOG.md Unreleased section
  • Localize all strings using string keys; remove any orphaned string keys
  • Check DscResource.Common before creating private functions
  • Separate reusable logic into private functions
  • DSC resources should always be created as class-based resources
  • Add unit tests for all commands/functions/resources
  • Add integration tests for all public commands and resources

Files:

  • tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1
  • source/Public/Test-SqlDscBackupFile.ps1
  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
{**/*.ps1,**/*.psm1,**/*.psd1}

⚙️ CodeRabbit configuration file

{**/*.ps1,**/*.psm1,**/*.psd1}: # PowerShell Guidelines

Naming

  • Use descriptive names (3+ characters, no abbreviations)
  • Functions: PascalCase with Verb-Noun format using approved verbs
  • Parameters: PascalCase
  • Variables: camelCase
  • Keywords: lower-case
  • Classes: PascalCase
  • Include scope for script/global/environment variables: $script:, $global:, $env:

File naming

  • Class files: ###.ClassName.ps1 format (e.g. 001.SqlReason.ps1, 004.StartupParameters.ps1)

Formatting

Indentation & Spacing

  • Use 4 spaces (no tabs)
  • One space around operators: $a = 1 + 2
  • One space between type and variable: [String] $name
  • One space between keyword and parenthesis: if ($condition)
  • No spaces on empty lines
  • Try to limit lines to 120 characters

Braces

  • Newline before opening brace (except variable assignments)
  • One newline after opening brace
  • Two newlines after closing brace (one if followed by another brace or continuation)

Quotes

  • Use single quotes unless variable expansion is needed: 'text' vs "text $variable"

Arrays

  • Single line: @('one', 'two', 'three')
  • Multi-line: each element on separate line with proper indentation
  • Do not use the unary comma operator (,) in return statements to force
    an array

Hashtables

  • Empty: @{}
  • Each property on separate line with proper indentation
  • Properties: Use PascalCase

Comments

  • Single line: # Comment (capitalized, on own line)
  • Multi-line: <# Comment #> format (opening and closing brackets on own line), and indent text
  • No commented-out code

Comment-based help

  • Always add comment-based help to all functions and scripts
  • Comment-based help: SYNOPSIS, DESCRIPTION (40+ chars), PARAMETER, EXAMPLE sections before function/class
  • Comment-based help indentation: keywords 4 spaces, text 8 spaces
  • Include examples for all parameter sets and combinations
  • INPUTS: List each pipeline‑accepted type as inline code with a 1‑line description...

Files:

  • tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1
  • source/Public/Test-SqlDscBackupFile.ps1
  • tests/Unit/Public/Restore-SqlDscDatabase.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 in PowerShell scripts
Use localized string keys from $script:localizedData, not hardcoded strings, in diagnostic messages
Reference localized strings using the syntax: Write-Verbose -Message ($script:localizedData.KeyName -f $value1)

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

Files:

  • source/Public/Test-SqlDscBackupFile.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-SqlDscBackupFile.ps1
source/Public/*.ps1

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

Public commands should be located in source/Public/{CommandName}.ps1

Files:

  • source/Public/Test-SqlDscBackupFile.ps1
🧠 Learnings (37)
📓 Common learnings
Learnt from: dan-hughes
Repo: dsccommunity/UpdateServicesDsc PR: 85
File: source/en-US/UpdateServicesDsc.strings.psd1:1-2
Timestamp: 2025-10-04T21:33:23.022Z
Learning: In UpdateServicesDsc (and similar DSC modules), the module-level localization file (source/en-US/<ModuleName>.strings.psd1) can be empty when DSC resources have their own localization files in source/DSCResources/<ResourceName>/en-US/DSC_<ResourceName>.strings.psd1. Automated tests verify localization completeness for resources. Don't flag empty module-level localization files as issues when resources have separate localization.
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-11-27T17:58:02.422Z
Learning: Applies to **/tests/Integration/**/*.ps1 : Integration tests: use `Connect-SqlDscDatabaseEngine` for SQL Server DB session with correct CI credentials, and always follow with `Disconnect-SqlDscDatabaseEngine`
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-11-27T17:58:02.422Z
Learning: Applies to **/*.ps1 : Format public commands as `{Verb}-SqlDsc{Noun}` following PowerShell naming conventions
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-11-27T17:58:02.422Z
Learning: Applies to **/tests/**/*.tests.ps1 : When unit tests test classes or commands containing SMO types like `[Microsoft.SqlServer.Management.Smo.*]`, ensure they are properly stubbed in SMO.cs
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-11-27T17:58:02.422Z
Learning: Applies to **/tests/**/*.tests.ps1 : Add `$env:SqlServerDscCI = $true` in `BeforeAll` block and remove in `AfterAll` block of unit tests
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-11-27T17:58:02.422Z
Learning: Applies to **/resources/**/*.ps1 : Add `InstanceName`, `ServerName`, and `Credential` to `$this.ExcludeDscProperties` in Database Engine resources
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-mof-resources.instructions.md:0-0
Timestamp: 2025-11-27T17:59:01.508Z
Learning: Applies to source/DSCResources/**/*.psm1 : Import localized strings using `Get-LocalizedData` at the module top level
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-11-27T17:58:02.422Z
Learning: After changing SMO stub types in SMO.cs, run tests in a new PowerShell session for changes to take effect
Learnt from: johlju
Repo: dsccommunity/SqlServerDsc PR: 2136
File: source/suffix.ps1:24-24
Timestamp: 2025-08-17T10:48:15.384Z
Learning: In source/suffix.ps1, the Write-Verbose message in the catch block for Import-SqlDscPreferredModule does not need localization because the exception message from Import-SqlDscPreferredModule is already localized by that command, making it an edge case exception to the localization guidelines.
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-mof-resources.instructions.md:0-0
Timestamp: 2025-11-27T17:59:01.508Z
Learning: Applies to source/DSCResources/**/*.psm1 : Use names returned from `Get-UICulture` for additional language folder names in DSC resources
📚 Learning: 2025-11-27T17:58:02.422Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-11-27T17:58:02.422Z
Learning: Applies to **/tests/**/*.tests.ps1 : Load SMO stub types in unit test files using `Add-Type -Path "$PSScriptRoot/../Stubs/SMO.cs"`

Applied to files:

  • .github/workflows/code-analysis-built-module.yml
  • .github/workflows/code-analysis.yml
  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-11-27T17:58:02.422Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-11-27T17:58:02.422Z
Learning: After changing SMO stub types in SMO.cs, run tests in a new PowerShell session for changes to take effect

Applied to files:

  • .github/workflows/code-analysis-built-module.yml
  • .github/workflows/code-analysis.yml
📚 Learning: 2025-11-27T17:58:02.422Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-11-27T17:58:02.422Z
Learning: Applies to **/tests/**/*.tests.ps1 : When unit tests test classes or commands containing SMO types like `[Microsoft.SqlServer.Management.Smo.*]`, ensure they are properly stubbed in SMO.cs

Applied to files:

  • .github/workflows/code-analysis-built-module.yml
  • .github/workflows/code-analysis.yml
  • tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1
  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-11-27T17:58:02.422Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-11-27T17:58:02.422Z
Learning: Applies to **/tests/**/*.tests.ps1 : In unit tests: use SMO stub types from SMO.cs, never mock SMO types

Applied to files:

  • .github/workflows/code-analysis-built-module.yml
  • .github/workflows/code-analysis.yml
  • tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1
  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-11-27T18:00:35.078Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines.instructions.md:0-0
Timestamp: 2025-11-27T18:00:35.078Z
Learning: Setup build and test environment using `./build.ps1 -Tasks noop` (once per pwsh session)

Applied to files:

  • .github/workflows/code-analysis-built-module.yml
  • .github/workflows/code-analysis.yml
📚 Learning: 2025-10-11T08:35:56.141Z
Learnt from: johlju
Repo: dsccommunity/SqlServerDsc PR: 2300
File: tests/Unit/DSC_SqlAGDatabase.Tests.ps1:22-22
Timestamp: 2025-10-11T08:35:56.141Z
Learning: In DSC Community projects, when writing error messages for missing DscResource.Test module dependency in unit test files (tests/[Uu]nit/**/*.[Tt]ests.ps1), the policy is: new code should instruct users to run ".\build.ps1 -Tasks noop" for quick test environment setup; existing code using ".\build.ps1 -Tasks build" is acceptable but slower since it also builds the project. The `noop` task is preferred as it assumes the module is already built before running tests, especially when tests run in a separate process.

Applied to files:

  • .github/workflows/code-analysis-built-module.yml
  • .github/workflows/code-analysis.yml
📚 Learning: 2025-11-27T17:58:02.422Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-11-27T17:58:02.422Z
Learning: Setup build and test environment (once per `pwsh` session): execute `./build.ps1 -Tasks noop`

Applied to files:

  • .github/workflows/code-analysis-built-module.yml
  • .github/workflows/code-analysis.yml
📚 Learning: 2025-10-11T08:18:26.062Z
Learnt from: johlju
Repo: dsccommunity/SqlServerDsc PR: 2300
File: tests/Unit/DSC_SqlAGDatabase.Tests.ps1:22-22
Timestamp: 2025-10-11T08:18:26.062Z
Learning: In unit test files (tests/[Uu]nit/**/*.[Tt]ests.ps1), when DscResource.Test module dependency is not found during BeforeDiscovery setup, the error message should instruct users to run ".\build.ps1 -Tasks noop" (not "build") because the noop task is designed for quick test environment setup. The build task is more extensive and unnecessary when tests run in a separate process, as the module should already be built before running tests.

Applied to files:

  • .github/workflows/code-analysis-built-module.yml
  • .github/workflows/code-analysis.yml
📚 Learning: 2025-11-27T18:00:35.078Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines.instructions.md:0-0
Timestamp: 2025-11-27T18:00:35.078Z
Learning: Build project before running tests using `./build.ps1 -Tasks build`

Applied to files:

  • .github/workflows/code-analysis-built-module.yml
  • .github/workflows/code-analysis.yml
📚 Learning: 2025-11-27T17:58:02.422Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-11-27T17:58:02.422Z
Learning: Build project before running tests: execute `./build.ps1 -Tasks build`

Applied to files:

  • .github/workflows/code-analysis-built-module.yml
  • .github/workflows/code-analysis.yml
📚 Learning: 2025-11-27T17:58:02.422Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-11-27T17:58:02.422Z
Learning: Applies to **/tests/**/*.tests.ps1 : Add `$env:SqlServerDscCI = $true` in `BeforeAll` block and remove in `AfterAll` block of unit tests

Applied to files:

  • tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1
  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-11-27T17:58:31.910Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-integration-tests.instructions.md:0-0
Timestamp: 2025-11-27T17:58:31.910Z
Learning: Applies to tests/Integration/**/*.Integration.Tests.ps1 : Integration tests must include the required setup block with BeforeDiscovery that imports DscResource.Test module and BeforeAll that imports the module being tested

Applied to files:

  • tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1
  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-11-27T18:00:20.934Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-unit-tests.instructions.md:0-0
Timestamp: 2025-11-27T18:00:20.934Z
Learning: Applies to tests/[Uu]nit/**/*.[Tt]ests.ps1 : Use the exact setup block with BeforeDiscovery, BeforeAll, and AfterAll blocks including DscResource.Test module import and PSDefaultParameterValues configuration

Applied to files:

  • tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1
  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-11-27T17:58:02.422Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-11-27T17:58:02.422Z
Learning: Applies to **/tests/Integration/**/*.ps1 : Integration tests: use `Connect-SqlDscDatabaseEngine` for SQL Server DB session with correct CI credentials, and always follow with `Disconnect-SqlDscDatabaseEngine`

Applied to files:

  • tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1
  • source/Public/Test-SqlDscBackupFile.ps1
  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-11-27T17:59:27.205Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-11-27T17:59:27.205Z
Learning: Applies to tests/Unit/Private/*.[Tt]ests.ps1 : Private functions: `tests/Unit/Private/{Name}.Tests.ps1`

Applied to files:

  • tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1
📚 Learning: 2025-11-27T17:59:27.205Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-11-27T17:59:27.205Z
Learning: Applies to **/*.[Tt]ests.ps1 : All public commands and class-based resources must have integration tests

Applied to files:

  • tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1
📚 Learning: 2025-11-27T17:59:27.205Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-11-27T17:59:27.205Z
Learning: Applies to **/*.[Tt]ests.ps1 : One `Describe` block per file matching the tested entity name

Applied to files:

  • tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1
📚 Learning: 2025-11-27T17:59:27.205Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-11-27T17:59:27.205Z
Learning: Applies to tests/Unit/Public/*.[Tt]ests.ps1 : Public commands: `tests/Unit/Public/{Name}.Tests.ps1`

Applied to files:

  • tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1
  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-11-27T18:00:20.934Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-unit-tests.instructions.md:0-0
Timestamp: 2025-11-27T18:00:20.934Z
Learning: Applies to tests/[Uu]nit/**/*.[Tt]ests.ps1 : Parameter property tests should verify mandatory parameter attributes using Get-Command Parameters and Should -BeTrue assertions

Applied to files:

  • tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1
  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-11-27T17:59:01.508Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-mof-resources.instructions.md:0-0
Timestamp: 2025-11-27T17:59:01.508Z
Learning: Applies to source/DSCResources/**/*.psm1 : `Test-TargetResource` function must return a boolean value ($true or $false)

Applied to files:

  • tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1
  • source/Public/Test-SqlDscBackupFile.ps1
📚 Learning: 2025-11-27T18:00:20.934Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-unit-tests.instructions.md:0-0
Timestamp: 2025-11-27T18:00:20.934Z
Learning: Applies to tests/[Uu]nit/**/*.[Tt]ests.ps1 : All public commands require parameter set validation tests

Applied to files:

  • tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1
  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-11-27T17:59:27.205Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-11-27T17:59:27.205Z
Learning: Applies to **/*.[Tt]ests.ps1 : Cover all scenarios and code paths

Applied to files:

  • tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1
  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-11-27T18:56:46.759Z
Learnt from: johlju
Repo: dsccommunity/SqlServerDsc PR: 1622
File: tests/Integration/DSC_SqlDatabase.Integration.Tests.ps1:1-30
Timestamp: 2025-11-27T18:56:46.759Z
Learning: Integration tests for MOF-based DSC resources (located in source/DSCResources/**) should use the Initialize-TestEnvironment pattern with -ResourceType 'Mof', not the BeforeDiscovery/BeforeAll pattern. The BeforeDiscovery/BeforeAll pattern is for class-based resources only.

Applied to files:

  • tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1
📚 Learning: 2025-11-27T17:59:27.205Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-11-27T17:59:27.205Z
Learning: Applies to **/*.[Tt]ests.ps1 : Avoid unnecessary remove/recreate cycles

Applied to files:

  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-08-17T10:13:30.079Z
Learnt from: johlju
Repo: dsccommunity/SqlServerDsc PR: 2136
File: source/Public/Remove-SqlDscLogin.ps1:104-108
Timestamp: 2025-08-17T10:13:30.079Z
Learning: In SqlServerDsc unit tests, SMO object stubs (like Login objects) should have properly mocked Parent properties with correct Server stub types and valid InstanceName values, rather than handling null Parent scenarios in production code.

Applied to files:

  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-11-27T17:59:27.205Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-11-27T17:59:27.205Z
Learning: Applies to **/*.[Tt]ests.ps1 : Mock variables prefix: 'mock'

Applied to files:

  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-11-27T17:59:27.205Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-11-27T17:59:27.205Z
Learning: Applies to **/*.[Tt]ests.ps1 : Mocking in `BeforeAll` (`BeforeEach` only when required)

Applied to files:

  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-11-27T17:59:27.205Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-11-27T17:59:27.205Z
Learning: Applies to **/*.[Tt]ests.ps1 : Never use `Mock` inside `InModuleScope`-block

Applied to files:

  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-11-27T17:59:27.205Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-11-27T17:59:27.205Z
Learning: Applies to **/*.[Tt]ests.ps1 : Never use `param()` inside `-MockWith` scriptblocks, parameters are auto-bound

Applied to files:

  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-11-27T17:59:27.205Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-11-27T17:59:27.205Z
Learning: Applies to **/*.[Tt]ests.ps1 : Omit `-MockWith` when returning `$null`

Applied to files:

  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-11-27T18:00:20.934Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-unit-tests.instructions.md:0-0
Timestamp: 2025-11-27T18:00:20.934Z
Learning: Applies to tests/[Uu]nit/**/*.[Tt]ests.ps1 : Parameter set validation tests should use Get-Command with Where-Object filtering and Should assertions to verify ParameterSetName and ParameterListAsString

Applied to files:

  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-11-27T18:00:35.078Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines.instructions.md:0-0
Timestamp: 2025-11-27T18:00:35.078Z
Learning: Follow PowerShell style and test guideline instructions strictly

Applied to files:

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

Applied to files:

  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-08-16T13:22:15.230Z
Learnt from: johlju
Repo: dsccommunity/SqlServerDsc PR: 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/Restore-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-11-27T17:58:31.910Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-integration-tests.instructions.md:0-0
Timestamp: 2025-11-27T17:58:31.910Z
Learning: Applies to tests/Integration/**/*.Integration.Tests.ps1 : Integration tests must cover all scenarios and code paths

Applied to files:

  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-11-27T17:58:31.910Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-integration-tests.instructions.md:0-0
Timestamp: 2025-11-27T17:58:31.910Z
Learning: Applies to tests/Integration/**/*.Integration.Tests.ps1 : Call commands with `-Force` parameter where applicable to avoid prompting

Applied to files:

  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: dsccommunity.SqlServerDsc (Build Package Module)
  • GitHub Check: PSScriptAnalyzer
🔇 Additional comments (7)
.github/workflows/code-analysis-built-module.yml (1)

49-49: Verify that new SMO stub types require System.Data and System.Xml assemblies.

The explicit -ReferencedAssemblies 'System.Data', 'System.Xml' parameter has been added to the Add-Type command that loads SMO.cs. Confirm that the new SMO types introduced in SMO.cs (such as RestoreActionType, RelocateFile, Restore) actually use types from these assemblies. Additionally, check if other workflows, test runners, or local test invocations that load SMO.cs need the same -ReferencedAssemblies parameter to maintain consistency.

.github/workflows/code-analysis.yml (1)

48-49: SMO stub loading change looks correct.

Adding -ReferencedAssemblies 'System.Data', 'System.Xml' to the Add-Type call is appropriate for compiling SMO.cs and should make the PSScriptAnalyzer job more reliable without affecting other steps.

tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1 (2)

1-50: Unit test scaffolding and SMO stub setup align with templates.

The BeforeDiscovery/BeforeAll/AfterAll blocks correctly load DscResource.Test, import SqlServerDsc, set $env:SqlServerDscCI, and load SMO.cs stubs, matching the prescribed unit-test pattern for this repo.

As per coding guidelines, this follows the required unit test setup.


75-86: Pipeline input handling test looks good.

The 'When pipeline is used' context correctly pipes ServerObject into Test-SqlDscBackupFile and asserts on the boolean result, validating the ValueFromPipeline behavior for ServerObject.

As per coding guidelines, this covers the pipeline usage scenario for the public command.

source/Public/Test-SqlDscBackupFile.ps1 (1)

1-67: Public command surface and help are well-structured.

The function exposes a clear public contract:

  • Comment-based help covers usage, pipeline input, and boolean output.
  • Parameters and attributes (mandatory flags, ValueFromPipeline, ValidateRange) match the intended behavior.
  • [CmdletBinding()] and [OutputType([System.Boolean])] are correctly applied, and the command name follows the {Verb}-SqlDsc{Noun} pattern.

No issues here from an API/UX standpoint.

As per coding guidelines, this matches the expected shape for a new public command.

tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1 (2)

1-50: Unit test harness and SMO stub loading are consistent with project patterns.

The file uses the standard BeforeDiscovery/BeforeAll/AfterAll scaffold, imports SqlServerDsc, sets $env:SqlServerDscCI, and loads SMO.cs stubs. This matches the documented unit test setup for SqlServerDsc.

As per coding guidelines and retrieved learnings, this is the expected pattern for unit tests using SMO stubs.


52-275: Restore behavior scenarios are well covered.

The contexts for existing databases, NoRecovery/Standby conflicts, non-log point-in-time/mark misuse, successful restores (Full/Diff/Log/Files), RelocateFile usage, and Refresh behavior collectively give strong coverage of the main restore flows and guard-rails without touching a real SQL instance (thanks to SMO stubs).

The tests also correctly:

  • Use Should -Throw with localized messages via InModuleScope only where needed.
  • Assign unused results to $result and assert on it, aligning with Pester and style guidelines.

No functional or structural issues spotted in these scenarios.

As per coding guidelines, this satisfies the requirement to cover key scenarios and code paths for the new public command.

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

🧹 Nitpick comments (2)
tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1 (2)

127-138: Strengthen pipeline test by adding mock setup.

The pipeline test context lacks mock configuration for New-Object, so it relies on the SMO stub's default MockSqlVerifyResult = $false behavior. This doesn't meaningfully validate that pipeline input works correctly—it only confirms the default stub outcome.

Consider adding a Mock setup in the BeforeAll block (similar to the other contexts) to explicitly control the verification result and demonstrate that the pipeline scenario behaves as intended.

Apply this diff to add mock setup:

     Context 'When pipeline is used' {
         BeforeAll {
             $mockServerObject = New-Object -TypeName 'Microsoft.SqlServer.Management.Smo.Server'
             $mockServerObject | Add-Member -MemberType 'NoteProperty' -Name 'InstanceName' -Value 'TestInstance' -Force
+
+            $script:mockRestoreObject = $null
+
+            Mock -CommandName New-Object -MockWith {
+                if ($TypeName -eq 'Microsoft.SqlServer.Management.Smo.Restore')
+                {
+                    $script:mockRestoreObject = [Microsoft.SqlServer.Management.Smo.Restore]::new()
+                    $script:mockRestoreObject.MockSqlVerifyResult = $true
+
+                    return $script:mockRestoreObject
+                }
+
+                # For BackupDeviceItem, use the real constructor
+                if ($TypeName -eq 'Microsoft.SqlServer.Management.Smo.BackupDeviceItem')
+                {
+                    return [Microsoft.SqlServer.Management.Smo.BackupDeviceItem]::new($ArgumentList[0], $ArgumentList[1])
+                }
+            }
         }
 
         It 'Should accept ServerObject from pipeline' {
             $result = $mockServerObject | Test-SqlDscBackupFile -BackupFile 'C:\Backups\ValidBackup.bak'
 
-            $result | Should -BeFalse
+            $result | Should -BeTrue
         }
     }

52-177: Consider adding error handling test scenarios.

The current tests cover happy paths (valid/invalid backup, with/without FileNumber, pipeline usage) and parameter validation. However, error handling scenarios are not tested, such as:

  • What happens when SqlVerify throws an exception?
  • How does the command handle non-existent backup files?
  • What if the ServerObject connection fails?

Adding these scenarios would provide more complete code coverage and ensure robust error handling behavior.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4dc245a and 836db79.

📒 Files selected for processing (3)
  • tests/QA/ScriptAnalyzer.Tests.ps1 (1 hunks)
  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1 (1 hunks)
  • tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1 (1 hunks)
🧰 Additional context used
📓 Path-based instructions (9)
**/*.ps1

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

**/*.ps1: Format public commands as {Verb}-SqlDsc{Noun} following PowerShell naming conventions
Format private functions as {Verb}-{Noun} following PowerShell naming conventions

Files:

  • tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1
  • tests/QA/ScriptAnalyzer.Tests.ps1
  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
**/*.[Tt]ests.ps1

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

**/*.[Tt]ests.ps1: All public commands, private functions and classes must have unit tests
All public commands and class-based resources must have integration tests
Use Pester v5 syntax only
Test code only inside Describe blocks
Assertions only in It blocks
Never test verbose messages, debug messages or parameter binding behavior
Pass all mandatory parameters to avoid prompts
Inside It blocks, assign unused return objects to $null (unless part of 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
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'
Public commands: Never use InModuleScope (unless retrieving localized strings or creating an object using an internal class)
Private functions/class resources: Always use InModuleScope
Each class method = separate 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
Spacing between blocks, arrange, act, and assert for readability
PascalCase: Describe, Context, It, Should, BeforeAll, BeforeEach, AfterAll, AfterEach
Use -BeTrue/-BeFalse never -Be $true/-Be $false
Never use Assert-MockCalled, use Should -Invoke instead
No Should -Not -Throw - invoke commands directly
Never add an empty -MockWith block
Omit -MockWith when returning $null
Set $PSDefaultParameterValues for Mock:ModuleName, Should:ModuleName, InModuleScope:ModuleName
Omit -ModuleName parameter on Pester commands
Never use Mock inside InModuleScope-block
Never use param() inside -MockWith scriptblock...

Files:

  • tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1
  • tests/QA/ScriptAnalyzer.Tests.ps1
  • tests/Unit/Public/Restore-SqlDscDatabase.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 or creating an object using an internal class)
  • 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
  • Spacing between blocks, arrange, act, and assert for readability

Syntax Rules

  • PascalCase: Describe, Context, It, Should, BeforeAll, BeforeEach, AfterAll, AfterEach
  • Use -BeTrue/-BeFalse never -Be $true/-Be $false
  • Never use Assert-MockCalled, use Should -Invoke instead
  • No Should -Not -Throw - invoke commands directly
  • Never add an empty -MockWith block
  • Omit -MockWith when returning $null
  • Set $PSDefaultParameterValues for Mock:ModuleName, Should:ModuleName, `...

Files:

  • tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1
  • tests/QA/ScriptAnalyzer.Tests.ps1
  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
tests/Unit/Public/*.[Tt]ests.ps1

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

Public commands: tests/Unit/Public/{Name}.Tests.ps1

Files:

  • tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1
  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
tests/[Uu]nit/**/*.[Tt]ests.ps1

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

tests/[Uu]nit/**/*.[Tt]ests.ps1: Test with localized strings using InModuleScope -ScriptBlock { $script:localizedData.Key }
Mock files using the $TestDrive variable (path to the test drive)
All public commands require parameter set validation tests
Use the exact setup block with BeforeDiscovery, BeforeAll, and AfterAll blocks including DscResource.Test module import and PSDefaultParameterValues configuration
Parameter set validation tests should use Get-Command with Where-Object filtering and Should assertions to verify ParameterSetName and ParameterListAsString
Parameter property tests should verify mandatory parameter attributes using Get-Command Parameters and Should -BeTrue assertions

Files:

  • tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1
  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1

⚙️ CodeRabbit configuration file

tests/[Uu]nit/**/*.[Tt]ests.ps1: # Unit Tests Guidelines

  • Test with localized strings: Use InModuleScope -ScriptBlock { $script:localizedData.Key }
  • Mock files: Use $TestDrive variable (path to the test drive)
  • All public commands require parameter set validation tests
  • After modifying classes, always run tests in new session (for changes to take effect)

Test Setup Requirements

Use this exact setup block before Describe:

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

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

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

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

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

    $PSDefaultParameterValues['InModuleScope:ModuleName'] = $script:moduleName
    $PSDefaultParameterValues['Mock:ModuleName'] = $script:moduleName
    $PSDefaultParameterValues['Should:ModuleName'] = $script:moduleName
}

AfterAll {
    $PSDefaultParameterValues.Remove('InModuleScope:ModuleName')
    $PSDefaultParameterValues.Remove('Mock:ModuleNam...

Files:

  • tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1
  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
tests/Unit/**/*.Tests.ps1

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

Unit tests should be located in tests/Unit/{Classes|Public|Private}/{Name}.Tests.ps1

Files:

  • tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1
  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
**/*.{ps1,psm1,psd1}

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

**/*.{ps1,psm1,psd1}: Use descriptive names with 3+ characters and no abbreviations for functions, parameters, variables, keywords, and classes
Use PascalCase with Verb-Noun format for function names, using approved PowerShell verbs
Use PascalCase for parameter names
Use camelCase for variable names
Use lower-case for keywords
Use PascalCase for class names
Include scope for script/global/environment variables using $script:, $global:, or $env: prefixes
Use 4 spaces for indentation, not tabs
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))
Avoid spaces on empty lines
Limit lines to 120 characters
Place opening brace on a new line, except for variable assignments
Add one newline after opening brace
Add two newlines after closing brace (one if followed by another brace or continuation)
Use single quotes unless variable expansion is needed (e.g., 'text' vs "text $variable")
Use single-line array syntax for simple arrays: @('one', 'two', 'three')
Use multi-line array syntax with each element on a separate line with proper indentation
Do not use the unary comma operator (,) in return statements to force an array
Use empty hashtable syntax: @{}
Place each hashtable property on a separate line with proper indentation
Use PascalCase for hashtable properties
Use single-line comment format # Comment (capitalized, on own line)
Use multi-line comment format <# Comment #> with opening and closing brackets on own lines and indented text
Never include commented-out code
Always add comment-based help to all functions and scripts with SYNOPSIS, DESCRIPTION (40+ chars), PARAMETER, and EXAMPLE sections before function/class declaration
Use comment-based help indentation with keywords at 4 spaces and text at 8 spaces
Include examples in comment-based help for all parameter sets and combinations
In comment-based help INPUTS sec...

Files:

  • tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1
  • tests/QA/ScriptAnalyzer.Tests.ps1
  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
**/*.{ps1,psm1}

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

Use $PSCmdlet.ThrowTerminatingError() for terminating errors (except in classes), use relevant error category, and in try-catch include exception with localized message

Files:

  • tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1
  • tests/QA/ScriptAnalyzer.Tests.ps1
  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
**

⚙️ CodeRabbit configuration file

**: # DSC Community Guidelines

Terminology

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

Build & Test Workflow Requirements

  • Run PowerShell script files from repository root
  • Setup build and test environment (once per pwsh session): ./build.ps1 -Tasks noop
  • Build project before running tests: ./build.ps1 -Tasks build
  • Always run tests in new pwsh session: Invoke-Pester -Path @({test paths}) -Output Detailed

File Organization

  • Public commands: source/Public/{CommandName}.ps1
  • Private functions: source/Private/{FunctionName}.ps1
  • Classes: source/Classes/{DependencyGroupNumber}.{ClassName}.ps1
  • Enums: source/Enum/{DependencyGroupNumber}.{EnumName}.ps1
  • Unit tests: tests/Unit/{Classes|Public|Private}/{Name}.Tests.ps1
  • Integration tests: tests/Integration/Commands/{CommandName}.Integration.Tests.ps1

Requirements

  • Follow instructions over existing code patterns
  • Follow PowerShell style and test guideline instructions strictly
  • Always update CHANGELOG.md Unreleased section
  • Localize all strings using string keys; remove any orphaned string keys
  • Check DscResource.Common before creating private functions
  • Separate reusable logic into private functions
  • DSC resources should always be created as class-based resources
  • Add unit tests for all commands/functions/resources
  • Add integration tests for all public commands and resources

Files:

  • tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1
  • tests/QA/ScriptAnalyzer.Tests.ps1
  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
{**/*.ps1,**/*.psm1,**/*.psd1}

⚙️ CodeRabbit configuration file

{**/*.ps1,**/*.psm1,**/*.psd1}: # PowerShell Guidelines

Naming

  • Use descriptive names (3+ characters, no abbreviations)
  • Functions: PascalCase with Verb-Noun format using approved verbs
  • Parameters: PascalCase
  • Variables: camelCase
  • Keywords: lower-case
  • Classes: PascalCase
  • Include scope for script/global/environment variables: $script:, $global:, $env:

File naming

  • Class files: ###.ClassName.ps1 format (e.g. 001.SqlReason.ps1, 004.StartupParameters.ps1)

Formatting

Indentation & Spacing

  • Use 4 spaces (no tabs)
  • One space around operators: $a = 1 + 2
  • One space between type and variable: [String] $name
  • One space between keyword and parenthesis: if ($condition)
  • No spaces on empty lines
  • Try to limit lines to 120 characters

Braces

  • Newline before opening brace (except variable assignments)
  • One newline after opening brace
  • Two newlines after closing brace (one if followed by another brace or continuation)

Quotes

  • Use single quotes unless variable expansion is needed: 'text' vs "text $variable"

Arrays

  • Single line: @('one', 'two', 'three')
  • Multi-line: each element on separate line with proper indentation
  • Do not use the unary comma operator (,) in return statements to force
    an array

Hashtables

  • Empty: @{}
  • Each property on separate line with proper indentation
  • Properties: Use PascalCase

Comments

  • Single line: # Comment (capitalized, on own line)
  • Multi-line: <# Comment #> format (opening and closing brackets on own line), and indent text
  • No commented-out code

Comment-based help

  • Always add comment-based help to all functions and scripts
  • Comment-based help: SYNOPSIS, DESCRIPTION (40+ chars), PARAMETER, EXAMPLE sections before function/class
  • Comment-based help indentation: keywords 4 spaces, text 8 spaces
  • Include examples for all parameter sets and combinations
  • INPUTS: List each pipeline‑accepted type as inline code with a 1‑line description...

Files:

  • tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1
  • tests/QA/ScriptAnalyzer.Tests.ps1
  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
🧠 Learnings (48)
📓 Common learnings
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-11-27T17:58:02.422Z
Learning: Applies to **/tests/**/*.tests.ps1 : When unit tests test classes or commands containing SMO types like `[Microsoft.SqlServer.Management.Smo.*]`, ensure they are properly stubbed in SMO.cs
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-11-27T17:58:02.422Z
Learning: After changing SMO stub types in SMO.cs, run tests in a new PowerShell session for changes to take effect
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-11-27T17:58:02.422Z
Learning: Applies to **/tests/Integration/**/*.ps1 : Integration tests: use `Connect-SqlDscDatabaseEngine` for SQL Server DB session with correct CI credentials, and always follow with `Disconnect-SqlDscDatabaseEngine`
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-11-27T17:58:02.422Z
Learning: Applies to **/tests/**/*.tests.ps1 : In unit tests: use SMO stub types from SMO.cs, never mock SMO types
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-11-27T17:58:02.422Z
Learning: Applies to **/tests/**/*.tests.ps1 : Load SMO stub types in unit test files using `Add-Type -Path "$PSScriptRoot/../Stubs/SMO.cs"`
Learnt from: dan-hughes
Repo: dsccommunity/UpdateServicesDsc PR: 85
File: source/en-US/UpdateServicesDsc.strings.psd1:1-2
Timestamp: 2025-10-04T21:33:23.022Z
Learning: In UpdateServicesDsc (and similar DSC modules), the module-level localization file (source/en-US/<ModuleName>.strings.psd1) can be empty when DSC resources have their own localization files in source/DSCResources/<ResourceName>/en-US/DSC_<ResourceName>.strings.psd1. Automated tests verify localization completeness for resources. Don't flag empty module-level localization files as issues when resources have separate localization.
📚 Learning: 2025-11-27T17:58:02.422Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-11-27T17:58:02.422Z
Learning: Applies to **/tests/**/*.tests.ps1 : Add `$env:SqlServerDscCI = $true` in `BeforeAll` block and remove in `AfterAll` block of unit tests

Applied to files:

  • tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1
  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-11-27T17:58:02.422Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-11-27T17:58:02.422Z
Learning: Applies to **/tests/**/*.tests.ps1 : When unit tests test classes or commands containing SMO types like `[Microsoft.SqlServer.Management.Smo.*]`, ensure they are properly stubbed in SMO.cs

Applied to files:

  • tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1
  • tests/QA/ScriptAnalyzer.Tests.ps1
  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-11-27T18:00:20.934Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-unit-tests.instructions.md:0-0
Timestamp: 2025-11-27T18:00:20.934Z
Learning: Applies to tests/[Uu]nit/**/*.[Tt]ests.ps1 : Use the exact setup block with BeforeDiscovery, BeforeAll, and AfterAll blocks including DscResource.Test module import and PSDefaultParameterValues configuration

Applied to files:

  • tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1
  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-11-27T17:58:31.910Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-integration-tests.instructions.md:0-0
Timestamp: 2025-11-27T17:58:31.910Z
Learning: Applies to tests/Integration/**/*.Integration.Tests.ps1 : Integration tests must include the required setup block with BeforeDiscovery that imports DscResource.Test module and BeforeAll that imports the module being tested

Applied to files:

  • tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1
  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-11-27T17:59:27.205Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-11-27T17:59:27.205Z
Learning: Applies to tests/Unit/Private/*.[Tt]ests.ps1 : Private functions: `tests/Unit/Private/{Name}.Tests.ps1`

Applied to files:

  • tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1
📚 Learning: 2025-11-27T17:59:27.205Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-11-27T17:59:27.205Z
Learning: Applies to **/*.[Tt]ests.ps1 : All public commands, private functions and classes must have unit tests

Applied to files:

  • tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1
📚 Learning: 2025-11-27T18:00:20.934Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-unit-tests.instructions.md:0-0
Timestamp: 2025-11-27T18:00:20.934Z
Learning: Applies to tests/[Uu]nit/**/*.[Tt]ests.ps1 : Mock files using the `$TestDrive` variable (path to the test drive)

Applied to files:

  • tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1
📚 Learning: 2025-11-27T17:58:02.422Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-11-27T17:58:02.422Z
Learning: Applies to **/tests/**/*.tests.ps1 : Load SMO stub types in unit test files using `Add-Type -Path "$PSScriptRoot/../Stubs/SMO.cs"`

Applied to files:

  • tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1
  • tests/QA/ScriptAnalyzer.Tests.ps1
  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-11-27T17:59:27.205Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-11-27T17:59:27.205Z
Learning: Applies to **/*.[Tt]ests.ps1 : All public commands and class-based resources must have integration tests

Applied to files:

  • tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1
📚 Learning: 2025-11-27T17:59:27.205Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-11-27T17:59:27.205Z
Learning: Applies to tests/Unit/Classes/*.[Tt]ests.ps1 : Class resources: `tests/Unit/Classes/{Name}.Tests.ps1`

Applied to files:

  • tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1
📚 Learning: 2025-11-27T17:59:27.205Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-11-27T17:59:27.205Z
Learning: Applies to **/*.[Tt]ests.ps1 : Use `-BeTrue`/`-BeFalse` never `-Be $true`/`-Be $false`

Applied to files:

  • tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1
📚 Learning: 2025-08-17T10:13:30.079Z
Learnt from: johlju
Repo: dsccommunity/SqlServerDsc PR: 2136
File: source/Public/Remove-SqlDscLogin.ps1:104-108
Timestamp: 2025-08-17T10:13:30.079Z
Learning: In SqlServerDsc unit tests, SMO object stubs (like Login objects) should have properly mocked Parent properties with correct Server stub types and valid InstanceName values, rather than handling null Parent scenarios in production code.

Applied to files:

  • tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1
  • tests/QA/ScriptAnalyzer.Tests.ps1
  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-09-25T16:38:08.867Z
Learnt from: johlju
Repo: dsccommunity/ActiveDirectoryDsc PR: 741
File: tests/Integration/MSFT_ADReadOnlyDomainControllerAccount.Integration.Tests.ps1:102-104
Timestamp: 2025-09-25T16:38:08.867Z
Learning: The PowerShell guideline "Use -BeTrue/-BeFalse; never use -Be $true/-Be $false" applies only when the actual return value is a boolean. When a cmdlet returns string values like 'True' or 'False', Should -Be 'True' is the appropriate assertion.

Applied to files:

  • tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1
📚 Learning: 2025-09-25T16:38:08.867Z
Learnt from: johlju
Repo: dsccommunity/ActiveDirectoryDsc PR: 741
File: tests/Integration/MSFT_ADReadOnlyDomainControllerAccount.Integration.Tests.ps1:102-104
Timestamp: 2025-09-25T16:38:08.867Z
Learning: Test-DscConfiguration cmdlet returns string values 'True' or 'False', not boolean values. Therefore, Should -Be 'True' is correct, and Should -BeTrue would be incorrect for this cmdlet.

Applied to files:

  • tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1
📚 Learning: 2025-11-27T17:59:27.205Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-11-27T17:59:27.205Z
Learning: Applies to **/*.[Tt]ests.ps1 : `Context` descriptions start with 'When'

Applied to files:

  • tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1
📚 Learning: 2025-10-22T17:32:29.221Z
Learnt from: johlju
Repo: dsccommunity/SqlServerDsc PR: 2314
File: tests/Integration/Commands/Get-SqlDscSetupLog.Integration.Tests.ps1:61-68
Timestamp: 2025-10-22T17:32:29.221Z
Learning: In Pester tests, never gate assertions with conditional logic (if/else blocks). Each test should directly assert the expected outcome. If a test needs to handle multiple scenarios, split it into separate test cases instead.

Applied to files:

  • tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1
📚 Learning: 2025-11-27T18:00:20.934Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-unit-tests.instructions.md:0-0
Timestamp: 2025-11-27T18:00:20.934Z
Learning: Applies to tests/[Uu]nit/**/*.[Tt]ests.ps1 : Parameter property tests should verify mandatory parameter attributes using Get-Command Parameters and Should -BeTrue assertions

Applied to files:

  • tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1
  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-08-09T19:29:36.323Z
Learnt from: johlju
Repo: dsccommunity/DscResource.Test PR: 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:

  • tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1
📚 Learning: 2025-11-27T17:59:27.205Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-11-27T17:59:27.205Z
Learning: Applies to **/*.[Tt]ests.ps1 : Assertions only in `It` blocks

Applied to files:

  • tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1
📚 Learning: 2025-11-27T17:59:01.508Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-mof-resources.instructions.md:0-0
Timestamp: 2025-11-27T17:59:01.508Z
Learning: Applies to source/DSCResources/**/*.psm1 : `Test-TargetResource` function must return a boolean value ($true or $false)

Applied to files:

  • tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1
📚 Learning: 2025-11-27T18:00:20.934Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-unit-tests.instructions.md:0-0
Timestamp: 2025-11-27T18:00:20.934Z
Learning: Applies to tests/[Uu]nit/**/*.[Tt]ests.ps1 : All public commands require parameter set validation tests

Applied to files:

  • tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1
  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-11-27T17:59:27.205Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-11-27T17:59:27.205Z
Learning: Applies to **/*.[Tt]ests.ps1 : Cover all scenarios and code paths

Applied to files:

  • tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1
  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-11-27T18:00:20.934Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-unit-tests.instructions.md:0-0
Timestamp: 2025-11-27T18:00:20.934Z
Learning: Applies to tests/[Uu]nit/**/*.[Tt]ests.ps1 : Parameter set validation tests should use Get-Command with Where-Object filtering and Should assertions to verify ParameterSetName and ParameterListAsString

Applied to files:

  • tests/Unit/Public/Test-SqlDscBackupFile.Tests.ps1
  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-11-27T17:58:02.422Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-11-27T17:58:02.422Z
Learning: After changing SMO stub types in SMO.cs, run tests in a new PowerShell session for changes to take effect

Applied to files:

  • tests/QA/ScriptAnalyzer.Tests.ps1
📚 Learning: 2025-11-27T17:58:02.422Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-11-27T17:58:02.422Z
Learning: Applies to **/tests/**/*.tests.ps1 : In unit tests: use SMO stub types from SMO.cs, never mock SMO types

Applied to files:

  • tests/QA/ScriptAnalyzer.Tests.ps1
  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-12-04T17:07:00.186Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-powershell.instructions.md:0-0
Timestamp: 2025-12-04T17:07:00.186Z
Learning: Applies to **/*.{ps1,psm1,psd1} : Use full type names when type casting

Applied to files:

  • tests/QA/ScriptAnalyzer.Tests.ps1
📚 Learning: 2025-11-27T17:59:27.205Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-11-27T17:59:27.205Z
Learning: Applies to **/*.[Tt]ests.ps1 : Avoid unnecessary remove/recreate cycles

Applied to files:

  • tests/QA/ScriptAnalyzer.Tests.ps1
  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-11-27T18:00:35.078Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines.instructions.md:0-0
Timestamp: 2025-11-27T18:00:35.078Z
Learning: Run PowerShell script files from repository root

Applied to files:

  • tests/QA/ScriptAnalyzer.Tests.ps1
📚 Learning: 2025-12-04T17:07:00.186Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-powershell.instructions.md:0-0
Timestamp: 2025-12-04T17:07:00.186Z
Learning: Applies to **/*.{ps1,psm1,psd1} : Use full type names for parameters

Applied to files:

  • tests/QA/ScriptAnalyzer.Tests.ps1
📚 Learning: 2025-11-27T17:58:02.422Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-11-27T17:58:02.422Z
Learning: Applies to **/tests/Integration/**/*.ps1 : Integration tests: use `Connect-SqlDscDatabaseEngine` for SQL Server DB session with correct CI credentials, and always follow with `Disconnect-SqlDscDatabaseEngine`

Applied to files:

  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-11-27T17:58:31.910Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-integration-tests.instructions.md:0-0
Timestamp: 2025-11-27T17:58:31.910Z
Learning: Applies to tests/Integration/**/*.Integration.Tests.ps1 : Integration tests must cover all scenarios and code paths

Applied to files:

  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-11-27T17:59:27.205Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-11-27T17:59:27.205Z
Learning: Applies to **/*.[Tt]ests.ps1 : Mock variables prefix: 'mock'

Applied to files:

  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-11-27T17:59:27.205Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-11-27T17:59:27.205Z
Learning: Applies to **/*.[Tt]ests.ps1 : Mocking in `BeforeAll` (`BeforeEach` only when required)

Applied to files:

  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-11-27T17:59:27.205Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-11-27T17:59:27.205Z
Learning: Applies to **/*.[Tt]ests.ps1 : Never use `Mock` inside `InModuleScope`-block

Applied to files:

  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-11-27T17:59:27.205Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-11-27T17:59:27.205Z
Learning: Applies to **/*.[Tt]ests.ps1 : Never use `param()` inside `-MockWith` scriptblocks, parameters are auto-bound

Applied to files:

  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-11-27T17:59:27.205Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-11-27T17:59:27.205Z
Learning: Applies to **/*.[Tt]ests.ps1 : Omit `-MockWith` when returning `$null`

Applied to files:

  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-08-16T13:22:15.230Z
Learnt from: johlju
Repo: dsccommunity/SqlServerDsc PR: 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/Restore-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-08-17T10:15:48.194Z
Learnt from: johlju
Repo: dsccommunity/SqlServerDsc PR: 2136
File: tests/Unit/Public/Remove-SqlDscLogin.Tests.ps1:36-39
Timestamp: 2025-08-17T10:15:48.194Z
Learning: Public command unit tests guideline: Never use InModuleScope unless accessing localized strings from $script:localizedData. PSDefaultParameterValues for InModuleScope should be kept in public command tests to support localized string retrieval when necessary.

Applied to files:

  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-11-27T17:59:01.508Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-mof-resources.instructions.md:0-0
Timestamp: 2025-11-27T17:59:01.508Z
Learning: Applies to source/DSCResources/**/*.psm1 : `Set-TargetResource` and `Test-TargetResource` must have identical parameters

Applied to files:

  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-11-27T18:00:35.078Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines.instructions.md:0-0
Timestamp: 2025-11-27T18:00:35.078Z
Learning: Follow PowerShell style and test guideline instructions strictly

Applied to files:

  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-08-17T10:59:03.955Z
Learnt from: johlju
Repo: dsccommunity/SqlServerDsc PR: 2136
File: source/Public/Remove-SqlDscLogin.ps1:59-77
Timestamp: 2025-08-17T10:59:03.955Z
Learning: In PowerShell, mandatory parameters with [Parameter(Mandatory = $true)] automatically guard against $null values and don't require additional [ValidateNotNull()] or [ValidateNotNullOrEmpty()] attributes, as these validations are redundant with the mandatory parameter behavior.

Applied to files:

  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-08-28T17:10:34.765Z
Learnt from: johlju
Repo: dsccommunity/SqlServerDsc PR: 2150
File: source/Classes/020.SqlAgentAlert.ps1:198-217
Timestamp: 2025-08-28T17:10:34.765Z
Learning: DSC properties with default values (e.g., `$Ensure = 'Present'`) are always present in the properties hashtable passed to validation methods, even when not explicitly specified by the user.

Applied to files:

  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-12-04T17:07:00.186Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-powershell.instructions.md:0-0
Timestamp: 2025-12-04T17:07:00.186Z
Learning: Applies to **/*.{ps1,psm1,psd1} : Use `[Parameter()]` attribute on all parameters with `[Parameter(Mandatory = $true)]` for mandatory parameters

Applied to files:

  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-11-27T17:59:27.205Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-11-27T17:59:27.205Z
Learning: Applies to **/*.[Tt]ests.ps1 : Pass all mandatory parameters to avoid prompts

Applied to files:

  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-11-27T17:59:01.508Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-mof-resources.instructions.md:0-0
Timestamp: 2025-11-27T17:59:01.508Z
Learning: Applies to source/DSCResources/**/*.psm1 : Unused mandatory parameters in `Set-TargetResource` and `Test-TargetResource` should include "Not used in <function_name>" in the help comment

Applied to files:

  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-11-27T17:59:01.508Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-mof-resources.instructions.md:0-0
Timestamp: 2025-11-27T17:59:01.508Z
Learning: Applies to source/DSCResources/**/*.psm1 : `Get-TargetResource` should remove non-mandatory parameters that are never used

Applied to files:

  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
📚 Learning: 2025-12-04T17:07:00.186Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-powershell.instructions.md:0-0
Timestamp: 2025-12-04T17:07:00.186Z
Learning: Applies to **/*.{ps1,psm1,psd1} : Do not use default values for mandatory or switch parameters

Applied to files:

  • tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: dsccommunity.SqlServerDsc (Build Package Module)
  • GitHub Check: PSScriptAnalyzer
  • GitHub Check: PSScriptAnalyzer
🔇 Additional comments (9)
tests/QA/ScriptAnalyzer.Tests.ps1 (1)

42-42: LGTM!

The addition of System.Data and System.Xml to the referenced assemblies correctly supports the expanded SMO stub types introduced in this PR.

tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1 (8)

53-95: LGTM!

The test context correctly validates that Full restores throw an error when the database exists without ReplaceDatabase, while Differential, Log, and Files restores proceed without error. The mock object ordering has been properly addressed from the previous review.


97-116: LGTM!

The test correctly validates that NoRecovery and Standby parameters are mutually exclusive and throws the appropriate error when both are specified.


118-143: LGTM!

The test context correctly validates that point-in-time recovery parameters (ToPointInTime, StopAtMarkName, StopBeforeMarkName) are restricted to Log restore types, as they should not be used with Full, Differential, or Files restores.


145-252: LGTM!

Comprehensive test coverage for successful restore scenarios including all restore types (Full, Differential, Log, Files), recovery options (NoRecovery, Standby), database replacement, data integrity options (Checksum), access restrictions (RestrictedUser), replication handling (KeepReplication), backup selection (FileNumber), point-in-time recovery, and performance tuning options (BlockSize, BufferCount, MaxTransferSize).


254-275: LGTM!

The test correctly validates the use of explicit RelocateFile objects to specify custom file locations during restore.


277-298: LGTM!

The test correctly validates that the Databases.Refresh() method is called when the -Refresh parameter is specified, using a script-scoped tracking variable to verify the method invocation.


300-323: LGTM!

The test correctly validates the DatabaseObject parameter set functionality. The mock object creation order has been properly addressed from the previous review.


325-482: LGTM!

Comprehensive parameter validation tests covering all four parameter sets (ServerObject, ServerObjectSimpleRelocate, DatabaseObject, DatabaseObjectSimpleRelocate), default parameter set validation, valid values for RestoreType and BlockSize parameters, and mandatory parameter verification across all parameter sets. The tests follow the required patterns from the coding guidelines.

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

# Loading mocked classes
Add-Type -Path (Join-Path -Path (Join-Path -Path $PSScriptRoot -ChildPath '../Stubs') -ChildPath 'SMO.cs')
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

Add required assembly references when loading SMO stubs.

The SMO stub loading is missing the -ReferencedAssemblies parameter that was added to the QA test file (line 42 of tests/QA/ScriptAnalyzer.Tests.ps1). The SMO stubs now include Restore-related types that require System.Data and System.Xml assemblies, and their absence could cause type loading failures.

Apply this diff:

-    Add-Type -Path (Join-Path -Path (Join-Path -Path $PSScriptRoot -ChildPath '../Stubs') -ChildPath 'SMO.cs')
+    Add-Type -Path (Join-Path -Path (Join-Path -Path $PSScriptRoot -ChildPath '../Stubs') -ChildPath 'SMO.cs') -ReferencedAssemblies 'System.Data', 'System.Xml'
🤖 Prompt for AI Agents
In tests/Unit/Public/Restore-SqlDscDatabase.Tests.ps1 around line 34, the
Add-Type call loading the SMO stub is missing the -ReferencedAssemblies
parameter; update the Add-Type invocation to include the required referenced
assemblies (at minimum 'System.Data' and 'System.Xml') so the Restore-related
types in the SMO stub resolve correctly, e.g. add -ReferencedAssemblies
@('System.Data','System.Xml') to the Add-Type call.

@codecov
Copy link

codecov bot commented Dec 9, 2025

Codecov Report

❌ Patch coverage is 81.60000% with 23 lines in your changes missing coverage. Please review.
✅ Project coverage is 94%. Comparing base (443a52f) to head (836db79).

Files with missing lines Patch % Lines
source/Public/Restore-SqlDscDatabase.ps1 80% 18 Missing ⚠️
source/Public/Get-SqlDscBackupFileList.ps1 75% 3 Missing ⚠️
source/Public/Test-SqlDscBackupFile.ps1 84% 2 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@          Coverage Diff          @@
##           main   #2367    +/-   ##
=====================================
- Coverage    94%     94%    -1%     
=====================================
  Files       167     171     +4     
  Lines      9864    9989   +125     
=====================================
+ Hits       9303    9405   +102     
- Misses      561     584    +23     
Flag Coverage Δ
unit 94% <81%> (-1%) ⬇️
Files with missing lines Coverage Δ
source/Classes/002.BackupFileSpec.ps1 100% <100%> (ø)
source/Public/Backup-SqlDscDatabase.ps1 96% <ø> (ø)
source/Public/Test-SqlDscBackupFile.ps1 84% <84%> (ø)
source/Public/Get-SqlDscBackupFileList.ps1 75% <75%> (ø)
source/Public/Restore-SqlDscDatabase.ps1 80% <80%> (ø)
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

needs review The pull request needs a code review.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Restore-SqlDscDatabase: New command proposal

1 participant