From 82d6efe37cac638299d01917d189a9bce7210562 Mon Sep 17 00:00:00 2001 From: Daniel Scott-Raynsford Date: Thu, 24 Jul 2025 19:48:27 -0700 Subject: [PATCH] New Instructions: PowerShell Pester v5 Testing Guidelines (#122) * CHANGE: Add PowerShell Pester v5 Testing Guidelines - Introduced a new guide for PowerShell Pester testing best practices. - Covers file naming, test structure, core keywords, setup/teardown, assertions, mocking, and best practices. - Provides examples and configuration details for effective test execution. * CHANGE: Remove unnecessary code block from guidelines - Removed the empty PowerShell code block from the PowerShell Pester v5 testing guidelines. * CHANGE: Correct file naming pattern in guidelines - Updated the file naming pattern from '**/*.tests.ps1' to '**/*.Tests.ps1' for consistency with PowerShell Pester v5 conventions. --------- Co-authored-by: Matt Soucoup --- README.md | 1 + .../powershell-pester-5.instructions.md | 197 ++++++++++++++++++ 2 files changed, 198 insertions(+) create mode 100644 instructions/powershell-pester-5.instructions.md diff --git a/README.md b/README.md index 2d47a51..5140b6e 100644 --- a/README.md +++ b/README.md @@ -57,6 +57,7 @@ Team and project-specific instructions to enhance GitHub Copilot's behavior for | [Performance Optimization Best Practices](instructions/performance-optimization.instructions.md) | The most comprehensive, practical, and engineer-authored performance optimization instructions for all languages, frameworks, and stacks. Covers frontend, backend, and database best practices with actionable guidance, scenario-based checklists, troubleshooting, and pro tips. | [![Install in VS Code](https://img.shields.io/badge/VS_Code-Install-0098FF?style=flat-square&logo=visualstudiocode&logoColor=white)](https://vscode.dev/redirect?url=vscode%3Achat-instructions%2Finstall%3Furl%3Dhttps%3A%2F%2Fraw.githubusercontent.com%2Fgithub%2Fawesome-copilot%2Fmain%2Finstructions%2Fperformance-optimization.instructions.md) [![Install in VS Code](https://img.shields.io/badge/VS_Code_Insiders-Install-24bfa5?style=flat-square&logo=visualstudiocode&logoColor=white)](https://insiders.vscode.dev/redirect?url=vscode-insiders%3Achat-instructions%2Finstall%3Furl%3Dhttps%3A%2F%2Fraw.githubusercontent.com%2Fgithub%2Fawesome-copilot%2Fmain%2Finstructions%2Fperformance-optimization.instructions.md) | | [Playwright Typescript](instructions/playwright-typescript.instructions.md) | Playwright test generation instructions | [![Install in VS Code](https://img.shields.io/badge/VS_Code-Install-0098FF?style=flat-square&logo=visualstudiocode&logoColor=white)](https://vscode.dev/redirect?url=vscode%3Achat-instructions%2Finstall%3Furl%3Dhttps%3A%2F%2Fraw.githubusercontent.com%2Fgithub%2Fawesome-copilot%2Fmain%2Finstructions%2Fplaywright-typescript.instructions.md) [![Install in VS Code](https://img.shields.io/badge/VS_Code_Insiders-Install-24bfa5?style=flat-square&logo=visualstudiocode&logoColor=white)](https://insiders.vscode.dev/redirect?url=vscode-insiders%3Achat-instructions%2Finstall%3Furl%3Dhttps%3A%2F%2Fraw.githubusercontent.com%2Fgithub%2Fawesome-copilot%2Fmain%2Finstructions%2Fplaywright-typescript.instructions.md) | | [Power Platform Connectors Schema Development Instructions](instructions/power-platform-connector.instructions.md) | Comprehensive development guidelines for Power Platform Custom Connectors using JSON Schema definitions. Covers API definitions (Swagger 2.0), API properties, and settings configuration with Microsoft extensions. | [![Install in VS Code](https://img.shields.io/badge/VS_Code-Install-0098FF?style=flat-square&logo=visualstudiocode&logoColor=white)](https://vscode.dev/redirect?url=vscode%3Achat-instructions%2Finstall%3Furl%3Dhttps%3A%2F%2Fraw.githubusercontent.com%2Fgithub%2Fawesome-copilot%2Fmain%2Finstructions%2Fpower-platform-connector.instructions.md) [![Install in VS Code](https://img.shields.io/badge/VS_Code_Insiders-Install-24bfa5?style=flat-square&logo=visualstudiocode&logoColor=white)](https://insiders.vscode.dev/redirect?url=vscode-insiders%3Achat-instructions%2Finstall%3Furl%3Dhttps%3A%2F%2Fraw.githubusercontent.com%2Fgithub%2Fawesome-copilot%2Fmain%2Finstructions%2Fpower-platform-connector.instructions.md) | +| [PowerShell Pester v5 Testing Guidelines](instructions/powershell-pester-5.instructions.md) | PowerShell Pester testing best practices based on Pester v5 conventions | [![Install in VS Code](https://img.shields.io/badge/VS_Code-Install-0098FF?style=flat-square&logo=visualstudiocode&logoColor=white)](https://vscode.dev/redirect?url=vscode%3Achat-instructions%2Finstall%3Furl%3Dhttps%3A%2F%2Fraw.githubusercontent.com%2Fgithub%2Fawesome-copilot%2Fmain%2Finstructions%2Fpowershell-pester-5.instructions.md) [![Install in VS Code](https://img.shields.io/badge/VS_Code_Insiders-Install-24bfa5?style=flat-square&logo=visualstudiocode&logoColor=white)](https://insiders.vscode.dev/redirect?url=vscode-insiders%3Achat-instructions%2Finstall%3Furl%3Dhttps%3A%2F%2Fraw.githubusercontent.com%2Fgithub%2Fawesome-copilot%2Fmain%2Finstructions%2Fpowershell-pester-5.instructions.md) | | [PowerShell Cmdlet Development Guidelines](instructions/powershell.instructions.md) | PowerShell cmdlet and scripting best practices based on Microsoft guidelines | [![Install in VS Code](https://img.shields.io/badge/VS_Code-Install-0098FF?style=flat-square&logo=visualstudiocode&logoColor=white)](https://vscode.dev/redirect?url=vscode%3Achat-instructions%2Finstall%3Furl%3Dhttps%3A%2F%2Fraw.githubusercontent.com%2Fgithub%2Fawesome-copilot%2Fmain%2Finstructions%2Fpowershell.instructions.md) [![Install in VS Code](https://img.shields.io/badge/VS_Code_Insiders-Install-24bfa5?style=flat-square&logo=visualstudiocode&logoColor=white)](https://insiders.vscode.dev/redirect?url=vscode-insiders%3Achat-instructions%2Finstall%3Furl%3Dhttps%3A%2F%2Fraw.githubusercontent.com%2Fgithub%2Fawesome-copilot%2Fmain%2Finstructions%2Fpowershell.instructions.md) | | [Python Coding Conventions](instructions/python.instructions.md) | Python coding conventions and guidelines | [![Install in VS Code](https://img.shields.io/badge/VS_Code-Install-0098FF?style=flat-square&logo=visualstudiocode&logoColor=white)](https://vscode.dev/redirect?url=vscode%3Achat-instructions%2Finstall%3Furl%3Dhttps%3A%2F%2Fraw.githubusercontent.com%2Fgithub%2Fawesome-copilot%2Fmain%2Finstructions%2Fpython.instructions.md) [![Install in VS Code](https://img.shields.io/badge/VS_Code_Insiders-Install-24bfa5?style=flat-square&logo=visualstudiocode&logoColor=white)](https://insiders.vscode.dev/redirect?url=vscode-insiders%3Achat-instructions%2Finstall%3Furl%3Dhttps%3A%2F%2Fraw.githubusercontent.com%2Fgithub%2Fawesome-copilot%2Fmain%2Finstructions%2Fpython.instructions.md) | | [Quarkus MCP Server](instructions/quarkus-mcp-server-sse.instructions.md) | Quarkus and MCP Server with HTTP SSE transport development standards and instructions | [![Install in VS Code](https://img.shields.io/badge/VS_Code-Install-0098FF?style=flat-square&logo=visualstudiocode&logoColor=white)](https://vscode.dev/redirect?url=vscode%3Achat-instructions%2Finstall%3Furl%3Dhttps%3A%2F%2Fraw.githubusercontent.com%2Fgithub%2Fawesome-copilot%2Fmain%2Finstructions%2Fquarkus-mcp-server-sse.instructions.md) [![Install in VS Code](https://img.shields.io/badge/VS_Code_Insiders-Install-24bfa5?style=flat-square&logo=visualstudiocode&logoColor=white)](https://insiders.vscode.dev/redirect?url=vscode-insiders%3Achat-instructions%2Finstall%3Furl%3Dhttps%3A%2F%2Fraw.githubusercontent.com%2Fgithub%2Fawesome-copilot%2Fmain%2Finstructions%2Fquarkus-mcp-server-sse.instructions.md) | diff --git a/instructions/powershell-pester-5.instructions.md b/instructions/powershell-pester-5.instructions.md new file mode 100644 index 0000000..78b81ad --- /dev/null +++ b/instructions/powershell-pester-5.instructions.md @@ -0,0 +1,197 @@ +--- +applyTo: '**/*.Tests.ps1' +description: 'PowerShell Pester testing best practices based on Pester v5 conventions' +--- + +# PowerShell Pester v5 Testing Guidelines + +This guide provides PowerShell-specific instructions for creating automated tests using PowerShell Pester v5 module. Follow PowerShell cmdlet development guidelines in [powershell.instructions.md](./powershell.instructions.md) for general PowerShell scripting best practices. + +## File Naming and Structure + +- **File Convention:** Use `*.Tests.ps1` naming pattern +- **Placement:** Place test files next to tested code or in dedicated test directories +- **Import Pattern:** Use `BeforeAll { . $PSScriptRoot/FunctionName.ps1 }` to import tested functions +- **No Direct Code:** Put ALL code inside Pester blocks (`BeforeAll`, `Describe`, `Context`, `It`, etc.) + +## Test Structure Hierarchy + +```powershell +BeforeAll { # Import tested functions } +Describe 'FunctionName' { + Context 'When condition' { + BeforeAll { # Setup for context } + It 'Should behavior' { # Individual test } + AfterAll { # Cleanup for context } + } +} +``` + +## Core Keywords + +- **`Describe`**: Top-level grouping, typically named after function being tested +- **`Context`**: Sub-grouping within Describe for specific scenarios +- **`It`**: Individual test cases, use descriptive names +- **`Should`**: Assertion keyword for test validation +- **`BeforeAll/AfterAll`**: Setup/teardown once per block +- **`BeforeEach/AfterEach`**: Setup/teardown before/after each test + +## Setup and Teardown + +- **`BeforeAll`**: Runs once at start of containing block, use for expensive operations +- **`BeforeEach`**: Runs before every `It` in block, use for test-specific setup +- **`AfterEach`**: Runs after every `It`, guaranteed even if test fails +- **`AfterAll`**: Runs once at end of block, use for cleanup +- **Variable Scoping**: `BeforeAll` variables available to child blocks (read-only), `BeforeEach/It/AfterEach` share same scope + +## Assertions (Should) + +- **Basic Comparisons**: `-Be`, `-BeExactly`, `-Not -Be` +- **Collections**: `-Contain`, `-BeIn`, `-HaveCount` +- **Numeric**: `-BeGreaterThan`, `-BeLessThan`, `-BeGreaterOrEqual` +- **Strings**: `-Match`, `-Like`, `-BeNullOrEmpty` +- **Types**: `-BeOfType`, `-BeTrue`, `-BeFalse` +- **Files**: `-Exist`, `-FileContentMatch` +- **Exceptions**: `-Throw`, `-Not -Throw` + +## Mocking + +- **`Mock CommandName { ScriptBlock }`**: Replace command behavior +- **`-ParameterFilter`**: Mock only when parameters match condition +- **`-Verifiable`**: Mark mock as requiring verification +- **`Should -Invoke`**: Verify mock was called specific number of times +- **`Should -InvokeVerifiable`**: Verify all verifiable mocks were called +- **Scope**: Mocks default to containing block scope + +```powershell +Mock Get-Service { @{ Status = 'Running' } } -ParameterFilter { $Name -eq 'TestService' } +Should -Invoke Get-Service -Exactly 1 -ParameterFilter { $Name -eq 'TestService' } +``` + +## Test Cases (Data-Driven Tests) + +Use `-TestCases` or `-ForEach` for parameterized tests: + +```powershell +It 'Should return for ' -TestCases @( + @{ Input = 'value1'; Expected = 'result1' } + @{ Input = 'value2'; Expected = 'result2' } +) { + Get-Function $Input | Should -Be $Expected +} +``` + +## Data-Driven Tests + +- **`-ForEach`**: Available on `Describe`, `Context`, and `It` for generating multiple tests from data +- **`-TestCases`**: Alias for `-ForEach` on `It` blocks (backwards compatibility) +- **Hashtable Data**: Each item defines variables available in test (e.g., `@{ Name = 'value'; Expected = 'result' }`) +- **Array Data**: Uses `$_` variable for current item +- **Templates**: Use `` in test names for dynamic expansion + +```powershell +# Hashtable approach +It 'Returns for ' -ForEach @( + @{ Name = 'test1'; Expected = 'result1' } + @{ Name = 'test2'; Expected = 'result2' } +) { Get-Function $Name | Should -Be $Expected } + +# Array approach +It 'Contains <_>' -ForEach 'item1', 'item2' { Get-Collection | Should -Contain $_ } +``` + +## Tags + +- **Available on**: `Describe`, `Context`, and `It` blocks +- **Filtering**: Use `-TagFilter` and `-ExcludeTagFilter` with `Invoke-Pester` +- **Wildcards**: Tags support `-like` wildcards for flexible filtering + +```powershell +Describe 'Function' -Tag 'Unit' { + It 'Should work' -Tag 'Fast', 'Stable' { } + It 'Should be slow' -Tag 'Slow', 'Integration' { } +} + +# Run only fast unit tests +Invoke-Pester -TagFilter 'Unit' -ExcludeTagFilter 'Slow' +``` + +## Skip + +- **`-Skip`**: Available on `Describe`, `Context`, and `It` to skip tests +- **Conditional**: Use `-Skip:$condition` for dynamic skipping +- **Runtime Skip**: Use `Set-ItResult -Skipped` during test execution (setup/teardown still run) + +```powershell +It 'Should work on Windows' -Skip:(-not $IsWindows) { } +Context 'Integration tests' -Skip { } +``` + +## Error Handling + +- **Continue on Failure**: Use `Should.ErrorAction = 'Continue'` to collect multiple failures +- **Stop on Critical**: Use `-ErrorAction Stop` for pre-conditions +- **Test Exceptions**: Use `{ Code } | Should -Throw` for exception testing + +## Best Practices + +- **Descriptive Names**: Use clear test descriptions that explain behavior +- **AAA Pattern**: Arrange (setup), Act (execute), Assert (verify) +- **Isolated Tests**: Each test should be independent +- **Avoid Aliases**: Use full cmdlet names (`Where-Object` not `?`) +- **Single Responsibility**: One assertion per test when possible +- **Test File Organization**: Group related tests in Context blocks. Context blocks can be nested. + +## Example Test Pattern + +```powershell +BeforeAll { + . $PSScriptRoot/Get-UserInfo.ps1 +} + +Describe 'Get-UserInfo' { + Context 'When user exists' { + BeforeAll { + Mock Get-ADUser { @{ Name = 'TestUser'; Enabled = $true } } + } + + It 'Should return user object' { + $result = Get-UserInfo -Username 'TestUser' + $result | Should -Not -BeNullOrEmpty + $result.Name | Should -Be 'TestUser' + } + + It 'Should call Get-ADUser once' { + Get-UserInfo -Username 'TestUser' + Should -Invoke Get-ADUser -Exactly 1 + } + } + + Context 'When user does not exist' { + BeforeAll { + Mock Get-ADUser { throw "User not found" } + } + + It 'Should throw exception' { + { Get-UserInfo -Username 'NonExistent' } | Should -Throw "*not found*" + } + } +} +``` + +## Configuration + +Configuration is defined **outside** test files when calling `Invoke-Pester` to control execution behavior. + +```powershell +# Create configuration (Pester 5.2+) +$config = New-PesterConfiguration +$config.Run.Path = './Tests' +$config.Output.Verbosity = 'Detailed' +$config.TestResult.Enabled = $true +$config.TestResult.OutputFormat = 'NUnitXml' +$config.Should.ErrorAction = 'Continue' +Invoke-Pester -Configuration $config +``` + +**Key Sections**: Run (Path, Exit), Filter (Tag, ExcludeTag), Output (Verbosity), TestResult (Enabled, OutputFormat), CodeCoverage (Enabled, Path), Should (ErrorAction), Debug