diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index a78e9d8d..083f3075 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -22,7 +22,7 @@ // Use 'postCreateCommand' to run commands after the container is created. "postCreateCommand": "yarn install", - + // Configure tool-specific properties. "customizations": { "vscode": { @@ -33,7 +33,8 @@ "dbaeumer.vscode-eslint", "unifiedjs.vscode-mdx", "ms-vscode.powershell", - "EditorConfig.EditorConfig" + "EditorConfig.EditorConfig", + "github.vscode-github-actions" ] } } diff --git a/.editorconfig b/.editorconfig index 92beea7e..77a099a6 100644 --- a/.editorconfig +++ b/.editorconfig @@ -9,5 +9,5 @@ trim_trailing_whitespace = true indent_size = 4 max_line_length = 80 -[*.{json,ps1xml,props,xml,yaml,css}] +[*.{js,jsx,ts,tsx,json,ps1xml,props,xml,yml,yaml,css}] indent_size = 2 diff --git a/.github/workflows/generate-pester-docs.yml b/.github/workflows/generate-pester-docs.yml new file mode 100644 index 00000000..df3985ad --- /dev/null +++ b/.github/workflows/generate-pester-docs.yml @@ -0,0 +1,98 @@ +name: Update Pester Docs +run-name: Update Pester ${{ github.event.inputs.docs_version }} docs to v${{ github.event.inputs.pester_version }} + +on: + workflow_dispatch: + inputs: + docs_version: + description: 'Docs version to update' + required: true + default: 'v5' + type: choice + options: + - Current + - v5 + - v4 + pester_version: + description: 'Pester version to use for docs generation. Format: 5.6.0 or 6.0.0-alpha1' + required: true + type: string + +jobs: + generate_docs: + name: Docs PR + runs-on: ubuntu-latest + env: + PESTER: ${{ github.event.inputs.pester_version }} + DOCS: ${{ github.event.inputs.docs_version }} + permissions: + contents: write + pull-requests: write + steps: + - name: Validate Pester version input + run: | + echo "Validating that the provided pester_version input is a valid version-format (x.y.z or x.y.z-suffix)" + echo "${{ env.PESTER }}" | grep -P '^\d+.\d+.\d+(?:-\w+)?$' + + - name: Checkout code + uses: actions/checkout@v4 + + # This step will also install and import modules incl. selected Pester-version + - name: Update Command Reference + id: commands + shell: pwsh + run: | + ./generate-command-reference.ps1 -PesterVersion '${{ env.PESTER }}' -DocsVersion '${{ env.DOCS }}' + + # Output if any files were modified + $updated = $null -ne (git status -s | Select-String '/commands/') + "updated=$updated" >> $env:GITHUB_OUTPUT + - name: Update PesterConfiguration docs + if: ${{ env.DOCS != 'v4' }} + id: config + shell: pwsh + run: | + ./generate-pesterconfiguration-docs.ps1 -PesterVersion '${{ env.PESTER }}' -Style Table -DocsVersion '${{ env.DOCS }}' + + # Output if any files were modified + $updated = $null -ne (git status -s | Select-String '/usage/Configuration.mdx') + "updated=$updated" >> $env:GITHUB_OUTPUT + - name: Create Pull Request + uses: peter-evans/create-pull-request@6d6857d36972b65feb161a90e484f2984215f83e # v6.0.5 + id: create-pr + env: + PR_BRANCH: "docs-update/${{ env.DOCS }}-v${{ env.PESTER }}" + TITLE_DOCS_VERSION: "${{ env.DOCS != 'Current' && format('{0} ', env.DOCS) || '' }}" + with: + branch: ${{ env.PR_BRANCH }} + branch-suffix: short-commit-hash + draft: false + # Should always be reviewed by author to fix typos or other errors + reviewers: ${{ github.actor }} + # Set user triggering the workflow as author (default in action) + author: ${{ github.actor }} <${{ github.actor_id }}+${{ github.actor }}@users.noreply.github.com> + # Github Action as commit (explicit default) + committer: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> + commit-message: "Update generated docs to ${{ env.PESTER }}" + add-paths: | + docs + versioned_docs + title: Update ${{ env.TITLE_DOCS_VERSION }}docs to Pester v${{ env.PESTER }} + body: | + Updates generated documentation using the specified Pester-version. + + **Docs version:** ${{ env.DOCS }} + **Pester version:** ${{ env.PESTER }} + + | Documentation updated | Result | + |-----------------------|--------| + | Command Reference | ${{ steps.commands.outputs.updated }} | + | PesterConfiguration section | ${{ steps.config.outputs.updated }} | + + *PR created using 'Update Pester Docs' workflow* + + - name: Output PR details + if: ${{ steps.create-pr.outputs.pull-request-number }} + run: | + echo "### Update Pester Docs successfully completed! :rocket:" >> $GITHUB_STEP_SUMMARY + echo "See [pull request #${{ steps.create-pr.outputs.pull-request-number }}](${{ steps.create-pr.outputs.pull-request-url }})" >> $GITHUB_STEP_SUMMARY diff --git a/.vscode/launch.json b/.vscode/launch.json index 10d5b432..79e3477a 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -5,10 +5,10 @@ "version": "0.2.0", "configurations": [ { - "command": "yarn start --poll", + "command": "yarn start --host 0.0.0.0 --poll 1000", "name": "Start Docusaurus (with polling)", "request": "launch", "type": "node-terminal" } ] -} \ No newline at end of file +} diff --git a/docs/additional-resources/projects.mdx b/docs/additional-resources/projects.mdx index 1ba1690c..e7e0618a 100644 --- a/docs/additional-resources/projects.mdx +++ b/docs/additional-resources/projects.mdx @@ -15,7 +15,7 @@ import { columns, projects } from "./projects.table"; /> :::note Compatibility -Many projects above were designed for earlier versions of Pester and might not yet be updated to support Pester v5. +Many projects above were designed for earlier versions of Pester and might not yet be updated to support Pester v5 and later. ::: $null , and @() | will give $local:input -> @(), is that distinction important when we know that we will only check against values? + +# This fails, because -Expected does not allow collections. +@() | Should-Be -Expected @() + +```powershell +# Should-BeCollection is a collection assertion: +1 | Should-BeCollection -Expected @(1) +@(1) | Should-BeCollection -Expected @(1) +@() | Should-BeCollection -Expected @() + +# This fails, because -Expected requires a collection. +$null | Should-BeCollection -Expected $null +``` + +#### Using the -Actual syntax + +The value provides to `-Actual`, is always exactly the same as provided. + +```powershell +Should-Be -Actual 1 -Expected 1 + +# This fails, Actual is collection, while expected is int. +Should-Be -Actual @(1) -Expected 1 +``` + +### Value assertions + +#### Generic value assertions + +Generic value assertions, such as `Should-Be`, are for asserting on a single value. They behave quite similar to PowerShell operators, e.g. `Should-Be` maps to `-eq`. + +The `$Expected` accepts any input that is not a collection. +The type of `$Expected` determines the type to be used for the comparison. +`$Actual` is automatically converted to that type. + +```powershell +1 | Should-Be -Expected $true +Get-Process -Name Idle | Should-Be -Expected "System.Diagnostics.Process (Idle)" +``` + +The assertions in the above examples will both pass: +- `1` converts to `bool`-value as `$true`, which is the expected value. +- `Get-Process` retrieves the `Idle` process (on Windows). This process object gets converted to `string` which is equal to the expected value. + +#### Type specific value assertions + +Type specific assertions are for asserting on a single value of a given type like `boolean`. +These assertions take the advantage of being more specialized to provide a type specific functionality, such as `Should-BeString -IgnoreWhitespace`. + +- `$Expected` accepts input that has the same type as the assertion type. E.g. `Should-BeString -Expected "my string"`. +- `$Actual` accepts input that has the same type as the assertion type. The input is **not** converted to the destination type unless the assertion specifies it, e.g. `Should-BeFalsy` will convert to `bool`. + +### Collection assertions + +TODO + +## `Should` (v4/v5) + `Should` is used to do an assertion that fails or passes the test. An example of assertion is comparing two strings in case insensitive manner: diff --git a/docs/commands/Add-ShouldOperator.mdx b/docs/commands/Add-ShouldOperator.mdx index b56e1445..83b75608 100644 --- a/docs/commands/Add-ShouldOperator.mdx +++ b/docs/commands/Add-ShouldOperator.mdx @@ -49,7 +49,7 @@ function BeAwesome($ActualValue, [switch] $Negate) { } } - return New-Object psobject -Property @{ + return [PSCustomObject]@{ Succeeded = $succeeded FailureMessage = $failureMessage } @@ -166,4 +166,4 @@ This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable ## VERSION -*This page was generated using comment-based help in [Pester 5.6.0](https://github.com/pester/pester).* +*This page was generated using comment-based help in [Pester 6.0.0-alpha1](https://github.com/pester/pester).* diff --git a/docs/commands/AfterAll.mdx b/docs/commands/AfterAll.mdx index 66f2e673..cfc138fb 100644 --- a/docs/commands/AfterAll.mdx +++ b/docs/commands/AfterAll.mdx @@ -107,4 +107,4 @@ This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable ## VERSION -*This page was generated using comment-based help in [Pester 5.6.0](https://github.com/pester/pester).* +*This page was generated using comment-based help in [Pester 6.0.0-alpha1](https://github.com/pester/pester).* diff --git a/docs/commands/AfterEach.mdx b/docs/commands/AfterEach.mdx index 49b971e8..eebcd6a9 100644 --- a/docs/commands/AfterEach.mdx +++ b/docs/commands/AfterEach.mdx @@ -104,4 +104,4 @@ This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable ## VERSION -*This page was generated using comment-based help in [Pester 5.6.0](https://github.com/pester/pester).* +*This page was generated using comment-based help in [Pester 6.0.0-alpha1](https://github.com/pester/pester).* diff --git a/docs/commands/BeforeAll.mdx b/docs/commands/BeforeAll.mdx index 2f43f3c0..bb5b7479 100644 --- a/docs/commands/BeforeAll.mdx +++ b/docs/commands/BeforeAll.mdx @@ -116,4 +116,4 @@ This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable ## VERSION -*This page was generated using comment-based help in [Pester 5.6.0](https://github.com/pester/pester).* +*This page was generated using comment-based help in [Pester 6.0.0-alpha1](https://github.com/pester/pester).* diff --git a/docs/commands/BeforeDiscovery.mdx b/docs/commands/BeforeDiscovery.mdx index 9d58752d..73d0e0fe 100644 --- a/docs/commands/BeforeDiscovery.mdx +++ b/docs/commands/BeforeDiscovery.mdx @@ -94,4 +94,4 @@ This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable ## VERSION -*This page was generated using comment-based help in [Pester 5.6.0](https://github.com/pester/pester).* +*This page was generated using comment-based help in [Pester 6.0.0-alpha1](https://github.com/pester/pester).* diff --git a/docs/commands/BeforeEach.mdx b/docs/commands/BeforeEach.mdx index 88015aaf..34ecbfaf 100644 --- a/docs/commands/BeforeEach.mdx +++ b/docs/commands/BeforeEach.mdx @@ -101,4 +101,4 @@ This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable ## VERSION -*This page was generated using comment-based help in [Pester 5.6.0](https://github.com/pester/pester).* +*This page was generated using comment-based help in [Pester 6.0.0-alpha1](https://github.com/pester/pester).* diff --git a/docs/commands/Context.mdx b/docs/commands/Context.mdx index 4b2013ba..02ef9668 100644 --- a/docs/commands/Context.mdx +++ b/docs/commands/Context.mdx @@ -183,4 +183,4 @@ This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable ## VERSION -*This page was generated using comment-based help in [Pester 5.6.0](https://github.com/pester/pester).* +*This page was generated using comment-based help in [Pester 6.0.0-alpha1](https://github.com/pester/pester).* diff --git a/docs/commands/ConvertTo-JUnitReport.mdx b/docs/commands/ConvertTo-JUnitReport.mdx index 09fb6e61..6dca52c9 100644 --- a/docs/commands/ConvertTo-JUnitReport.mdx +++ b/docs/commands/ConvertTo-JUnitReport.mdx @@ -118,4 +118,4 @@ This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable ## VERSION -*This page was generated using comment-based help in [Pester 5.6.0](https://github.com/pester/pester).* +*This page was generated using comment-based help in [Pester 6.0.0-alpha1](https://github.com/pester/pester).* diff --git a/docs/commands/ConvertTo-NUnitReport.mdx b/docs/commands/ConvertTo-NUnitReport.mdx index 6850dd87..35da193d 100644 --- a/docs/commands/ConvertTo-NUnitReport.mdx +++ b/docs/commands/ConvertTo-NUnitReport.mdx @@ -145,4 +145,4 @@ This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable ## VERSION -*This page was generated using comment-based help in [Pester 5.6.0](https://github.com/pester/pester).* +*This page was generated using comment-based help in [Pester 6.0.0-alpha1](https://github.com/pester/pester).* diff --git a/docs/commands/ConvertTo-Pester4Result.mdx b/docs/commands/ConvertTo-Pester4Result.mdx index d515ed7e..57532f1a 100644 --- a/docs/commands/ConvertTo-Pester4Result.mdx +++ b/docs/commands/ConvertTo-Pester4Result.mdx @@ -86,4 +86,4 @@ This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable ## VERSION -*This page was generated using comment-based help in [Pester 5.6.0](https://github.com/pester/pester).* +*This page was generated using comment-based help in [Pester 6.0.0-alpha1](https://github.com/pester/pester).* diff --git a/docs/commands/Describe.mdx b/docs/commands/Describe.mdx index fcf82020..fc8d18e2 100644 --- a/docs/commands/Describe.mdx +++ b/docs/commands/Describe.mdx @@ -193,4 +193,4 @@ This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable ## VERSION -*This page was generated using comment-based help in [Pester 5.6.0](https://github.com/pester/pester).* +*This page was generated using comment-based help in [Pester 6.0.0-alpha1](https://github.com/pester/pester).* diff --git a/docs/commands/Export-JUnitReport.mdx b/docs/commands/Export-JUnitReport.mdx index 74665c5c..c6401805 100644 --- a/docs/commands/Export-JUnitReport.mdx +++ b/docs/commands/Export-JUnitReport.mdx @@ -105,4 +105,4 @@ This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable ## VERSION -*This page was generated using comment-based help in [Pester 5.6.0](https://github.com/pester/pester).* +*This page was generated using comment-based help in [Pester 6.0.0-alpha1](https://github.com/pester/pester).* diff --git a/docs/commands/Export-NUnitReport.mdx b/docs/commands/Export-NUnitReport.mdx index 7f0b487c..8305a640 100644 --- a/docs/commands/Export-NUnitReport.mdx +++ b/docs/commands/Export-NUnitReport.mdx @@ -121,4 +121,4 @@ This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable ## VERSION -*This page was generated using comment-based help in [Pester 5.6.0](https://github.com/pester/pester).* +*This page was generated using comment-based help in [Pester 6.0.0-alpha1](https://github.com/pester/pester).* diff --git a/docs/commands/Get-EquivalencyOption.mdx b/docs/commands/Get-EquivalencyOption.mdx new file mode 100644 index 00000000..666579e8 --- /dev/null +++ b/docs/commands/Get-EquivalencyOption.mdx @@ -0,0 +1,123 @@ +--- +id: Get-EquivalencyOption +title: Get-EquivalencyOption +description: Help page for the PowerShell Pester "Get-EquivalencyOption" command +keywords: + - PowerShell + - Pester + - Help + - Documentation +hide_title: false +hide_table_of_contents: false +custom_edit_url: null +--- + +:::info This page was generated +Contributions are welcome in [Pester-repo](https://github.com/pester/pester). +::: + +## SYNOPSIS + +Generates an object containing options for checking equivalency. + +## SYNTAX + +```powershell +Get-EquivalencyOption [[-ExcludePath] ] [-ExcludePathsNotOnExpected] [[-Comparator] ] + [] +``` + +## DESCRIPTION + +The `Get-EquivalencyOption` function creates a custom object with options that determine how equivalency between two objects is assessed. +This can be used in scenarios where a deep comparison of objects is required, with the ability to exclude specific paths from the comparison and to choose between different comparison strategies. + +## EXAMPLES + +### EXAMPLE 1 + +```powershell +$option = Get-EquivalencyOption -ExcludePath 'Id', 'Timestamp' -Comparator 'Equality' +This example generates an equivalency option object that excludes the 'Id' and 'Timestamp' properties from the comparison and uses a simple equality comparison strategy. +``` + +### EXAMPLE 2 + +```powershell +$option = Get-EquivalencyOption -ExcludePathsNotOnExpected +This example generates an equivalency option object that excludes any paths not present on the expected object from the comparison, using the default deep comparison strategy. +``` + +## PARAMETERS + +### -ExcludePath + +An array of strings specifying the paths to exclude from the comparison. +Each path should correspond to a property name or a chain of property names separated by dots for nested properties. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: @() +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ExcludePathsNotOnExpected + +A switch parameter that, when set, excludes any paths from the comparison that are not present on the expected object. +This is useful for ignoring extra properties on the actual object that are not relevant to the comparison. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Comparator + +Specifies the comparison strategy to use. +The options are 'Equivalency' for a deep comparison that considers the structure and values of objects, and 'Equality' for a simple equality comparison. +The default is 'Equivalency'. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: Equivalency +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS + +[https://pester.dev/docs/commands/Get-EquivalencyOption](https://pester.dev/docs/commands/Get-EquivalencyOption) + +[https://pester.dev/docs/assertions](https://pester.dev/docs/assertions) + +## VERSION + +*This page was generated using comment-based help in [Pester 6.0.0-alpha1](https://github.com/pester/pester).* diff --git a/docs/commands/Get-ShouldOperator.mdx b/docs/commands/Get-ShouldOperator.mdx index 1b9b5769..4025ab19 100644 --- a/docs/commands/Get-ShouldOperator.mdx +++ b/docs/commands/Get-ShouldOperator.mdx @@ -94,4 +94,4 @@ standard PowerShell discovery patterns (like `Get-Help Should -Parameter *`). ## VERSION -*This page was generated using comment-based help in [Pester 5.6.0](https://github.com/pester/pester).* +*This page was generated using comment-based help in [Pester 6.0.0-alpha1](https://github.com/pester/pester).* diff --git a/docs/commands/InModuleScope.mdx b/docs/commands/InModuleScope.mdx index 8a1afbe6..a7c5392e 100644 --- a/docs/commands/InModuleScope.mdx +++ b/docs/commands/InModuleScope.mdx @@ -204,4 +204,4 @@ This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable ## VERSION -*This page was generated using comment-based help in [Pester 5.6.0](https://github.com/pester/pester).* +*This page was generated using comment-based help in [Pester 6.0.0-alpha1](https://github.com/pester/pester).* diff --git a/docs/commands/Invoke-Pester.mdx b/docs/commands/Invoke-Pester.mdx index 59c7806f..214a5737 100644 --- a/docs/commands/Invoke-Pester.mdx +++ b/docs/commands/Invoke-Pester.mdx @@ -37,7 +37,7 @@ Invoke-Pester [[-Path] ] [-TagFilter ] [-ExcludeTagFilter ] [-PassThru] [-EnableExit] [-CodeCoverage ] [-CodeCoverageOutputFile ] [-CodeCoverageOutputFileEncoding ] [-CodeCoverageOutputFileFormat ] [-Strict] [-OutputFile ] [-OutputFormat ] [-Quiet] - [-PesterOption ] [-Show ] [] + [-PesterOption ] [-Show ] [] ``` ### Advanced @@ -74,7 +74,7 @@ OutputFormat parameters to write the test results to an XML file, and use the EnableExit parameter to return an exit code that contains the number of failed tests. -You can also use the Strict parameter to fail all pending and skipped tests. +You can also use the Strict parameter to fail all skipped tests. This feature is ideal for build systems and other processes that require success on every test. @@ -489,7 +489,7 @@ Accept wildcard characters: False ### -Strict (Deprecated v4) -Makes Pending and Skipped tests to Failed tests. +Makes Skipped tests to Failed tests. Useful for continuous integration where you need to make sure all tests passed. @@ -599,7 +599,7 @@ Accept wildcard characters: False Replace with ConfigurationProperty Output.Verbosity Customizes the output Pester writes to the screen. Available options are None, Default, -Passed, Failed, Pending, Skipped, Inconclusive, Describe, Context, Summary, Header, All, Fails. +Passed, Failed, Skipped, Inconclusive, Describe, Context, Summary, Header, All, Fails. The options can be combined to define presets. ConfigurationProperty Output.Verbosity supports the following values: None @@ -623,10 +623,9 @@ This parameter does not affect the PassThru custom object or the XML output that is written when you use the Output parameters. ```yaml -Type: OutputTypes +Type: String Parameter Sets: Legacy Aliases: -Accepted values: None, Default, Passed, Failed, Pending, Skipped, Inconclusive, Describe, Context, Summary, Header, Fails, All Required: False Position: Named @@ -653,4 +652,4 @@ This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable ## VERSION -*This page was generated using comment-based help in [Pester 5.6.0](https://github.com/pester/pester).* +*This page was generated using comment-based help in [Pester 6.0.0-alpha1](https://github.com/pester/pester).* diff --git a/docs/commands/It.mdx b/docs/commands/It.mdx index 54712351..cb5c08c8 100644 --- a/docs/commands/It.mdx +++ b/docs/commands/It.mdx @@ -28,13 +28,6 @@ Validates the results of a test inside of a Describe block. It [-Name] [[-Test] ] [-ForEach ] [-Tag ] [] ``` -### Pending - -```powershell -It [-Name] [[-Test] ] [-ForEach ] [-Tag ] [-Pending] - [] -``` - ### Skip ```powershell @@ -202,26 +195,6 @@ Accept pipeline input: False Accept wildcard characters: False ``` -### -Pending - -Use this parameter to explicitly mark the test as work-in-progress/not implemented/pending when you -need to distinguish a test that fails because it is not finished yet from a tests -that fail as a result of changes being made in the code base. -An empty test, that is a -test that contains nothing except whitespace or comments is marked as Pending by default. - -```yaml -Type: SwitchParameter -Parameter Sets: Pending -Aliases: - -Required: False -Position: Named -Default value: False -Accept pipeline input: False -Accept wildcard characters: False -``` - ### -Skip Use this parameter to explicitly mark the test to be skipped. @@ -262,4 +235,4 @@ This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable ## VERSION -*This page was generated using comment-based help in [Pester 5.6.0](https://github.com/pester/pester).* +*This page was generated using comment-based help in [Pester 6.0.0-alpha1](https://github.com/pester/pester).* diff --git a/docs/commands/Mock.mdx b/docs/commands/Mock.mdx index 5b75de86..6988be35 100644 --- a/docs/commands/Mock.mdx +++ b/docs/commands/Mock.mdx @@ -339,4 +339,4 @@ This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable ## VERSION -*This page was generated using comment-based help in [Pester 5.6.0](https://github.com/pester/pester).* +*This page was generated using comment-based help in [Pester 6.0.0-alpha1](https://github.com/pester/pester).* diff --git a/docs/commands/New-Fixture.mdx b/docs/commands/New-Fixture.mdx index 2fde74ae..290eaefb 100644 --- a/docs/commands/New-Fixture.mdx +++ b/docs/commands/New-Fixture.mdx @@ -142,4 +142,4 @@ This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable ## VERSION -*This page was generated using comment-based help in [Pester 5.6.0](https://github.com/pester/pester).* +*This page was generated using comment-based help in [Pester 6.0.0-alpha1](https://github.com/pester/pester).* diff --git a/docs/commands/New-MockObject.mdx b/docs/commands/New-MockObject.mdx index 5cf702a9..df1cc24f 100644 --- a/docs/commands/New-MockObject.mdx +++ b/docs/commands/New-MockObject.mdx @@ -194,4 +194,4 @@ This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable ## VERSION -*This page was generated using comment-based help in [Pester 5.6.0](https://github.com/pester/pester).* +*This page was generated using comment-based help in [Pester 6.0.0-alpha1](https://github.com/pester/pester).* diff --git a/docs/commands/New-PesterConfiguration.mdx b/docs/commands/New-PesterConfiguration.mdx index 1ce368fc..81e69047 100644 --- a/docs/commands/New-PesterConfiguration.mdx +++ b/docs/commands/New-PesterConfiguration.mdx @@ -121,10 +121,11 @@ This uses the TestFilter from general configuration. CoveragePercentTarget: Target percent of code coverage that you want to achieve, default 75%. Default value: 75 - UseBreakpoints: EXPERIMENTAL: When false, use Profiler based tracer to do CodeCoverage instead of using breakpoints. - Default value: $true + UseBreakpoints: When false, use Profiler based tracer to do CodeCoverage instead of using breakpoints. + Default value: $false SingleHitBreakpoints: Remove breakpoint when it is hit. +This increases performance of breakpoint based CodeCoverage. Default value: $true TestResult: @@ -272,4 +273,4 @@ This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable ## VERSION -*This page was generated using comment-based help in [Pester 5.6.0](https://github.com/pester/pester).* +*This page was generated using comment-based help in [Pester 6.0.0-alpha1](https://github.com/pester/pester).* diff --git a/docs/commands/New-PesterContainer.mdx b/docs/commands/New-PesterContainer.mdx index 127f5249..175a343c 100644 --- a/docs/commands/New-PesterContainer.mdx +++ b/docs/commands/New-PesterContainer.mdx @@ -152,4 +152,4 @@ This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable ## VERSION -*This page was generated using comment-based help in [Pester 5.6.0](https://github.com/pester/pester).* +*This page was generated using comment-based help in [Pester 6.0.0-alpha1](https://github.com/pester/pester).* diff --git a/docs/commands/Set-ItResult.mdx b/docs/commands/Set-ItResult.mdx index 3728c807..86aae3c9 100644 --- a/docs/commands/Set-ItResult.mdx +++ b/docs/commands/Set-ItResult.mdx @@ -28,12 +28,6 @@ Set-ItResult is used inside the It block to explicitly set the test result Set-ItResult [-Inconclusive] [-Because ] [] ``` -### Pending - -```powershell -Set-ItResult [-Pending] [-Because ] [] -``` - ### Skipped ```powershell @@ -45,11 +39,7 @@ Set-ItResult [-Skipped] [-Because ] [] Sometimes a test shouldn't be executed, sometimes the condition cannot be evaluated. By default such tests would typically fail and produce a big red message. Using Set-ItResult it is possible to set the result from the inside of the It script -block to either inconclusive, pending or skipped. - -As of Pester 5, there is no "Inconclusive" or "Pending" test state, so all tests will now go to state skipped, -however the test result notes will include information about being inconclusive or testing to keep this command -backwards compatible +block to either inconclusive, or skipped. ## EXAMPLES @@ -81,7 +71,7 @@ Tests Passed: 0, Failed: 0, Skipped: 1, Inconclusive: 1, NotRun: 0 ### -Inconclusive Sets the test result to inconclusive. -Cannot be used at the same time as -Pending or -Skipped +Cannot be used at the same time as -Skipped ```yaml Type: SwitchParameter @@ -95,27 +85,10 @@ Accept pipeline input: False Accept wildcard characters: False ``` -### -Pending - -**DEPRECATED** Sets the test result to pending. -Cannot be used at the same time as -Inconclusive or -Skipped - -```yaml -Type: SwitchParameter -Parameter Sets: Pending -Aliases: - -Required: False -Position: Named -Default value: False -Accept pipeline input: False -Accept wildcard characters: False -``` - ### -Skipped Sets the test result to skipped. -Cannot be used at the same time as -Inconclusive or -Pending +Cannot be used at the same time as -Inconclusive. ```yaml Type: SwitchParameter @@ -163,4 +136,4 @@ This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable ## VERSION -*This page was generated using comment-based help in [Pester 5.6.0](https://github.com/pester/pester).* +*This page was generated using comment-based help in [Pester 6.0.0-alpha1](https://github.com/pester/pester).* diff --git a/docs/commands/Should-All.mdx b/docs/commands/Should-All.mdx new file mode 100644 index 00000000..b53fa8b8 --- /dev/null +++ b/docs/commands/Should-All.mdx @@ -0,0 +1,123 @@ +--- +id: Should-All +title: Should-All +description: Help page for the PowerShell Pester "Should-All" command +keywords: + - PowerShell + - Pester + - Help + - Documentation +hide_title: false +hide_table_of_contents: false +custom_edit_url: null +--- + +:::info This page was generated +Contributions are welcome in [Pester-repo](https://github.com/pester/pester). +::: + +## SYNOPSIS + +Compares all items in a collection to a filter script. +If the filter returns true, or does not throw for all the items in the collection, the assertion passes. + +## SYNTAX + +```powershell +Should-All [[-Actual] ] [-FilterScript] [-Because ] [] +``` + +## DESCRIPTION + +\{\{ Fill in the Description \}\} + +## EXAMPLES + +### EXAMPLE 1 + +```powershell +1, 2, 3 | Should-All { $_ -gt 0 } +1, 2, 3 | Should-All { $_ | Should-BeGreaterThan 0 } +``` + +This assertion will pass, because all items pass the filter. + +### EXAMPLE 2 + +```powershell +1, 2, 3 | Should-All { $_ -gt 1 } +1, 2, 3 | Should-All { $_ | Should-BeGreaterThan 1 } +``` + +The assertions will fail because not all items in the array are greater than 1. + +## PARAMETERS + +### -Actual + +A collection of items to filter. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -FilterScript + +A script block that filters the input collection. +The script block can use Should-* assertions or throw exceptions to indicate failure. + +```yaml +Type: ScriptBlock +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Because + +The reason why the input should be the expected value. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS + +[https://pester.dev/docs/commands/Should-All](https://pester.dev/docs/commands/Should-All) + +[https://pester.dev/docs/assertions](https://pester.dev/docs/assertions) + +## VERSION + +*This page was generated using comment-based help in [Pester 6.0.0-alpha1](https://github.com/pester/pester).* diff --git a/docs/commands/Should-Any.mdx b/docs/commands/Should-Any.mdx new file mode 100644 index 00000000..2b5137f3 --- /dev/null +++ b/docs/commands/Should-Any.mdx @@ -0,0 +1,124 @@ +--- +id: Should-Any +title: Should-Any +description: Help page for the PowerShell Pester "Should-Any" command +keywords: + - PowerShell + - Pester + - Help + - Documentation +hide_title: false +hide_table_of_contents: false +custom_edit_url: null +--- + +:::info This page was generated +Contributions are welcome in [Pester-repo](https://github.com/pester/pester). +::: + +## SYNOPSIS + +Compares all items in a collection to a filter script. +If the filter returns true, or does not throw for any of the items in the collection, the assertion passes. + +## SYNTAX + +```powershell +Should-Any [[-Actual] ] [-FilterScript] [-Because ] [] +``` + +## DESCRIPTION + +\{\{ Fill in the Description \}\} + +## EXAMPLES + +### EXAMPLE 1 + +```powershell +1, 2, 3 | Should-Any { $_ -gt 2 } +1, 2, 3 | Should-Any { $_ | Should-BeGreaterThan 2 } +``` + +This assertion will pass, because at least one item in the collection passed the filter. +3 is greater than 2. + +### EXAMPLE 2 + +```powershell +1, 2, 3 | Should-Any { $_ -gt 4 } +1, 2, 3 | Should-Any { $_ | Should-BeGreaterThan 4 } +``` + +The assertions will fail because none of theitems in the array are greater than 4. + +## PARAMETERS + +### -Actual + +A collection of items to filter. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -FilterScript + +A script block that filters the input collection. +The script block can use Should-* assertions or throw exceptions to indicate failure. + +```yaml +Type: ScriptBlock +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Because + +The reason why the input should be the expected value. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS + +[https://pester.dev/docs/commands/Should-Any](https://pester.dev/docs/commands/Should-Any) + +[https://pester.dev/docs/assertions](https://pester.dev/docs/assertions) + +## VERSION + +*This page was generated using comment-based help in [Pester 6.0.0-alpha1](https://github.com/pester/pester).* diff --git a/docs/commands/Should-Be.mdx b/docs/commands/Should-Be.mdx new file mode 100644 index 00000000..f53cf39d --- /dev/null +++ b/docs/commands/Should-Be.mdx @@ -0,0 +1,112 @@ +--- +id: Should-Be +title: Should-Be +description: Help page for the PowerShell Pester "Should-Be" command +keywords: + - PowerShell + - Pester + - Help + - Documentation +hide_title: false +hide_table_of_contents: false +custom_edit_url: null +--- + +:::info This page was generated +Contributions are welcome in [Pester-repo](https://github.com/pester/pester). +::: + +## SYNOPSIS + +Compares the expected value to actual value, to see if they are equal. + +## SYNTAX + +```powershell +Should-Be [[-Actual] ] [-Expected] [-Because ] [] +``` + +## DESCRIPTION + +\{\{ Fill in the Description \}\} + +## EXAMPLES + +### EXAMPLE 1 + +```powershell +1 | Should-Be 1 +"hello" | Should-Be "hello" +``` + +These assertions will pass, because the expected value is equal to the actual value. + +## PARAMETERS + +### -Actual + +The actual value. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Expected + +The expected value. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Because + +The reason why the input should be the expected value. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS + +[https://pester.dev/docs/commands/Should-Be](https://pester.dev/docs/commands/Should-Be) + +[https://pester.dev/docs/assertions](https://pester.dev/docs/assertions) + +## VERSION + +*This page was generated using comment-based help in [Pester 6.0.0-alpha1](https://github.com/pester/pester).* diff --git a/docs/commands/Should-BeAfter.mdx b/docs/commands/Should-BeAfter.mdx new file mode 100644 index 00000000..9db3fabb --- /dev/null +++ b/docs/commands/Should-BeAfter.mdx @@ -0,0 +1,201 @@ +--- +id: Should-BeAfter +title: Should-BeAfter +description: Help page for the PowerShell Pester "Should-BeAfter" command +keywords: + - PowerShell + - Pester + - Help + - Documentation +hide_title: false +hide_table_of_contents: false +custom_edit_url: null +--- + +:::info This page was generated +Contributions are welcome in [Pester-repo](https://github.com/pester/pester). +::: + +## SYNOPSIS + +Asserts that the provided [datetime] is after the expected [datetime]. + +## SYNTAX + +### Now (Default) + +```powershell +Should-BeAfter [[-Actual] ] [-Now] [] +``` + +### Fluent + +```powershell +Should-BeAfter [[-Actual] ] [[-Time] ] [-Ago] [-FromNow] [] +``` + +### Expected + +```powershell +Should-BeAfter [[-Actual] ] [[-Expected] ] [] +``` + +## DESCRIPTION + +\{\{ Fill in the Description \}\} + +## EXAMPLES + +### EXAMPLE 1 + +```powershell +(Get-Date).AddDays(1) | Should-BeAfter (Get-Date) +``` + +This assertion will pass, because the actual value is after the expected value. + +### EXAMPLE 2 + +```powershell +(Get-Date).AddDays(-1) | Should-BeAfter (Get-Date) +``` + +This assertion will fail, because the actual value is not after the expected value. + +### EXAMPLE 3 + +```powershell +(Get-Date).AddDays(1) | Should-BeAfter 10minutes -FromNow +``` + +This assertion will pass, because the actual value is after the expected value. + +### EXAMPLE 4 + +```powershell +(Get-Date).AddDays(-1) | Should-BeAfter -Time 3days -Ago +``` + +This assertion will pass, because the actual value is after the expected value. + +## PARAMETERS + +### -Actual + +The actual [datetime] value. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 3 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Now + +Indicates that the current time should be used as the expected time. + +```yaml +Type: SwitchParameter +Parameter Sets: Now +Aliases: + +Required: False +Position: 1 +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Time + +The time to add or subtract from the current time. +This parameter uses fluent time syntax e.g. +1minute. + +```yaml +Type: Object +Parameter Sets: Fluent +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Ago + +Indicates that the -Time should be subtracted from the current time. + +```yaml +Type: SwitchParameter +Parameter Sets: Fluent +Aliases: + +Required: False +Position: 2 +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -FromNow + +Indicates that the -Time should be added to the current time. + +```yaml +Type: SwitchParameter +Parameter Sets: Fluent +Aliases: + +Required: False +Position: 2 +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Expected + +The expected [datetime] value. + +```yaml +Type: DateTime +Parameter Sets: Expected +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +The `Should-BeAfter` assertion is the opposite of the `Should-BeBefore` assertion. + +## RELATED LINKS + +[https://pester.dev/docs/commands/Should-BeAfter](https://pester.dev/docs/commands/Should-BeAfter) + +[https://pester.dev/docs/assertions](https://pester.dev/docs/assertions) + +## VERSION + +*This page was generated using comment-based help in [Pester 6.0.0-alpha1](https://github.com/pester/pester).* diff --git a/docs/commands/Should-BeBefore.mdx b/docs/commands/Should-BeBefore.mdx new file mode 100644 index 00000000..f158baa2 --- /dev/null +++ b/docs/commands/Should-BeBefore.mdx @@ -0,0 +1,202 @@ +--- +id: Should-BeBefore +title: Should-BeBefore +description: Help page for the PowerShell Pester "Should-BeBefore" command +keywords: + - PowerShell + - Pester + - Help + - Documentation +hide_title: false +hide_table_of_contents: false +custom_edit_url: null +--- + +:::info This page was generated +Contributions are welcome in [Pester-repo](https://github.com/pester/pester). +::: + +## SYNOPSIS + +Asserts that the provided [datetime] is before the expected [datetime]. + +## SYNTAX + +### Now (Default) + +```powershell +Should-BeBefore [[-Actual] ] [-Now] [] +``` + +### Fluent + +```powershell +Should-BeBefore [[-Actual] ] [[-Time] ] [-Ago] [-FromNow] [] +``` + +### Expected + +```powershell +Should-BeBefore [[-Actual] ] [[-Expected] ] [] +``` + +## DESCRIPTION + +\{\{ Fill in the Description \}\} + +## EXAMPLES + +### EXAMPLE 1 + +```powershell +(Get-Date).AddDays(-1) | Should-BeBefore (Get-Date) +``` + +This assertion will pass, because the actual value is before the expected value. + +### EXAMPLE 2 + +``` +```powershell +(Get-Date).AddDays(1) | Should-BeBefore (Get-Date) +```powershell +This assertion will fail, because the actual value is not before the expected value. +``` + +### EXAMPLE 3 + +```powershell +(Get-Date).AddMinutes(1) | Should-BeBefore 10minutes -FromNow +``` + +This assertion will pass, because the actual value is before the expected value. + +### EXAMPLE 4 + +```powershell +(Get-Date).AddDays(-2) | Should-BeBefore -Time 3days -Ago +``` + +This assertion will pass, because the actual value is before the expected value. + +## PARAMETERS + +### -Actual + +The actual [datetime] value. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 3 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Now + +Indicates that the current time should be used as the expected time. + +```yaml +Type: SwitchParameter +Parameter Sets: Now +Aliases: + +Required: False +Position: 1 +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Time + +The time to add or subtract from the current time. +This parameter uses fluent time syntax e.g. +1minute. + +```yaml +Type: Object +Parameter Sets: Fluent +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Ago + +Indicates that the -Time should be subtracted from the current time. + +```yaml +Type: SwitchParameter +Parameter Sets: Fluent +Aliases: + +Required: False +Position: 2 +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -FromNow + +Indicates that the -Time should be added to the current time. + +```yaml +Type: SwitchParameter +Parameter Sets: Fluent +Aliases: + +Required: False +Position: 2 +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Expected + +The expected [datetime] value. + +```yaml +Type: DateTime +Parameter Sets: Expected +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +The `Should-BeBefore` assertion is the opposite of the `Should-BeAfter` assertion. + +## RELATED LINKS + +[https://pester.dev/docs/commands/Should-BeBefore](https://pester.dev/docs/commands/Should-BeBefore) + +[https://pester.dev/docs/assertions](https://pester.dev/docs/assertions) + +## VERSION + +*This page was generated using comment-based help in [Pester 6.0.0-alpha1](https://github.com/pester/pester).* diff --git a/docs/commands/Should-BeCollection.mdx b/docs/commands/Should-BeCollection.mdx new file mode 100644 index 00000000..8b448dcb --- /dev/null +++ b/docs/commands/Should-BeCollection.mdx @@ -0,0 +1,125 @@ +--- +id: Should-BeCollection +title: Should-BeCollection +description: Help page for the PowerShell Pester "Should-BeCollection" command +keywords: + - PowerShell + - Pester + - Help + - Documentation +hide_title: false +hide_table_of_contents: false +custom_edit_url: null +--- + +:::info This page was generated +Contributions are welcome in [Pester-repo](https://github.com/pester/pester). +::: + +## SYNOPSIS + +Compares collections for equality, by comparing their sizes and each item in them. +It does not compare the types of the input collections. + +## SYNTAX + +```powershell +Should-BeCollection [[-Actual] ] [-Expected] [-Because ] [] +``` + +## DESCRIPTION + +\{\{ Fill in the Description \}\} + +## EXAMPLES + +### EXAMPLE 1 + +```powershell +1, 2, 3 | Should-BeCollection @(1, 2, 3) +@(1) | Should-BeCollection @(1) +1 | Should-BeCollection 1 +``` + +This assertion will pass, because the collections have the same size and the items are equal. + +### EXAMPLE 2 + +```powershell +1, 2, 3, 4 | Should-BeCollection @(1, 2, 3) +1, 2, 3, 4 | Should-BeCollection @(5, 6, 7, 8) +@(1) | Should-BeCollection @(2) +1 | Should-BeCollection @(2) +``` + +The assertions will fail because the collections are not equal. + +## PARAMETERS + +### -Actual + +A collection of items. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Expected + +A collection of items. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Because + +The reason why the input should be the expected value. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS + +[https://pester.dev/docs/commands/Should-BeCollection](https://pester.dev/docs/commands/Should-BeCollection) + +[https://pester.dev/docs/assertions](https://pester.dev/docs/assertions) + +## VERSION + +*This page was generated using comment-based help in [Pester 6.0.0-alpha1](https://github.com/pester/pester).* diff --git a/docs/commands/Should-BeEmptyString.mdx b/docs/commands/Should-BeEmptyString.mdx new file mode 100644 index 00000000..661383a8 --- /dev/null +++ b/docs/commands/Should-BeEmptyString.mdx @@ -0,0 +1,116 @@ +--- +id: Should-BeEmptyString +title: Should-BeEmptyString +description: Help page for the PowerShell Pester "Should-BeEmptyString" command +keywords: + - PowerShell + - Pester + - Help + - Documentation +hide_title: false +hide_table_of_contents: false +custom_edit_url: null +--- + +:::info This page was generated +Contributions are welcome in [Pester-repo](https://github.com/pester/pester). +::: + +## SYNOPSIS + +Ensures that input is an empty string. + +## SYNTAX + +```powershell +Should-BeEmptyString [[-Actual] ] [-Because ] [] +``` + +## DESCRIPTION + +\{\{ Fill in the Description \}\} + +## EXAMPLES + +### EXAMPLE 1 + +```powershell +$actual = "" +$actual | Should-BeEmptyString +``` + +This test will pass. + +### EXAMPLE 2 + +```powershell +$actual = "hello" +$actual | Should-BeEmptyString +``` + +This test will fail, the input is not an empty string. + +### EXAMPLE 3 + +```powershell +$null | Should-BeEmptyString +@() | Should-BeEmptyString +$() | Should-BeEmptyString +$false | Should-BeEmptyString +``` + +All the tests above will fail, the input is not a string. + +## PARAMETERS + +### -Actual + +The actual value that will be compared to an empty string. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Because + +The reason why the input should be an empty string. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS + +[https://pester.dev/docs/commands/Should-BeEmptyString](https://pester.dev/docs/commands/Should-BeEmptyString) + +[https://pester.dev/docs/assertions](https://pester.dev/docs/assertions) + +## VERSION + +*This page was generated using comment-based help in [Pester 6.0.0-alpha1](https://github.com/pester/pester).* diff --git a/docs/commands/Should-BeEquivalent.mdx b/docs/commands/Should-BeEquivalent.mdx new file mode 100644 index 00000000..50cc8754 --- /dev/null +++ b/docs/commands/Should-BeEquivalent.mdx @@ -0,0 +1,154 @@ +--- +id: Should-BeEquivalent +title: Should-BeEquivalent +description: Help page for the PowerShell Pester "Should-BeEquivalent" command +keywords: + - PowerShell + - Pester + - Help + - Documentation +hide_title: false +hide_table_of_contents: false +custom_edit_url: null +--- + +:::info This page was generated +Contributions are welcome in [Pester-repo](https://github.com/pester/pester). +::: + +## SYNOPSIS + +Compares two objects for equivalency, by recursively comparing their properties for equivalency. + +## SYNTAX + +```powershell +Should-BeEquivalent [[-Actual] ] [-Expected] [-Because ] [-Options ] + [] +``` + +## DESCRIPTION + +\{\{ Fill in the Description \}\} + +## EXAMPLES + +### EXAMPLE 1 + +```powershell + $expected = [PSCustomObject] @{ + Name = "Thomas" + } + + $actual = [PSCustomObject] @{ + Name = "Jakub" + Age = 30 + } + + $actual | Should-BeEquivalent $expected +``` + +This will throw an error because the actual object has an additional property Age and the Name values are not equivalent. + +### EXAMPLE 2 + +```powershell + $expected = [PSCustomObject] @{ + Name = "Thomas" + } + + $actual = [PSCustomObject] @{ + Name = "Thomas" + } + + $actual | Should-BeEquivalent $expected +``` + +This will pass because the actual object has the same properties as the expected object and the Name values are equivalent. + +## PARAMETERS + +### -Actual + +The actual object to compare. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Expected + +The expected object to compare. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Because + +The reason why the input should be the expected value. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Options + +Options for the comparison. +Get-EquivalencyOption function is called to get the default options. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: (Get-EquivalencyOption) +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS + +[https://pester.dev/docs/commands/Should-BeEquivalent](https://pester.dev/docs/commands/Should-BeEquivalent) + +[https://pester.dev/docs/assertions](https://pester.dev/docs/assertions) + +## VERSION + +*This page was generated using comment-based help in [Pester 6.0.0-alpha1](https://github.com/pester/pester).* diff --git a/docs/commands/Should-BeFalse.mdx b/docs/commands/Should-BeFalse.mdx new file mode 100644 index 00000000..f0e70646 --- /dev/null +++ b/docs/commands/Should-BeFalse.mdx @@ -0,0 +1,111 @@ +--- +id: Should-BeFalse +title: Should-BeFalse +description: Help page for the PowerShell Pester "Should-BeFalse" command +keywords: + - PowerShell + - Pester + - Help + - Documentation +hide_title: false +hide_table_of_contents: false +custom_edit_url: null +--- + +:::info This page was generated +Contributions are welcome in [Pester-repo](https://github.com/pester/pester). +::: + +## SYNOPSIS + +Compares the actual value to a boolean $false. +It does not convert input values to boolean, and will fail for any value that is not $false. + +## SYNTAX + +```powershell +Should-BeFalse [[-Actual] ] [[-Because] ] [] +``` + +## DESCRIPTION + +\{\{ Fill in the Description \}\} + +## EXAMPLES + +### EXAMPLE 1 + +```powershell +$false | Should-BeFalse +``` + +This assertion will pass. + +### EXAMPLE 2 + +```powershell +$true | Should-BeFalse +Get-Process | Should-BeFalse +$null | Should-BeFalse +$() | Should-BeFalse +@() | Should-BeFalse +0 | Should-BeFalse +``` + +All of these assertions will fail, because the actual value is not $false. + +## PARAMETERS + +### -Actual + +The actual value to compare to $false. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Because + +The reason why the input should be the expected value. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +The `Should-BeFalse` assertion is the opposite of the `Should-BeTrue` assertion. + +## RELATED LINKS + +[https://pester.dev/docs/commands/Should-BeFalse](https://pester.dev/docs/commands/Should-BeFalse) + +[https://pester.dev/docs/assertions](https://pester.dev/docs/assertions) + +## VERSION + +*This page was generated using comment-based help in [Pester 6.0.0-alpha1](https://github.com/pester/pester).* diff --git a/docs/commands/Should-BeFalsy.mdx b/docs/commands/Should-BeFalsy.mdx new file mode 100644 index 00000000..145de8e2 --- /dev/null +++ b/docs/commands/Should-BeFalsy.mdx @@ -0,0 +1,111 @@ +--- +id: Should-BeFalsy +title: Should-BeFalsy +description: Help page for the PowerShell Pester "Should-BeFalsy" command +keywords: + - PowerShell + - Pester + - Help + - Documentation +hide_title: false +hide_table_of_contents: false +custom_edit_url: null +--- + +:::info This page was generated +Contributions are welcome in [Pester-repo](https://github.com/pester/pester). +::: + +## SYNOPSIS + +Compares the actual value to a boolean $false or a falsy value: 0, "", $null or @(). +It converts the input value to a boolean. + +## SYNTAX + +```powershell +Should-BeFalsy [[-Actual] ] [[-Because] ] [] +``` + +## DESCRIPTION + +\{\{ Fill in the Description \}\} + +## EXAMPLES + +### EXAMPLE 1 + +```powershell +$false | Should-BeFalsy +$null | Should-BeFalsy +$() | Should-BeFalsy +@() | Should-BeFalsy +0 | Should-BeFalsy +``` + +These assertion will pass. + +### EXAMPLE 2 + +```powershell +$true | Should-BeFalsy +Get-Process | Should-BeFalsy +``` + +These assertions will fail, because the actual value is not $false or falsy. + +## PARAMETERS + +### -Actual + +The actual value to compare to $false. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Because + +The reason why the input should be the expected value. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +The `Should-BeFalsy` assertion is the opposite of the `Should-BeTruthy` assertion. + +## RELATED LINKS + +[https://pester.dev/docs/commands/Should-BeFalsy](https://pester.dev/docs/commands/Should-BeFalsy) + +[https://pester.dev/docs/assertions](https://pester.dev/docs/assertions) + +## VERSION + +*This page was generated using comment-based help in [Pester 6.0.0-alpha1](https://github.com/pester/pester).* diff --git a/docs/commands/Should-BeFasterThan.mdx b/docs/commands/Should-BeFasterThan.mdx new file mode 100644 index 00000000..8280d6b9 --- /dev/null +++ b/docs/commands/Should-BeFasterThan.mdx @@ -0,0 +1,105 @@ +--- +id: Should-BeFasterThan +title: Should-BeFasterThan +description: Help page for the PowerShell Pester "Should-BeFasterThan" command +keywords: + - PowerShell + - Pester + - Help + - Documentation +hide_title: false +hide_table_of_contents: false +custom_edit_url: null +--- + +:::info This page was generated +Contributions are welcome in [Pester-repo](https://github.com/pester/pester). +::: + +## SYNOPSIS + +Asserts that the provided [timespan] or [scriptblock] is faster than the expected [timespan]. + +## SYNTAX + +```powershell +Should-BeFasterThan [[-Actual] ] [[-Expected] ] [] +``` + +## DESCRIPTION + +\{\{ Fill in the Description \}\} + +## EXAMPLES + +### EXAMPLE 1 + +```powershell +Measure-Command { Start-Sleep -Milliseconds 100 } | Should-BeFasterThan 1s +``` + +This assertion will pass, because the actual value is faster than the expected value. + +### EXAMPLE 2 + +```powershell +{ Start-Sleep -Milliseconds 100 } | Should-BeFasterThan 50ms +``` + +This assertion will fail, because the actual value is not faster than the expected value. + +## PARAMETERS + +### -Actual + +The actual [timespan] or [scriptblock] value. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Expected + +The expected [timespan] or fluent time value. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +The `Should-BeFasterThan` assertion is the opposite of the `Should-BeSlowerThan` assertion. + +## RELATED LINKS + +[https://pester.dev/docs/commands/Should-BeFasterThan](https://pester.dev/docs/commands/Should-BeFasterThan) + +[https://pester.dev/docs/assertions](https://pester.dev/docs/assertions) + +## VERSION + +*This page was generated using comment-based help in [Pester 6.0.0-alpha1](https://github.com/pester/pester).* diff --git a/docs/commands/Should-BeGreaterThan.mdx b/docs/commands/Should-BeGreaterThan.mdx new file mode 100644 index 00000000..9a59f846 --- /dev/null +++ b/docs/commands/Should-BeGreaterThan.mdx @@ -0,0 +1,112 @@ +--- +id: Should-BeGreaterThan +title: Should-BeGreaterThan +description: Help page for the PowerShell Pester "Should-BeGreaterThan" command +keywords: + - PowerShell + - Pester + - Help + - Documentation +hide_title: false +hide_table_of_contents: false +custom_edit_url: null +--- + +:::info This page was generated +Contributions are welcome in [Pester-repo](https://github.com/pester/pester). +::: + +## SYNOPSIS + +Compares the expected value to actual value, to see if the actual value is greater than the expected value. + +## SYNTAX + +```powershell +Should-BeGreaterThan [[-Actual] ] [-Expected] [-Because ] [] +``` + +## DESCRIPTION + +\{\{ Fill in the Description \}\} + +## EXAMPLES + +### EXAMPLE 1 + +```powershell +2 | Should-BeGreaterThan 1 +2 | Should-BeGreaterThan 2 +``` + +These assertions will pass, because the actual value is greater than the expected value. + +## PARAMETERS + +### -Actual + +The actual value. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Expected + +The expected value. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Because + +The reason why the input should be the expected value. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS + +[https://pester.dev/docs/commands/Should-BeGreaterThan](https://pester.dev/docs/commands/Should-BeGreaterThan) + +[https://pester.dev/docs/assertions](https://pester.dev/docs/assertions) + +## VERSION + +*This page was generated using comment-based help in [Pester 6.0.0-alpha1](https://github.com/pester/pester).* diff --git a/docs/commands/Should-BeGreaterThanOrEqual.mdx b/docs/commands/Should-BeGreaterThanOrEqual.mdx new file mode 100644 index 00000000..131b1f5e --- /dev/null +++ b/docs/commands/Should-BeGreaterThanOrEqual.mdx @@ -0,0 +1,112 @@ +--- +id: Should-BeGreaterThanOrEqual +title: Should-BeGreaterThanOrEqual +description: Help page for the PowerShell Pester "Should-BeGreaterThanOrEqual" command +keywords: + - PowerShell + - Pester + - Help + - Documentation +hide_title: false +hide_table_of_contents: false +custom_edit_url: null +--- + +:::info This page was generated +Contributions are welcome in [Pester-repo](https://github.com/pester/pester). +::: + +## SYNOPSIS + +Compares the expected value to actual value, to see if the actual value is greater than or equal to the expected value. + +## SYNTAX + +```powershell +Should-BeGreaterThanOrEqual [[-Actual] ] [-Expected] [-Because ] [] +``` + +## DESCRIPTION + +\{\{ Fill in the Description \}\} + +## EXAMPLES + +### EXAMPLE 1 + +```powershell +2 | Should-BeGreaterThanOrEqual 1 +2 | Should-BeGreaterThanOrEqual 2 +``` + +These assertions will pass, because the actual value is greater than or equal to the expected value. + +## PARAMETERS + +### -Actual + +The actual value. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Expected + +The expected value. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Because + +The reason why the input should be the expected value. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS + +[https://pester.dev/docs/commands/Should-BeGreaterThanOrEqual](https://pester.dev/docs/commands/Should-BeGreaterThanOrEqual) + +[https://pester.dev/docs/assertions](https://pester.dev/docs/assertions) + +## VERSION + +*This page was generated using comment-based help in [Pester 6.0.0-alpha1](https://github.com/pester/pester).* diff --git a/docs/commands/Should-BeLessThan.mdx b/docs/commands/Should-BeLessThan.mdx new file mode 100644 index 00000000..fbecbf46 --- /dev/null +++ b/docs/commands/Should-BeLessThan.mdx @@ -0,0 +1,112 @@ +--- +id: Should-BeLessThan +title: Should-BeLessThan +description: Help page for the PowerShell Pester "Should-BeLessThan" command +keywords: + - PowerShell + - Pester + - Help + - Documentation +hide_title: false +hide_table_of_contents: false +custom_edit_url: null +--- + +:::info This page was generated +Contributions are welcome in [Pester-repo](https://github.com/pester/pester). +::: + +## SYNOPSIS + +Compares the expected value to actual value, to see if the actual value is less than the expected value. + +## SYNTAX + +```powershell +Should-BeLessThan [[-Actual] ] [-Expected] [-Because ] [] +``` + +## DESCRIPTION + +\{\{ Fill in the Description \}\} + +## EXAMPLES + +### EXAMPLE 1 + +```powershell +1 | Should-BeLessThan 2 +0 | Should-BeLessThan 1 +``` + +These assertions will pass, because the actual value is less than the expected value. + +## PARAMETERS + +### -Actual + +The actual value. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Expected + +The expected value. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Because + +The reason why the input should be the expected value. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS + +[https://pester.dev/docs/commands/Should-BeLessThan](https://pester.dev/docs/commands/Should-BeLessThan) + +[https://pester.dev/docs/assertions](https://pester.dev/docs/assertions) + +## VERSION + +*This page was generated using comment-based help in [Pester 6.0.0-alpha1](https://github.com/pester/pester).* diff --git a/docs/commands/Should-BeLessThanOrEqual.mdx b/docs/commands/Should-BeLessThanOrEqual.mdx new file mode 100644 index 00000000..e317a58b --- /dev/null +++ b/docs/commands/Should-BeLessThanOrEqual.mdx @@ -0,0 +1,122 @@ +--- +id: Should-BeLessThanOrEqual +title: Should-BeLessThanOrEqual +description: Help page for the PowerShell Pester "Should-BeLessThanOrEqual" command +keywords: + - PowerShell + - Pester + - Help + - Documentation +hide_title: false +hide_table_of_contents: false +custom_edit_url: null +--- + +:::info This page was generated +Contributions are welcome in [Pester-repo](https://github.com/pester/pester). +::: + +## SYNOPSIS + +Compares the expected value to actual value, to see if the actual value is less than or equal to the expected value. + +## SYNTAX + +```powershell +Should-BeLessThanOrEqual [[-Actual] ] [-Expected] [-Because ] [] +``` + +## DESCRIPTION + +\{\{ Fill in the Description \}\} + +## EXAMPLES + +### EXAMPLE 1 + +```powershell +1 | Should-BeLessThanOrEqual 2 +1 | Should-BeLessThanOrEqual 1 +``` + +These assertions will pass, because the actual value is less than or equal to the expected value. + +### EXAMPLE 2 + +```powershell +2 | Should-BeLessThanOrEqual 1 +``` + +This assertion will fail, because the actual value is not less than or equal to the expected value. + +## PARAMETERS + +### -Actual + +The actual value. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Expected + +The expected value. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Because + +The reason why the input should be the expected value. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +The `Should-BeLessThanOrEqual` assertion is the opposite of the `Should-BeGreaterThan` assertion. + +## RELATED LINKS + +[https://pester.dev/docs/commands/Should-BeLessThanOrEqual](https://pester.dev/docs/commands/Should-BeLessThanOrEqual) + +[https://pester.dev/docs/assertions](https://pester.dev/docs/assertions) + +## VERSION + +*This page was generated using comment-based help in [Pester 6.0.0-alpha1](https://github.com/pester/pester).* diff --git a/docs/commands/Should-BeLikeString.mdx b/docs/commands/Should-BeLikeString.mdx new file mode 100644 index 00000000..c09a604b --- /dev/null +++ b/docs/commands/Should-BeLikeString.mdx @@ -0,0 +1,139 @@ +--- +id: Should-BeLikeString +title: Should-BeLikeString +description: Help page for the PowerShell Pester "Should-BeLikeString" command +keywords: + - PowerShell + - Pester + - Help + - Documentation +hide_title: false +hide_table_of_contents: false +custom_edit_url: null +--- + +:::info This page was generated +Contributions are welcome in [Pester-repo](https://github.com/pester/pester). +::: + +## SYNOPSIS + +Asserts that the actual value is like the expected value. + +## SYNTAX + +```powershell +Should-BeLikeString [[-Actual] ] [-Expected] [-CaseSensitive] [-Because ] + [] +``` + +## DESCRIPTION + +The `Should-BeLikeString` assertion compares the actual value to the expected value using the `-like` operator. +The `-like` operator is case-insensitive by default, but you can make it case-sensitive by using the `-CaseSensitive` switch. + +## EXAMPLES + +### EXAMPLE 1 + +```powershell +"hello" | Should-BeLikeString "h*" +``` + +This assertion will pass, because the actual value is like the expected value. + +### EXAMPLE 2 + +```powershell +"hello" | Should-BeLikeString "H*" -CaseSensitive +``` + +This assertion will fail, because the actual value is not like the expected value. + +## PARAMETERS + +### -Actual + +The actual value. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Expected + +The expected value. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -CaseSensitive + +Indicates that the comparison should be case-sensitive. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Because + +The reason why the actual value should be like the expected value. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +The `Should-BeLikeString` assertion is the opposite of the `Should-NotBeLikeString` assertion. + +## RELATED LINKS + +[https://pester.dev/docs/commands/Should-BeLikeString](https://pester.dev/docs/commands/Should-BeLikeString) + +[https://pester.dev/docs/assertions](https://pester.dev/docs/assertions) + +## VERSION + +*This page was generated using comment-based help in [Pester 6.0.0-alpha1](https://github.com/pester/pester).* diff --git a/docs/commands/Should-BeNull.mdx b/docs/commands/Should-BeNull.mdx new file mode 100644 index 00000000..884c9fa7 --- /dev/null +++ b/docs/commands/Should-BeNull.mdx @@ -0,0 +1,95 @@ +--- +id: Should-BeNull +title: Should-BeNull +description: Help page for the PowerShell Pester "Should-BeNull" command +keywords: + - PowerShell + - Pester + - Help + - Documentation +hide_title: false +hide_table_of_contents: false +custom_edit_url: null +--- + +:::info This page was generated +Contributions are welcome in [Pester-repo](https://github.com/pester/pester). +::: + +## SYNOPSIS + +Asserts that the input is `$null`. + +## SYNTAX + +```powershell +Should-BeNull [[-Actual] ] [-Because ] [] +``` + +## DESCRIPTION + +\{\{ Fill in the Description \}\} + +## EXAMPLES + +### EXAMPLE 1 + +```powershell +$null | Should-BeNull +``` + +This assertion will pass, because the actual value is `$null`. + +## PARAMETERS + +### -Actual + +The actual value. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Because + +The reason why the input should be `$null`. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS + +[https://pester.dev/docs/commands/Should-BeNull](https://pester.dev/docs/commands/Should-BeNull) + +[https://pester.dev/docs/assertions](https://pester.dev/docs/assertions) + +## VERSION + +*This page was generated using comment-based help in [Pester 6.0.0-alpha1](https://github.com/pester/pester).* diff --git a/docs/commands/Should-BeSame.mdx b/docs/commands/Should-BeSame.mdx new file mode 100644 index 00000000..f8f776d0 --- /dev/null +++ b/docs/commands/Should-BeSame.mdx @@ -0,0 +1,124 @@ +--- +id: Should-BeSame +title: Should-BeSame +description: Help page for the PowerShell Pester "Should-BeSame" command +keywords: + - PowerShell + - Pester + - Help + - Documentation +hide_title: false +hide_table_of_contents: false +custom_edit_url: null +--- + +:::info This page was generated +Contributions are welcome in [Pester-repo](https://github.com/pester/pester). +::: + +## SYNOPSIS + +Compares the expected value to actual value, to see if they are the same instance. + +## SYNTAX + +```powershell +Should-BeSame [[-Actual] ] [-Expected] [-Because ] [] +``` + +## DESCRIPTION + +\{\{ Fill in the Description \}\} + +## EXAMPLES + +### EXAMPLE 1 + +```powershell +$a = New-Object Object +$a | Should-BeSame $a +``` + +This assertion will pass, because the actual value is the same instance as the expected value. + +### EXAMPLE 2 + +```powershell +$a = New-Object Object +$b = New-Object Object +$a | Should-BeSame $b +``` + +This assertion will fail, because the actual value is not the same instance as the expected value. + +## PARAMETERS + +### -Actual + +The actual value. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Expected + +The expected value. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Because + +The reason why the input should be the expected value. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +The `Should-BeSame` assertion is the opposite of the `Should-NotBeSame` assertion. + +## RELATED LINKS + +[https://pester.dev/docs/commands/Should-BeSame](https://pester.dev/docs/commands/Should-BeSame) + +[https://pester.dev/docs/assertions](https://pester.dev/docs/assertions) + +## VERSION + +*This page was generated using comment-based help in [Pester 6.0.0-alpha1](https://github.com/pester/pester).* diff --git a/docs/commands/Should-BeSlowerThan.mdx b/docs/commands/Should-BeSlowerThan.mdx new file mode 100644 index 00000000..ffb6611d --- /dev/null +++ b/docs/commands/Should-BeSlowerThan.mdx @@ -0,0 +1,113 @@ +--- +id: Should-BeSlowerThan +title: Should-BeSlowerThan +description: Help page for the PowerShell Pester "Should-BeSlowerThan" command +keywords: + - PowerShell + - Pester + - Help + - Documentation +hide_title: false +hide_table_of_contents: false +custom_edit_url: null +--- + +:::info This page was generated +Contributions are welcome in [Pester-repo](https://github.com/pester/pester). +::: + +## SYNOPSIS + +Asserts that the provided [timespan] is slower than the expected [timespan]. + +## SYNTAX + +```powershell +Should-BeSlowerThan [[-Actual] ] [[-Expected] ] [] +``` + +## DESCRIPTION + +\{\{ Fill in the Description \}\} + +## EXAMPLES + +### EXAMPLE 1 + +```powershell +{ Start-Sleep -Seconds 10 } | Should-BeSlowerThan 2seconds +``` + +This assertion will pass, because the actual value is slower than the expected value. + +### EXAMPLE 2 + +```powershell +[Timespan]::fromSeconds(10) | Should-BeSlowerThan 2seconds +``` + +This assertion will pass, because the actual value is slower than the expected value. + +### EXAMPLE 3 + +```powershell +{ Start-Sleep -Seconds 1 } | Should-BeSlowerThan 10seconds +``` + +This assertion will fail, because the actual value is not slower than the expected value. + +## PARAMETERS + +### -Actual + +The actual [timespan] or [scriptblock] value. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Expected + +The expected [timespan] or fluent time value. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +The `Should-BeSlowerThan` assertion is the opposite of the `Should-BeFasterThan` assertion. + +## RELATED LINKS + +[https://pester.dev/docs/commands/Should-BeSlowerThan](https://pester.dev/docs/commands/Should-BeSlowerThan) + +[https://pester.dev/docs/assertions](https://pester.dev/docs/assertions) + +## VERSION + +*This page was generated using comment-based help in [Pester 6.0.0-alpha1](https://github.com/pester/pester).* diff --git a/docs/commands/Should-BeString.mdx b/docs/commands/Should-BeString.mdx new file mode 100644 index 00000000..eb3dad29 --- /dev/null +++ b/docs/commands/Should-BeString.mdx @@ -0,0 +1,155 @@ +--- +id: Should-BeString +title: Should-BeString +description: Help page for the PowerShell Pester "Should-BeString" command +keywords: + - PowerShell + - Pester + - Help + - Documentation +hide_title: false +hide_table_of_contents: false +custom_edit_url: null +--- + +:::info This page was generated +Contributions are welcome in [Pester-repo](https://github.com/pester/pester). +::: + +## SYNOPSIS + +Asserts that the actual value is equal to the expected value. + +## SYNTAX + +```powershell +Should-BeString [[-Actual] ] [-Expected] [-Because ] [-CaseSensitive] + [-IgnoreWhitespace] [] +``` + +## DESCRIPTION + +The `Should-BeString` assertion compares the actual value to the expected value using the `-eq` operator. +The `-eq` operator is case-insensitive by default, but you can make it case-sensitive by using the `-CaseSensitive` switch. + +## EXAMPLES + +### EXAMPLE 1 + +```powershell +"hello" | Should-BeString "hello" +``` + +This assertion will pass, because the actual value is equal to the expected value. + +### EXAMPLE 2 + +```powershell +"hello" | Should-BeString "HELLO" -CaseSensitive +``` + +This assertion will fail, because the actual value is not equal to the expected value. + +## PARAMETERS + +### -Actual + +The actual value. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Expected + +The expected value. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Because + +The reason why the actual value should be equal to the expected value. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -CaseSensitive + +Indicates that the comparison should be case-sensitive. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -IgnoreWhitespace + +Indicates that the comparison should ignore whitespace. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +The `Should-BeString` assertion is the opposite of the `Should-NotBeString` assertion. + +## RELATED LINKS + +[https://pester.dev/docs/commands/Should-BeString](https://pester.dev/docs/commands/Should-BeString) + +[https://pester.dev/docs/assertions](https://pester.dev/docs/assertions) + +## VERSION + +*This page was generated using comment-based help in [Pester 6.0.0-alpha1](https://github.com/pester/pester).* diff --git a/docs/commands/Should-BeTrue.mdx b/docs/commands/Should-BeTrue.mdx new file mode 100644 index 00000000..73029e39 --- /dev/null +++ b/docs/commands/Should-BeTrue.mdx @@ -0,0 +1,111 @@ +--- +id: Should-BeTrue +title: Should-BeTrue +description: Help page for the PowerShell Pester "Should-BeTrue" command +keywords: + - PowerShell + - Pester + - Help + - Documentation +hide_title: false +hide_table_of_contents: false +custom_edit_url: null +--- + +:::info This page was generated +Contributions are welcome in [Pester-repo](https://github.com/pester/pester). +::: + +## SYNOPSIS + +Compares the actual value to a boolean $true. +It does not convert input values to boolean, and will fail for any value is not $true. + +## SYNTAX + +```powershell +Should-BeTrue [[-Actual] ] [[-Because] ] [] +``` + +## DESCRIPTION + +\{\{ Fill in the Description \}\} + +## EXAMPLES + +### EXAMPLE 1 + +```powershell +$true | Should-BeTrue +``` + +This assertion will pass. + +### EXAMPLE 2 + +```powershell +$false | Should-BeTrue +Get-Process | Should-BeTrue +$null | Should-BeTrue +$() | Should-BeTrue +@() | Should-BeTrue +0 | Should-BeTrue +``` + +All of these assertions will fail, because the actual value is not $true. + +## PARAMETERS + +### -Actual + +The actual value to compare to $true. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Because + +The reason why the input should be the expected value. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +The `Should-BeTrue` assertion is the opposite of the `Should-BeFalse` assertion. + +## RELATED LINKS + +[https://pester.dev/docs/commands/Should-BeTrue](https://pester.dev/docs/commands/Should-BeTrue) + +[https://pester.dev/docs/assertions](https://pester.dev/docs/assertions) + +## VERSION + +*This page was generated using comment-based help in [Pester 6.0.0-alpha1](https://github.com/pester/pester).* diff --git a/docs/commands/Should-BeTruthy.mdx b/docs/commands/Should-BeTruthy.mdx new file mode 100644 index 00000000..e8763a80 --- /dev/null +++ b/docs/commands/Should-BeTruthy.mdx @@ -0,0 +1,112 @@ +--- +id: Should-BeTruthy +title: Should-BeTruthy +description: Help page for the PowerShell Pester "Should-BeTruthy" command +keywords: + - PowerShell + - Pester + - Help + - Documentation +hide_title: false +hide_table_of_contents: false +custom_edit_url: null +--- + +:::info This page was generated +Contributions are welcome in [Pester-repo](https://github.com/pester/pester). +::: + +## SYNOPSIS + +Compares the actual value to a boolean $true. +It converts input values to boolean, and will fail for any value is not $true, or truthy. + +## SYNTAX + +```powershell +Should-BeTruthy [[-Actual] ] [[-Because] ] [] +``` + +## DESCRIPTION + +\{\{ Fill in the Description \}\} + +## EXAMPLES + +### EXAMPLE 1 + +```powershell +$true | Should-BeTruthy +1 | Should-BeTruthy +Get-Process | Should-BeTruthy +``` + +This assertion will pass. + +### EXAMPLE 2 + +```powershell +$false | Should-BeTruthy +$null | Should-BeTruthy +$() | Should-BeTruthy +@() | Should-BeTruthy +0 | Should-BeTruthy +``` + +All of these assertions will fail, because the actual value is not $true or truthy. + +## PARAMETERS + +### -Actual + +The actual value to compare to $true. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Because + +The reason why the input should be the expected value. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +The `Should-BeTruthy` assertion is the opposite of the `Should-BeFalsy` assertion. + +## RELATED LINKS + +[https://pester.dev/docs/commands/Should-BeTruthy](https://pester.dev/docs/commands/Should-BeTruthy) + +[https://pester.dev/docs/assertions](https://pester.dev/docs/assertions) + +## VERSION + +*This page was generated using comment-based help in [Pester 6.0.0-alpha1](https://github.com/pester/pester).* diff --git a/docs/commands/Should-ContainCollection.mdx b/docs/commands/Should-ContainCollection.mdx new file mode 100644 index 00000000..0122a340 --- /dev/null +++ b/docs/commands/Should-ContainCollection.mdx @@ -0,0 +1,123 @@ +--- +id: Should-ContainCollection +title: Should-ContainCollection +description: Help page for the PowerShell Pester "Should-ContainCollection" command +keywords: + - PowerShell + - Pester + - Help + - Documentation +hide_title: false +hide_table_of_contents: false +custom_edit_url: null +--- + +:::info This page was generated +Contributions are welcome in [Pester-repo](https://github.com/pester/pester). +::: + +## SYNOPSIS + +Compares collections to see if the expected collection is present in the provided collection. +It does not compare the types of the input collections. + +## SYNTAX + +```powershell +Should-ContainCollection [[-Actual] ] [-Expected] [-Because ] [] +``` + +## DESCRIPTION + +\{\{ Fill in the Description \}\} + +## EXAMPLES + +### EXAMPLE 1 + +```powershell +1, 2, 3 | Should-ContainCollection @(1, 2) +@(1) | Should-ContainCollection @(1) +``` + +This assertion will pass, because all items are present in the collection, in the right order. + +### EXAMPLE 2 + +```powershell +1, 2, 3 | Should-ContainCollection @(3, 4) +1, 2, 3 | Should-ContainCollection @(3, 2, 1) +@(1) | Should-ContainCollection @(2) +``` + +This assertion will fail, because not all items are present in the collection, or are not in the right order. + +## PARAMETERS + +### -Actual + +A collection of items. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Expected + +A collection of items. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Because + +The reason why the input should be the expected value. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS + +[https://pester.dev/docs/commands/Should-ContainCollection](https://pester.dev/docs/commands/Should-ContainCollection) + +[https://pester.dev/docs/assertions](https://pester.dev/docs/assertions) + +## VERSION + +*This page was generated using comment-based help in [Pester 6.0.0-alpha1](https://github.com/pester/pester).* diff --git a/docs/commands/Should-HaveType.mdx b/docs/commands/Should-HaveType.mdx new file mode 100644 index 00000000..ccb7d6ed --- /dev/null +++ b/docs/commands/Should-HaveType.mdx @@ -0,0 +1,112 @@ +--- +id: Should-HaveType +title: Should-HaveType +description: Help page for the PowerShell Pester "Should-HaveType" command +keywords: + - PowerShell + - Pester + - Help + - Documentation +hide_title: false +hide_table_of_contents: false +custom_edit_url: null +--- + +:::info This page was generated +Contributions are welcome in [Pester-repo](https://github.com/pester/pester). +::: + +## SYNOPSIS + +Asserts that the input is of the expected type. + +## SYNTAX + +```powershell +Should-HaveType [[-Actual] ] [-Expected] [-Because ] [] +``` + +## DESCRIPTION + +\{\{ Fill in the Description \}\} + +## EXAMPLES + +### EXAMPLE 1 + +```powershell +"hello" | Should-HaveType ([String]) +1 | Should-HaveType ([Int32]) +``` + +These assertions will pass, because the actual value is of the expected type. + +## PARAMETERS + +### -Actual + +The actual value. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Expected + +The expected type. + +```yaml +Type: Type +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Because + +The reason why the input should be the expected type. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS + +[https://pester.dev/docs/commands/Should-HaveType](https://pester.dev/docs/commands/Should-HaveType) + +[https://pester.dev/docs/assertions](https://pester.dev/docs/assertions) + +## VERSION + +*This page was generated using comment-based help in [Pester 6.0.0-alpha1](https://github.com/pester/pester).* diff --git a/docs/commands/Should-NotBe.mdx b/docs/commands/Should-NotBe.mdx new file mode 100644 index 00000000..0c37ee0f --- /dev/null +++ b/docs/commands/Should-NotBe.mdx @@ -0,0 +1,112 @@ +--- +id: Should-NotBe +title: Should-NotBe +description: Help page for the PowerShell Pester "Should-NotBe" command +keywords: + - PowerShell + - Pester + - Help + - Documentation +hide_title: false +hide_table_of_contents: false +custom_edit_url: null +--- + +:::info This page was generated +Contributions are welcome in [Pester-repo](https://github.com/pester/pester). +::: + +## SYNOPSIS + +Compares the expected value to actual value, to see if they are not equal. + +## SYNTAX + +```powershell +Should-NotBe [[-Actual] ] [-Expected] [-Because ] [] +``` + +## DESCRIPTION + +\{\{ Fill in the Description \}\} + +## EXAMPLES + +### EXAMPLE 1 + +```powershell +1 | Should-NotBe 2 +"hello" | Should-NotBe "world" +``` + +These assertions will pass, because the actual value is not equal to the expected value. + +## PARAMETERS + +### -Actual + +The actual value. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Expected + +The expected value. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Because + +The reason why the input should not be the expected value. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS + +[https://pester.dev/docs/commands/Should-NotBe](https://pester.dev/docs/commands/Should-NotBe) + +[https://pester.dev/docs/assertions](https://pester.dev/docs/assertions) + +## VERSION + +*This page was generated using comment-based help in [Pester 6.0.0-alpha1](https://github.com/pester/pester).* diff --git a/docs/commands/Should-NotBeEmptyString.mdx b/docs/commands/Should-NotBeEmptyString.mdx new file mode 100644 index 00000000..ea28a4fa --- /dev/null +++ b/docs/commands/Should-NotBeEmptyString.mdx @@ -0,0 +1,116 @@ +--- +id: Should-NotBeEmptyString +title: Should-NotBeEmptyString +description: Help page for the PowerShell Pester "Should-NotBeEmptyString" command +keywords: + - PowerShell + - Pester + - Help + - Documentation +hide_title: false +hide_table_of_contents: false +custom_edit_url: null +--- + +:::info This page was generated +Contributions are welcome in [Pester-repo](https://github.com/pester/pester). +::: + +## SYNOPSIS + +Ensures that the input is a string, and that the input is not $null or empty string. + +## SYNTAX + +```powershell +Should-NotBeEmptyString [[-Actual] ] [-Because ] [] +``` + +## DESCRIPTION + +\{\{ Fill in the Description \}\} + +## EXAMPLES + +### EXAMPLE 1 + +```powershell +$actual = "hello" +$actual | Should-NotBeEmptyString +``` + +This test will pass. + +### EXAMPLE 2 + +```powershell +$actual = "" +$actual | Should-NotBeEmptyString +``` + +This test will fail, the input is an empty string. + +### EXAMPLE 3 + +```powershell +$null | Should-NotBeEmptyString +$() | Should-NotBeEmptyString +$false | Should-NotBeEmptyString +1 | Should-NotBeEmptyString +``` + +All the tests above will fail, the input is not a string. + +## PARAMETERS + +### -Actual + +The actual value that will be compared. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Because + +The reason why the input should be a string that is not $null or empty. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS + +[https://pester.dev/docs/commands/Should-NotBeEmptyString](https://pester.dev/docs/commands/Should-NotBeEmptyString) + +[https://pester.dev/docs/assertions](https://pester.dev/docs/assertions) + +## VERSION + +*This page was generated using comment-based help in [Pester 6.0.0-alpha1](https://github.com/pester/pester).* diff --git a/docs/commands/Should-NotBeLikeString.mdx b/docs/commands/Should-NotBeLikeString.mdx new file mode 100644 index 00000000..cac6db53 --- /dev/null +++ b/docs/commands/Should-NotBeLikeString.mdx @@ -0,0 +1,139 @@ +--- +id: Should-NotBeLikeString +title: Should-NotBeLikeString +description: Help page for the PowerShell Pester "Should-NotBeLikeString" command +keywords: + - PowerShell + - Pester + - Help + - Documentation +hide_title: false +hide_table_of_contents: false +custom_edit_url: null +--- + +:::info This page was generated +Contributions are welcome in [Pester-repo](https://github.com/pester/pester). +::: + +## SYNOPSIS + +Asserts that the actual value is not like the expected value. + +## SYNTAX + +```powershell +Should-NotBeLikeString [[-Actual] ] [-Expected] [-CaseSensitive] [-Because ] + [] +``` + +## DESCRIPTION + +The `Should-NotBeLikeString` assertion compares the actual value to the expected value using the `-notlike` operator. +The `-notlike` operator is case-insensitive by default, but you can make it case-sensitive by using the `-CaseSensitive` switch. + +## EXAMPLES + +### EXAMPLE 1 + +```powershell +"hello" | Should-NotBeLikeString "H*" +``` + +This assertion will pass, because the actual value is not like the expected value. + +### EXAMPLE 2 + +```powershell +"hello" | Should-NotBeLikeString "h*" -CaseSensitive +``` + +This assertion will fail, because the actual value is like the expected value. + +## PARAMETERS + +### -Actual + +The actual value. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Expected + +The expected value. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -CaseSensitive + +Indicates that the comparison should be case-sensitive. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Because + +The reason why the actual value should not be like the expected value. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +The `Should-NotBeLikeString` assertion is the opposite of the `Should-BeLikeString` assertion. + +## RELATED LINKS + +[https://pester.dev/docs/commands/Should-NotBeLikeString](https://pester.dev/docs/commands/Should-NotBeLikeString) + +[https://pester.dev/docs/assertions](https://pester.dev/docs/assertions) + +## VERSION + +*This page was generated using comment-based help in [Pester 6.0.0-alpha1](https://github.com/pester/pester).* diff --git a/docs/commands/Should-NotBeNull.mdx b/docs/commands/Should-NotBeNull.mdx new file mode 100644 index 00000000..aa8e507c --- /dev/null +++ b/docs/commands/Should-NotBeNull.mdx @@ -0,0 +1,96 @@ +--- +id: Should-NotBeNull +title: Should-NotBeNull +description: Help page for the PowerShell Pester "Should-NotBeNull" command +keywords: + - PowerShell + - Pester + - Help + - Documentation +hide_title: false +hide_table_of_contents: false +custom_edit_url: null +--- + +:::info This page was generated +Contributions are welcome in [Pester-repo](https://github.com/pester/pester). +::: + +## SYNOPSIS + +Asserts that the input is not `$null`. + +## SYNTAX + +```powershell +Should-NotBeNull [[-Actual] ] [-Because ] [] +``` + +## DESCRIPTION + +\{\{ Fill in the Description \}\} + +## EXAMPLES + +### EXAMPLE 1 + +```powershell +"hello" | Should-NotBeNull +1 | Should-NotBeNull +``` + +These assertions will pass, because the actual value is not `$null. + +## PARAMETERS + +### -Actual + +The actual value. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Because + +The reason why the input should not be `$null`. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS + +[https://pester.dev/docs/commands/Should-NotBeNull](https://pester.dev/docs/commands/Should-NotBeNull) + +[https://pester.dev/docs/assertions](https://pester.dev/docs/assertions) + +## VERSION + +*This page was generated using comment-based help in [Pester 6.0.0-alpha1](https://github.com/pester/pester).* diff --git a/docs/commands/Should-NotBeSame.mdx b/docs/commands/Should-NotBeSame.mdx new file mode 100644 index 00000000..44244605 --- /dev/null +++ b/docs/commands/Should-NotBeSame.mdx @@ -0,0 +1,124 @@ +--- +id: Should-NotBeSame +title: Should-NotBeSame +description: Help page for the PowerShell Pester "Should-NotBeSame" command +keywords: + - PowerShell + - Pester + - Help + - Documentation +hide_title: false +hide_table_of_contents: false +custom_edit_url: null +--- + +:::info This page was generated +Contributions are welcome in [Pester-repo](https://github.com/pester/pester). +::: + +## SYNOPSIS + +Compares the expected value to actual value, to see if the actual value is not the same instance as the expected value. + +## SYNTAX + +```powershell +Should-NotBeSame [[-Actual] ] [-Expected] [-Because ] [] +``` + +## DESCRIPTION + +\{\{ Fill in the Description \}\} + +## EXAMPLES + +### EXAMPLE 1 + +``` +```powershell +$object = New-Object -TypeName PSObject +$object | Should-NotBeSame $object +```powershell +This assertion will pass, because the actual value is not the same instance as the expected value. +``` + +### EXAMPLE 2 + +```powershell +$object = New-Object -TypeName PSObject +$object | Should-NotBeSame $object +``` + +This assertion will fail, because the actual value is the same instance as the expected value. + +## PARAMETERS + +### -Actual + +The actual value. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Expected + +The expected value. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Because + +The reason why the input should not be the expected value. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +The `Should-NotBeSame` assertion is the opposite of the `Should-BeSame` assertion. + +## RELATED LINKS + +[https://pester.dev/docs/commands/Should-NotBeSame](https://pester.dev/docs/commands/Should-NotBeSame) + +[https://pester.dev/docs/assertions](https://pester.dev/docs/assertions) + +## VERSION + +*This page was generated using comment-based help in [Pester 6.0.0-alpha1](https://github.com/pester/pester).* diff --git a/docs/commands/Should-NotBeString.mdx b/docs/commands/Should-NotBeString.mdx new file mode 100644 index 00000000..76904f99 --- /dev/null +++ b/docs/commands/Should-NotBeString.mdx @@ -0,0 +1,157 @@ +--- +id: Should-NotBeString +title: Should-NotBeString +description: Help page for the PowerShell Pester "Should-NotBeString" command +keywords: + - PowerShell + - Pester + - Help + - Documentation +hide_title: false +hide_table_of_contents: false +custom_edit_url: null +--- + +:::info This page was generated +Contributions are welcome in [Pester-repo](https://github.com/pester/pester). +::: + +## SYNOPSIS + +Asserts that the actual value is not equal to the expected value. + +## SYNTAX + +```powershell +Should-NotBeString [[-Actual] ] [[-Expected] ] [-Because ] [-CaseSensitive] + [-IgnoreWhitespace] [] +``` + +## DESCRIPTION + +The `Should-NotBeString` assertion compares the actual value to the expected value using the `-ne` operator. +The `-ne` operator is case-insensitive by default, but you can make it case-sensitive by using the `-CaseSensitive` switch. + +## EXAMPLES + +### EXAMPLE 1 + +``` +```powershell +"hello" | Should-NotBeString "HELLO" +```powershell +This assertion will pass, because the actual value is not equal to the expected value. +``` + +### EXAMPLE 2 + +``` +```powershell +"hello" | Should-NotBeString "hello" -CaseSensitive +```powershell +This assertion will fail, because the actual value is equal to the expected value. +``` + +## PARAMETERS + +### -Actual + +The actual value. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Expected + +The expected value. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Because + +The reason why the actual value should not be equal to the expected value. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -CaseSensitive + +Indicates that the comparison should be case-sensitive. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -IgnoreWhitespace + +Indicates that the comparison should ignore whitespace. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +The `Should-NotBeString` assertion is the opposite of the `Should-BeString` assertion. + +## RELATED LINKS + +[https://pester.dev/docs/commands/Should-NotBeString](https://pester.dev/docs/commands/Should-NotBeString) + +[https://pester.dev/docs/assertions](https://pester.dev/docs/assertions) + +## VERSION + +*This page was generated using comment-based help in [Pester 6.0.0-alpha1](https://github.com/pester/pester).* diff --git a/docs/commands/Should-NotBeWhiteSpaceString.mdx b/docs/commands/Should-NotBeWhiteSpaceString.mdx new file mode 100644 index 00000000..e66cc9d3 --- /dev/null +++ b/docs/commands/Should-NotBeWhiteSpaceString.mdx @@ -0,0 +1,117 @@ +--- +id: Should-NotBeWhiteSpaceString +title: Should-NotBeWhiteSpaceString +description: Help page for the PowerShell Pester "Should-NotBeWhiteSpaceString" command +keywords: + - PowerShell + - Pester + - Help + - Documentation +hide_title: false +hide_table_of_contents: false +custom_edit_url: null +--- + +:::info This page was generated +Contributions are welcome in [Pester-repo](https://github.com/pester/pester). +::: + +## SYNOPSIS + +Ensures that the input is a string, and that the input is not $null, empty, or whitespace only string. + +## SYNTAX + +```powershell +Should-NotBeWhiteSpaceString [[-Actual] ] [-Because ] [] +``` + +## DESCRIPTION + +\{\{ Fill in the Description \}\} + +## EXAMPLES + +### EXAMPLE 1 + +```powershell +$actual = "hello" +$actual | Should-NotBeWhiteSpaceString +``` + +This test will pass. + +### EXAMPLE 2 + +```powershell +$actual = " " +$actual | Should-NotBeWhiteSpaceString +``` + +This test will fail, the input is a whitespace only string. + +### EXAMPLE 3 + +```powershell +$null | Should-NotBeWhiteSpaceString +"" | Should-NotBeWhiteSpaceString +$() | Should-NotBeWhiteSpaceString +$false | Should-NotBeWhiteSpaceString +1 | Should-NotBeWhiteSpaceString +``` + +All the tests above will fail, the input is not a string. + +## PARAMETERS + +### -Actual + +The actual value that will be compared. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Because + +The reason why the input should be a string that is not $null, empty, or whitespace only string. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS + +[https://pester.dev/docs/commands/Should-NotBeWhiteSpaceString](https://pester.dev/docs/commands/Should-NotBeWhiteSpaceString) + +[https://pester.dev/docs/assertions](https://pester.dev/docs/assertions) + +## VERSION + +*This page was generated using comment-based help in [Pester 6.0.0-alpha1](https://github.com/pester/pester).* diff --git a/docs/commands/Should-NotContainCollection.mdx b/docs/commands/Should-NotContainCollection.mdx new file mode 100644 index 00000000..5fc5e9b0 --- /dev/null +++ b/docs/commands/Should-NotContainCollection.mdx @@ -0,0 +1,123 @@ +--- +id: Should-NotContainCollection +title: Should-NotContainCollection +description: Help page for the PowerShell Pester "Should-NotContainCollection" command +keywords: + - PowerShell + - Pester + - Help + - Documentation +hide_title: false +hide_table_of_contents: false +custom_edit_url: null +--- + +:::info This page was generated +Contributions are welcome in [Pester-repo](https://github.com/pester/pester). +::: + +## SYNOPSIS + +Compares collections to ensure that the expected collection is not present in the provided collection. +It does not compare the types of the input collections. + +## SYNTAX + +```powershell +Should-NotContainCollection [[-Actual] ] [-Expected] [-Because ] [] +``` + +## DESCRIPTION + +\{\{ Fill in the Description \}\} + +## EXAMPLES + +### EXAMPLE 1 + +```powershell +1, 2, 3 | Should-ContainCollection @(3, 4) +1, 2, 3 | Should-ContainCollection @(3, 2, 1) +@(1) | Should-ContainCollection @(2) +``` + +This assertion will pass, because the collections are different, or the items are not in the right order. + +### EXAMPLE 2 + +```powershell +1, 2, 3 | Should-NotContainCollection @(1, 2) +@(1) | Should-NotContainCollection @(1) +``` + +This assertion will fail, because all items are present in the collection and are in the right order. + +## PARAMETERS + +### -Actual + +A collection of items. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Expected + +A collection of items. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Because + +The reason why the input should be the expected value. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS + +[https://pester.dev/docs/commands/Should-NotContainCollection](https://pester.dev/docs/commands/Should-NotContainCollection) + +[https://pester.dev/docs/assertions](https://pester.dev/docs/assertions) + +## VERSION + +*This page was generated using comment-based help in [Pester 6.0.0-alpha1](https://github.com/pester/pester).* diff --git a/docs/commands/Should-NotHaveType.mdx b/docs/commands/Should-NotHaveType.mdx new file mode 100644 index 00000000..4c0f519a --- /dev/null +++ b/docs/commands/Should-NotHaveType.mdx @@ -0,0 +1,114 @@ +--- +id: Should-NotHaveType +title: Should-NotHaveType +description: Help page for the PowerShell Pester "Should-NotHaveType" command +keywords: + - PowerShell + - Pester + - Help + - Documentation +hide_title: false +hide_table_of_contents: false +custom_edit_url: null +--- + +:::info This page was generated +Contributions are welcome in [Pester-repo](https://github.com/pester/pester). +::: + +## SYNOPSIS + +Asserts that the input is not of the expected type. + +## SYNTAX + +```powershell +Should-NotHaveType [[-Actual] ] [-Expected] [-Because ] [] +``` + +## DESCRIPTION + +\{\{ Fill in the Description \}\} + +## EXAMPLES + +### EXAMPLE 1 + +```powershell +"hello" | Should-NotHaveType ([Int32]) +1 | Should-NotHaveType ([String]) +``` + +These assertions will pass, because the actual value is not of the expected type. + +## PARAMETERS + +### -Actual + +The actual value. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Expected + +The expected type. + +```yaml +Type: Type +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Because + +The reason why the input should not be the expected type. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +This assertion is the opposite of `Should-HaveType`. + +## RELATED LINKS + +[https://pester.dev/docs/commands/Should-NotHaveType](https://pester.dev/docs/commands/Should-NotHaveType) + +[https://pester.dev/docs/assertions](https://pester.dev/docs/assertions) + +## VERSION + +*This page was generated using comment-based help in [Pester 6.0.0-alpha1](https://github.com/pester/pester).* diff --git a/docs/commands/Should-Throw.mdx b/docs/commands/Should-Throw.mdx new file mode 100644 index 00000000..ed264685 --- /dev/null +++ b/docs/commands/Should-Throw.mdx @@ -0,0 +1,176 @@ +--- +id: Should-Throw +title: Should-Throw +description: Help page for the PowerShell Pester "Should-Throw" command +keywords: + - PowerShell + - Pester + - Help + - Documentation +hide_title: false +hide_table_of_contents: false +custom_edit_url: null +--- + +:::info This page was generated +Contributions are welcome in [Pester-repo](https://github.com/pester/pester). +::: + +## SYNOPSIS + +Asserts that a script block throws an exception. + +## SYNTAX + +```powershell +Should-Throw [-ScriptBlock] [[-ExceptionType] ] [[-ExceptionMessage] ] + [[-FullyQualifiedErrorId] ] [-AllowNonTerminatingError] [[-Because] ] [] +``` + +## DESCRIPTION + +\{\{ Fill in the Description \}\} + +## EXAMPLES + +### EXAMPLE 1 + +```powershell +{ throw 'error' } | Should-Throw +{ throw 'error' } | Should-Throw -ExceptionMessage 'error' +{ throw 'error' } | Should-Throw -ExceptionType 'System.Management.Automation.RuntimeException' +{ throw 'error' } | Should-Throw -FullyQualifiedErrorId 'RuntimeException' +{ throw 'error' } | Should-Throw -FullyQualifiedErrorId '*Exception' +{ throw 'error' } | Should-Throw -AllowNonTerminatingError +``` + +All of these assertions will pass. + +### EXAMPLE 2 + +```powershell +$err = { throw 'error' } | Should-Throw +$err.Exception.Message | Should-BeLike '*err*' +``` + +The error record is returned from the assertion and can be used in further assertions. + +## PARAMETERS + +### -ScriptBlock + +The script block that should throw an exception. + +```yaml +Type: ScriptBlock +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -ExceptionType + +The type of exception that should be thrown. + +```yaml +Type: Type +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ExceptionMessage + +The message that the exception should contain. +`-like` wildcards are supported. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 3 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -FullyQualifiedErrorId + +The FullyQualifiedErrorId that the exception should contain. +`-like` wildcards are supported. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 4 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -AllowNonTerminatingError + +If set, the assertion will pass if a non-terminating error is thrown. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Because + +The reason why the input should be the expected value. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 5 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS + +[https://pester.dev/docs/commands/Should-Throw](https://pester.dev/docs/commands/Should-Throw) + +[https://pester.dev/docs/assertions](https://pester.dev/docs/assertions) + +## VERSION + +*This page was generated using comment-based help in [Pester 6.0.0-alpha1](https://github.com/pester/pester).* diff --git a/docs/commands/Should.mdx b/docs/commands/Should.mdx index 2f5fef43..4752e02f 100644 --- a/docs/commands/Should.mdx +++ b/docs/commands/Should.mdx @@ -1181,4 +1181,4 @@ This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable ## VERSION -*This page was generated using comment-based help in [Pester 5.6.0](https://github.com/pester/pester).* +*This page was generated using comment-based help in [Pester 6.0.0-alpha1](https://github.com/pester/pester).* diff --git a/docs/commands/docusaurus.sidebar.js b/docs/commands/docusaurus.sidebar.js index 9e69da4f..4fe28218 100644 --- a/docs/commands/docusaurus.sidebar.js +++ b/docs/commands/docusaurus.sidebar.js @@ -12,8 +12,6 @@ module.exports = [ 'commands/Add-ShouldOperator', 'commands/AfterAll', 'commands/AfterEach', - 'commands/Assert-MockCalled', - 'commands/Assert-VerifiableMock', 'commands/BeforeAll', 'commands/BeforeDiscovery', 'commands/BeforeEach', @@ -24,6 +22,7 @@ module.exports = [ 'commands/Describe', 'commands/Export-JUnitReport', 'commands/Export-NUnitReport', + 'commands/Get-EquivalencyOption', 'commands/Get-ShouldOperator', 'commands/InModuleScope', 'commands/Invoke-Pester', @@ -34,5 +33,39 @@ module.exports = [ 'commands/New-PesterConfiguration', 'commands/New-PesterContainer', 'commands/Set-ItResult', + 'commands/Should-All', + 'commands/Should-Any', + 'commands/Should-Be', + 'commands/Should-BeAfter', + 'commands/Should-BeBefore', + 'commands/Should-BeCollection', + 'commands/Should-BeEmptyString', + 'commands/Should-BeEquivalent', + 'commands/Should-BeFalse', + 'commands/Should-BeFalsy', + 'commands/Should-BeFasterThan', + 'commands/Should-BeGreaterThan', + 'commands/Should-BeGreaterThanOrEqual', + 'commands/Should-BeLessThan', + 'commands/Should-BeLessThanOrEqual', + 'commands/Should-BeLikeString', + 'commands/Should-BeNull', + 'commands/Should-BeSame', + 'commands/Should-BeSlowerThan', + 'commands/Should-BeString', + 'commands/Should-BeTrue', + 'commands/Should-BeTruthy', + 'commands/Should-ContainCollection', + 'commands/Should-HaveType', + 'commands/Should-NotBe', + 'commands/Should-NotBeEmptyString', + 'commands/Should-NotBeLikeString', + 'commands/Should-NotBeNull', + 'commands/Should-NotBeSame', + 'commands/Should-NotBeString', + 'commands/Should-NotBeWhiteSpaceString', + 'commands/Should-NotContainCollection', + 'commands/Should-NotHaveType', + 'commands/Should-Throw', 'commands/Should' ]; diff --git a/docs/introduction/installation.mdx b/docs/introduction/installation.mdx index af1bb73d..60a2bbe8 100644 --- a/docs/introduction/installation.mdx +++ b/docs/introduction/installation.mdx @@ -7,9 +7,9 @@ description: Pester is a cross-platform PowerShell module for testing your Power ## Compatibility -Pester is a cross-platform module that runs on Windows, Linux, MacOS and anywhere else supported by PowerShell. It is tested and compatible with: -- Windows PowerShell 3.0 - 5.1 -- PowerShell 6.0.4 and above +Pester is a cross-platform module that runs on Windows, Linux, MacOS and anywhere else running a supported version of PowerShell. Pester currently requires and is tested with: +- Windows PowerShell 5.1 +- PowerShell 7.2 and above ## Installing from PowerShell Gallery @@ -78,12 +78,6 @@ WARNING: Unable to resolve package source 'https://www.powershellgallery.com/api [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor [System.Net.SecurityProtocolType]::Tls12 ``` -#### Command `Install-Module` is not found - -Older versions of Windows running Windows PowerShell 3.0 or 4.0 do not have a built-in package manager. You can install `PowerShellGet` using the [instructions here](https://docs.microsoft.com/en-us/powershell/scripting/gallery/installing-psget#for-computers-running-powershell-30-or-powershell-40). After completing the steps, start a new PowerShell session and retry [the module installation](#installing-from-powershell-gallery). - -Alternatively, you can install the module manually using the instructions below. - ## Installing manually You don't have to use a package manager to install Pester. Another option is to download and installing it manually which can be useful in e.g. offline environments. diff --git a/docs/migrations/breaking-changes-in-v5.mdx b/docs/migrations/breaking-changes-in-v5.mdx index ebf3d5d0..c27a97d2 100644 --- a/docs/migrations/breaking-changes-in-v5.mdx +++ b/docs/migrations/breaking-changes-in-v5.mdx @@ -6,7 +6,7 @@ description: Pester v5 included an all-new runtime which lead to some breaking c ## Actual breaking changes -- (❗ new in 5.0.1) The Parameters of `Invoke-Pester` changed significantly, but in 5.0.1, a compatibility parameter set was added. To allow all the v4 parameters to be used, e.g. like this `Invoke-Pester -Script $testFile -PassThru -Verbose -OutputFile $tr -OutputFormat NUnitXml -CodeCoverage "$tmp/*-*.ps1" -CodeCoverageOutputFile $cc -Show All`. The compatibility is not 100%, neither -Script not -CodeCoverage take hashtables, they just take a collection of paths. The `-Strict` parameter and `-PesterOption` are ignored. The `-Output` \ `-Show` parameter takes all the values, but translates only the most used options to Pester 5 compatible options, otherwise it uses `Detailed` output. It also allows all the Pester 5 output options, to allow you to use `Diagnostic` during migration. **This whole Legacy-parameter set is deprecated** and prints a warning when used. For more options and the Advanced interface see [simple and advanced interface](./v4-to-v5#simple-and-advanced-interface) above on how to invoke Pester. +- The Parameters of `Invoke-Pester` changed significantly, but in 5.0.1, a compatibility parameter set was added. To allow all the v4 parameters to be used, e.g. like this `Invoke-Pester -Script $testFile -PassThru -Verbose -OutputFile $tr -OutputFormat NUnitXml -CodeCoverage "$tmp/*-*.ps1" -CodeCoverageOutputFile $cc -Show All`. The compatibility is not 100%, neither -Script not -CodeCoverage take hashtables, they just take a collection of paths. The `-Strict` parameter and `-PesterOption` are ignored. The `-Output` \ `-Show` parameter takes all the values, but translates only the most used options to Pester 5 compatible options, otherwise it uses `Detailed` output. It also allows all the Pester 5 output options, to allow you to use `Diagnostic` during migration. **This whole Legacy-parameter set is deprecated** and prints a warning when used. For more options and the Advanced interface see [simple and advanced interface](./v4-to-v5#simple-and-advanced-interface) above on how to invoke Pester. - PowerShell 2 is no longer supported - Legacy syntax `Should Be` (without `-`) is removed, see [Migrating from Pester v3 to v4](./v3-to-v4) - Mocks are scoped based on their placement, not in whole `Describe` / `Context`. The count also depends on their placement. See [mock scoping](../usage/mocking#mocks-are-scoped-based-on-their-placement) diff --git a/docs/migrations/v5-to-v6.mdx b/docs/migrations/v5-to-v6.mdx new file mode 100644 index 00000000..9bf3712f --- /dev/null +++ b/docs/migrations/v5-to-v6.mdx @@ -0,0 +1,50 @@ +--- +id: v5-to-v6 +title: Migrating from Pester v5 to v6 +sidebar_label: Pester v5 to v6 +description: See this guide for how to update your tests to be compatible with Pester v6. +--- + +Pester v6 builds upon the new runtime introduced in v5 and behaves mostly the same which ensures backwards-compatibility. This guide will highlight any necessary steps to update your code and environment to run Pester v6. + +## Breaking Changes + +### Removed support for PowerShell 3, 4, 5.0, 6, 7.0 and 7.1 + +To be able to support new functionality and modernize the codebase, Pester 6.0.0 dropped support for unsupported versions of PowerShell. +It currently requires Windows PowerShell 5.1 or PowerShell 7.2 and later, see [Installation](../introduction/installation#compatibility). + +Make sure your computer and/or CI-systems are updated to run a supported version of PowerShell. + +### Removed `Assert-MockCalled` and `Assert-VerifiableMock` + +Both functions were deprecated and replaced in Pester v5 and has been fully removed in Pester v6. Replace: +- `Assert-MockCalled` with [Should -Invoke](../usage/mocking) +- `Assert-VerifiableMock` with [Should -InvokeVerifiable](../usage/mocking) + +### Removed `Set-ItResult -Pending` + +The Pending result was never fully implemented in v5 and has been removed in v6. + +Replace any calls to `Set-ItResult -Pending` with `Set-ItResult -Inconclusive/-Skip` or mark the test using `It .. -Skip`. + +### Discovery throws on empty `-ForEach` values + +[Data-driven tests](../usage/data-driven-tests) will throw when provided `$null` or an empty array to `-ForEach/TestCases`. This makes it easier to detect common errors like referencing a variable that is not defined in `BeforeDiscovery` or provided as external data. Previously these tests and blocks would be silently ignored. + +To allow empty data in specific blocks or tests, use the new `-AllowNullOrEmptyForEach` switch in `Describe/Context/It`. +To disable the new behavior globally, set the configuration option `Run.FailOnNullOrEmptyForEach` to `$false`. + +## Changed Defaults + +### Code Coverage defaults to the newer Profiler-based tracer + +When using Code Coverage it will now run using the newer and faster Profiler-based tracer instead of using breakpoints. +The option `CodeCoverage.UseBreakpoints` is no longer experimental mode and the new default is `$false`. + +To switch back to the older breakpoints-mode, set `CodeCoverage.UseBreakpoints` to `$true`. + +:::warning Guide is incomplete +Like the v6 preview docs in general this guide is incomplete and will be updated as we release new builds. +To keep up with the latest development, see the release notes for 6.0.0 pre-release builds at https://github.com/pester/Pester/releases +::: diff --git a/docs/usage/configuration.mdx b/docs/usage/configuration.mdx index 6567b4c6..709a513a 100644 --- a/docs/usage/configuration.mdx +++ b/docs/usage/configuration.mdx @@ -3,30 +3,29 @@ title: Configuration description: Documentation about how to configure the behavior, options and features in Pester --- -### Advanced interface +## Advanced interface Advanced interface uses `PesterConfiguration` object which contains all options that you can provide to Pester and contains descriptions for all the configuration sections and as well as default values. Here is what you see when you look at the default Debug section of the object: ```powershell -[PesterConfiguration]::Default.Debug | Format-List +(New-PesterConfiguration).Debug | Format-List -ShowFullErrors : Show full errors including Pester internal stack. (False, default: False) +ShowFullErrors : Show full errors including Pester internal stack. This property is deprecated, and if set to true it will override Output.StackTraceVerbosity to 'Full'. (False, default: False) WriteDebugMessages : Write Debug messages to screen. (False, default: False) -WriteDebugMessagesFrom : Write Debug messages from a given source, WriteDebugMessages must be set to true for this to work. You can use like wildcards to get messages from multiple sources, as well as * to get everything. (*, default: *) +WriteDebugMessagesFrom : Write Debug messages from a given source, WriteDebugMessages must be set to true for this to work. You can use like wildcards to get messages from multiple sources, as well as * to get + everything. (System.String[], default: System.String[]) ShowNavigationMarkers : Write paths after every block and test, for easy navigation in VSCode. (False, default: False) +ReturnRawResultObject : Returns unfiltered result object, this is for development only. Do not rely on this object for additional properties, non-public properties will be renamed without previous notice. (False, + default: False) ``` -:::tip New in Pester 5.2.0! -[New-PesterConfiguration](../commands/New-PesterConfiguration) is now available and the recommended way to create the PesterConfiguration-object. It has the added benefit of auto-loading the Pester-module if needed and up-to-date help of available options in the configuration object. -::: - -The configuration object can be constructed either via the Default static property or by casting a hashtable to it. You can also cast a hashtable to any of its sections. Here are three different ways to the same goal: +The configuration object can be constructed either using the `New-PesterConfiguration` command or by casting a hashtable to the `PesterConfiguration` type. Here are three different ways to the same goal: ```powershell # import module before creating the object Import-Module Pester # get default from static property -$configuration = [PesterConfiguration]::Default +$configuration = New-PesterConfiguration # adding properties & discover via intellisense $configuration.Run.Path = 'C:\projects\tst' $configuration.Filter.Tag = 'Acceptance' @@ -69,14 +68,14 @@ $configuration.CodeCoverage.Enabled = $true This configuration object contains all the options that are currently supported and the Simple interface is internally translates to this object internally. It is the source of truth for the defaults and configuration. The Intermediate api will be figured out later, as well as all the other details. -### PesterPreference +## PesterPreference There is one more way to provide the configuration object which is `$PesterPreference`. On `Invoke-Pester` (in case of interactive execution `Invoke-Pester` is called inside of the first `Describe`) the preference is collected and merged with the configuration object if provided. This allows you to configure everything that you would via Invoke-Pester also when you are running interactively (via `F5`). You can also use this to define the defaults for your session by putting $PesterPreference into your PowerShell profile. Here is a simple example of enabling Mock logging output while running interactively : ```powershell -$PesterPreference = [PesterConfiguration]::Default +$PesterPreference = New-PesterConfiguration $PesterPreference.Debug.WriteDebugMessages = $true $PesterPreference.Debug.WriteDebugMessagesFrom = "Mock" @@ -123,3 +122,134 @@ Mock: Removing function PesterMock_b0bde5ee-1b4f-4b8f-b1dd-aef38b3bc13d and alia Tests completed in 1.12s Tests Passed: 1, Failed: 0, Skipped: 0, Total: 1, NotRun: 0 ``` + +## PesterConfiguration Options + + + +*This section was generated using Pester 6.0.0-alpha1.* + +### Run + +Run configuration. + +
+| Option | Description | Type | Default | +|--------|-------------|-----:|--------:| +| Run.Path | Directories to be searched for tests, paths directly to test files, or combination of both. | `string[]` | `@('.')` | +| Run.ExcludePath | Directories or files to be excluded from the run. | `string[]` | `@()` | +| Run.ScriptBlock | ScriptBlocks containing tests to be executed. | `scriptblock[]` | `@()` | +| Run.Container | ContainerInfo objects containing tests to be executed. | `ContainerInfo[]` | `@()` | +| Run.TestExtension | Filter used to identify test files. | `string` | `'.Tests.ps1'` | +| Run.Exit | Exit with non-zero exit code when the test run fails. Exit code is always set to `$LASTEXITCODE` even when this option is `$false`. When used together with Throw, throwing an exception is preferred. | `bool` | `$false` | +| Run.Throw | Throw an exception when test run fails. When used together with Exit, throwing an exception is preferred. | `bool` | `$false` | +| Run.PassThru | Return result object to the pipeline after finishing the test run. | `bool` | `$false` | +| Run.SkipRun | Runs the discovery phase but skips run. Use it with PassThru to get object populated with all tests. | `bool` | `$false` | +| Run.SkipRemainingOnFailure | Skips remaining tests after failure for selected scope, options are None, Run, Container and Block. | `string` | `'None'` | +
+ +### Filter + +Filter configuration + +
+| Option | Description | Type | Default | +|--------|-------------|-----:|--------:| +| Filter.Tag | Tags of Describe, Context or It to be run. | `string[]` | `@()` | +| Filter.ExcludeTag | Tags of Describe, Context or It to be excluded from the run. | `string[]` | `@()` | +| Filter.Line | Filter by file and scriptblock start line, useful to run parsed tests programmatically to avoid problems with expanded names. Example: 'C:\tests\file1.Tests.ps1:37' | `string[]` | `@()` | +| Filter.ExcludeLine | Exclude by file and scriptblock start line, takes precedence over Line. | `string[]` | `@()` | +| Filter.FullName | Full name of test with -like wildcards, joined by dot. Example: '*.describe Get-Item.test1' | `string[]` | `@()` | +
+ +### CodeCoverage + +CodeCoverage configuration. + +
+| Option | Description | Type | Default | +|--------|-------------|-----:|--------:| +| CodeCoverage.Enabled | Enable CodeCoverage. | `bool` | `$false` | +| CodeCoverage.OutputFormat | Format to use for code coverage report. Possible values: JaCoCo, CoverageGutters | `string` | `'JaCoCo'` | +| CodeCoverage.OutputPath | Path relative to the current directory where code coverage report is saved. | `string` | `'coverage.xml'` | +| CodeCoverage.OutputEncoding | Encoding of the output file. | `string` | `'UTF8'` | +| CodeCoverage.Path | Directories or files to be used for code coverage, by default the Path(s) from general settings are used, unless overridden here. | `string[]` | `@()` | +| CodeCoverage.ExcludeTests | Exclude tests from code coverage. This uses the TestFilter from general configuration. | `bool` | `$true` | +| CodeCoverage.RecursePaths | Will recurse through directories in the Path option. | `bool` | `$true` | +| CodeCoverage.CoveragePercentTarget | Target percent of code coverage that you want to achieve, default 75%. | `decimal` | `75` | +| CodeCoverage.UseBreakpoints | When false, use Profiler based tracer to do CodeCoverage instead of using breakpoints. | `bool` | `$false` | +| CodeCoverage.SingleHitBreakpoints | Remove breakpoint when it is hit. This increases performance of breakpoint based CodeCoverage. | `bool` | `$true` | +
+ +### TestResult + +TestResult configuration. + +
+| Option | Description | Type | Default | +|--------|-------------|-----:|--------:| +| TestResult.Enabled | Enable TestResult. | `bool` | `$false` | +| TestResult.OutputFormat | Format to use for test result report. Possible values: NUnitXml, NUnit2.5, NUnit3 or JUnitXml | `string` | `'NUnitXml'` | +| TestResult.OutputPath | Path relative to the current directory where test result report is saved. | `string` | `'testResults.xml'` | +| TestResult.OutputEncoding | Encoding of the output file. | `string` | `'UTF8'` | +| TestResult.TestSuiteName | Set the name assigned to the root 'test-suite' element. | `string` | `'Pester'` | +
+ +### Should + +Should configuration. + +
+| Option | Description | Type | Default | +|--------|-------------|-----:|--------:| +| Should.ErrorAction | Controls if Should throws on error. Use 'Stop' to throw on error, or 'Continue' to fail at the end of the test. | `string` | `'Stop'` | +
+ +### Debug + +Debug configuration for Pester. ⚠ Use at your own risk! + +
+| Option | Description | Type | Default | +|--------|-------------|-----:|--------:| +| Debug.ShowFullErrors | Show full errors including Pester internal stack. This property is deprecated, and if set to true it will override Output.StackTraceVerbosity to 'Full'. | `bool` | `$false` | +| Debug.WriteDebugMessages | Write Debug messages to screen. | `bool` | `$false` | +| Debug.WriteDebugMessagesFrom | Write Debug messages from a given source, WriteDebugMessages must be set to true for this to work. You can use like wildcards to get messages from multiple sources, as well as * to get everything. | `string[]` | `@('Discovery', 'Skip', 'Mock', 'CodeCoverage')` | +| Debug.ShowNavigationMarkers | Write paths after every block and test, for easy navigation in VSCode. | `bool` | `$false` | +| Debug.ReturnRawResultObject | Returns unfiltered result object, this is for development only. Do not rely on this object for additional properties, non-public properties will be renamed without previous notice. | `bool` | `$false` | +
+ +### Output + +Output configuration + +
+| Option | Description | Type | Default | +|--------|-------------|-----:|--------:| +| Output.Verbosity | The verbosity of output, options are None, Normal, Detailed and Diagnostic. | `string` | `'Normal'` | +| Output.StackTraceVerbosity | The verbosity of stacktrace output, options are None, FirstLine, Filtered and Full. | `string` | `'Filtered'` | +| Output.CIFormat | The CI format of error output in build logs, options are None, Auto, AzureDevops and GithubActions. | `string` | `'Auto'` | +| Output.CILogLevel | The CI log level in build logs, options are Error and Warning. | `string` | `'Error'` | +| Output.RenderMode | The mode used to render console output, options are Auto, Ansi, ConsoleColor and Plaintext. | `string` | `'Auto'` | +
+ +### TestDrive + +TestDrive configuration. + +
+| Option | Description | Type | Default | +|--------|-------------|-----:|--------:| +| TestDrive.Enabled | Enable TestDrive. | `bool` | `$true` | +
+ +### TestRegistry + +TestRegistry configuration. + +
+| Option | Description | Type | Default | +|--------|-------------|-----:|--------:| +| TestRegistry.Enabled | Enable TestRegistry. | `bool` | `$true` | +
+ diff --git a/docs/usage/data-driven-tests.mdx b/docs/usage/data-driven-tests.mdx index 51868f13..746a44b5 100644 --- a/docs/usage/data-driven-tests.mdx +++ b/docs/usage/data-driven-tests.mdx @@ -149,8 +149,6 @@ Describe "Get-Emoji " -ForEach @( } ``` - - ## Using `-ForEach` & `-TestCases` with an array `-ForEach` is most powerful when used with an array of hashtables, but it can take any array. In that case it will define `$_` variable, representing the current item. This approach can be used on `Describe`, `Context` and `It`: @@ -179,10 +177,15 @@ Describe "Get-FruitBasket" { } ``` -:::tip +:::tip Array of hashtables `-ForEach` defines the `$_` variable even when used with an array of hashtables. In that case `$_` will be set to the current hashtable. ::: +:::warning Empty or null data +Pester v6 will throw an exception when `-ForEach` is passed `$null` or an empty array to avoid silently ignoring the test. +To allow tests with missing/no data, use the `-AllowNullOrEmptyForEach` switch in `Describe/Context/It` or allow globally by setting the [configuration option](./configuration) `Run.FailOnNullOrEmptyForEach` to `$false`. +::: + ## Using `<>` templates Test and block names can contain values surrounded by `<>` in their name. Those will be considered a template, and will be expanded. Any variable available in scope can be expanded using this syntax, not just the data from `-ForEach`: @@ -480,7 +483,7 @@ Invoke-Pester -Container $containers -Output Detailed ## `BeforeDiscovery` -In Pester v4 it was normal to place code directly on top of the script file, or directly into the body of `Describe` and `Context`. Pester v5 discourages this, because all code directly in script or in `Describe / Context` body will run during `Discovery`. This leads to unexpected results. +In Pester v4 it was normal to place code directly on top of the script file, or directly into the body of `Describe` and `Context`. Pester v5 and later discourages this, because all code directly in script or in `Describe / Context` body will run during `Discovery`. This leads to unexpected results. BUT in some cases, especially when generating tests, putting code directly in script body is okay. `BeforeDiscovery` was introduced to show that the code is like this intentionally, and not by accident. Wrapping code into `BeforeDiscovery` has no impact on its execution. It should be used everywhere where code is intentionally placed outside of a Pester controlled leaf-block (see [Discovery and Run](discovery-and-run)). That is on top of files, or directly in body of `Describe / Context`. @@ -507,13 +510,13 @@ Describe "File - <_>" -ForEach $files { ## Migrating from Pester v4 -There are two main things to take into account when Data driven tests in Pester v5: The [execution is not top down](#execution-is-not-top-down) like in V4 but done in two phases `Discovery` and `Run`. Variables from `Discovery` are not available in `Run`, unless you explicitly attach them to a `Describe`, `Context` or `It` using `Foreach` or `TestCases` +There are two main things to take into account when Data driven tests in Pester v5+: The [execution is not top down](#execution-is-not-top-down) like in V4 but done in two phases `Discovery` and `Run`. Variables from `Discovery` are not available in `Run`, unless you explicitly attach them to a `Describe`, `Context` or `It` using `Foreach` or `TestCases` This has big impact the classic pattern of using `foreach` to generate tests. ### Execution is not top down -Pester v5 introduces a new two phase execution. In the first phase called `Discovery`, it will run your whole test script from top to bottom. It will also run all ScriptBlocks that you provided to any `Describe`, `Context` and `BeforeDiscovery`. It will collect the ScriptBlocks you provided to `It`, `BeforeAll`, `BeforeEach`, `AfterEach` and `AfterAll`, but won't run them until later. +Pester v5 introduced a new two phase execution. In the first phase called `Discovery`, it will run your whole test script from top to bottom. It will also run all ScriptBlocks that you provided to any `Describe`, `Context` and `BeforeDiscovery`. It will collect the ScriptBlocks you provided to `It`, `BeforeAll`, `BeforeEach`, `AfterEach` and `AfterAll`, but won't run them until later. | Phase | V4 | V5 Discovery | V5 Run | | :---------------- | :--- | :----------- | :----- | @@ -670,7 +673,7 @@ foreach ($file in $files) { } ``` -This approach can still be easily converted to Pester v5: +This approach can still be easily converted to Pester v5+: ```powershell BeforeDiscovery { diff --git a/docs/usage/discovery-and-run.mdx b/docs/usage/discovery-and-run.mdx index 200963a6..38aee85e 100644 --- a/docs/usage/discovery-and-run.mdx +++ b/docs/usage/discovery-and-run.mdx @@ -23,7 +23,7 @@ In Pester v4 the execution of your test code was mostly top-down, with the excep For example placing an `AfterAll` at the top of a `Describe` would not run it at the top, but instead it would correctly run it as the last thing in that `Describe` wrapped in a `try finally`. -Pester v5 takes this to the next level and manipulates the execution of your test file in a more complex way. This has good reason, but makes understanding how your code executes quite complex, especially when you don't follow the two rules listed above. +Pester v5 and later takes this to the next level and manipulates the execution of your test file in a more complex way. This has good reason, but makes understanding how your code executes quite complex, especially when you don't follow the two rules listed above. ### Discovery diff --git a/docs/usage/importing-tested-functions.mdx b/docs/usage/importing-tested-functions.mdx index 412cb6a5..5d1be4f4 100644 --- a/docs/usage/importing-tested-functions.mdx +++ b/docs/usage/importing-tested-functions.mdx @@ -44,7 +44,7 @@ Pester v4 users might be inclined not to use the `BeforeAll` block or to use `$M ## Migrating from Pester v4 ### Put setup in BeforeAll -In Pester v5 the setup code should be put into a `BeforeAll` block, and `$MyInvocation.MyCommand.Path` should *NOT* be used: +In Pester v5 and later the setup code should be put into a `BeforeAll` block, and `$MyInvocation.MyCommand.Path` should *NOT* be used: ```powershell # BEFORE (Pester v4): @@ -61,7 +61,7 @@ Describe "Get-Cactus" { ``` ```powershell -# AFTER (Pester v5): +# AFTER (Pester v5+): BeforeAll { # DON'T use $MyInvocation.MyCommand.Path diff --git a/docs/usage/mocking.mdx b/docs/usage/mocking.mdx index a631c26e..3469685d 100644 --- a/docs/usage/mocking.mdx +++ b/docs/usage/mocking.mdx @@ -94,65 +94,27 @@ If you need to mock calls to commands which are made from inside a Script Module ### Mocking a function that is called by a method in a PowerShell class -In PowerShell 6, functions called by classes can be mocked as above, with no known problems. +In PowerShell 6 and later functions called by classes can be mocked as above with no known problems. However previous versions of PowerShell, including **all** versions of Windows PowerShell up to 5.1 cache class definitions in such a way that they are never redefined, even if you remove the module and re-import, or modify the class. This breaks Pester's Mock command, as the scope where the mock must be injected cannot be found. -Dave Wyatt has provided this workaround: +Dave Wyatt has provided this workaround ([original source](https://github.com/pester/Pester/issues/797#issuecomment-314495326)): > Simply run your Pester tests in a fresh session every time; this is simple to do with Start-Job. I have this proxy function in my PowerShell profile to help with that: ```powershell -function Invoke-PesterJob -{ -[CmdletBinding(DefaultParameterSetName='LegacyOutputXml')] +# Updated example based on https://github.com/pester/Pester/issues/797#issuecomment-314495326 +function Invoke-PesterJob { + [CmdletBinding()] param( [Parameter(Position=0)] - [Alias('Path','relative_path')] - [System.Object[]] - ${Script}, - - [Parameter(Position=1)] - [Alias('Name')] - [string[]] - ${TestName}, - - [Parameter(Position=2)] - [switch] - ${EnableExit}, - - [Parameter(ParameterSetName='LegacyOutputXml', Position=3)] - [string] - ${OutputXml}, - - [Parameter(Position=4)] - [Alias('Tags')] - [string[]] - ${Tag}, - - [string[]] - ${ExcludeTag}, - - [switch] - ${PassThru}, - - [System.Object[]] - ${CodeCoverage}, - - [switch] - ${Strict}, - - [Parameter(ParameterSetName='NewOutputSet', Mandatory=$true)] - [string] - ${OutputFile}, - - [Parameter(ParameterSetName='NewOutputSet', Mandatory=$true)] - [ValidateSet('LegacyNUnitXml','NUnitXml')] - [string] - ${OutputFormat}, - - [switch] - ${Quiet} + [string[]] $Path = '.', + [string[]] $ExcludePath = @() + [string[]] $TagFilter, + [string[]] $ExcludeTagFilter, + [string[]] $FullNameFilter, + [switch] $EnableExit, + [switch] $PassThru ) $params = $PSBoundParameters @@ -162,8 +124,6 @@ function Invoke-PesterJob } Set-Alias ipj Invoke-PesterJob ``` -[Source](https://github.com/pester/Pester/issues/797#issuecomment-314495326) - ### Mocking a native application @@ -197,7 +157,7 @@ Describe 'Mocking native commands' { Calling a mocked command will execute a proxy-function (hook) which evaluates and chooses the correct behavior/mock to invoke in that scenario. Because of this proxy `$PSBoundParameters` will be overwritten and are not available inside your mock's scriptblock. -Starting in Pester 5.2.0, a new `$PesterBoundParameters` variable has been introduced as a replacement. Using this you can evaluate bound parameters and/or forward them to other functions inside your mock's code. +A new `$PesterBoundParameters` variable is included as a replacement. Using this you can evaluate bound parameters and/or forward them to other functions inside your mock's code. ```powershell Describe 'PesterBoundParameters' { diff --git a/docs/usage/modules.mdx b/docs/usage/modules.mdx index 7547d91b..54f38414 100644 --- a/docs/usage/modules.mdx +++ b/docs/usage/modules.mdx @@ -237,7 +237,7 @@ Describe 'Executing test code inside a dynamic module' { ### Manifest Modules -Pester 5.4 and later fully supports Manifest modules, so both `Mock` and `InModuleScope` can be used without any workarounds. For earlier versions, see workaround below. +Pester supports Manifest modules, so both `Mock` and `InModuleScope` can be used without any workarounds. For earlier versions, see workaround below. Be aware that only code in nested scripts (`*.ps1`) execute directly from the manifest module. Nested script modules (`*.psm1`) or binary modules (`*.dll`) are executed in their own module state. In the example below, mocking calls made inside `Get-HelloWorld` would require `-ModuleName MyNestedModule` because it's was defined in `MyNestedModule.psm1`. @@ -258,34 +258,6 @@ Get-HelloWorld Hello World from module: MyNestedModule ``` -:::tip Workaround for older versions of Pester -Prior to Pester 5.4, only exported members from a manifest module could be tested with Pester and the `Mock` and `InModuleScope` features were unavailable. However, by creating a empty script module with `*.psm1` extension and adding it into the `RootModule` (or `ModuleToProcess`) attribute of the manifest `*.psd1` file, the module is converted to a Script module. - -For example, save the manifest below to create a PowerShell **Manifest** module. - -```powershell title="MyModule.psd1" -@{ - ModuleVersion = '1.0' - NestedModules = @( "Invoke-PrivateManifestMethod.ps1", "Invoke-PublicManifestMethod.ps1" ) - FunctionsToExport = @( "Invoke-PublicManifestMethod" ) -} -``` - -To convert it into a **Script** module, create a new blank file called `MyModule.psm1` and modify the manifest created above as follows: - -```powershell title="MyModule.psd1" -@{ - ModuleVersion = '1.0' - # highlight-next-line - RootModule = "MyModule.psm1" - NestedModules = @( "Invoke-PrivateManifestMethod.ps1", "Invoke-PublicManifestMethod.ps1" ) - FunctionsToExport = @( "Invoke-PublicManifestMethod" ) -} -``` - -PowerShell will then load the module as a Script module and Pester's `Mock` and `InModuleScope` features will work as expected. -::: - ### Binary Modules Exported commands from a Binary module can be tested and mocked using with `Mock` for calls made in script or other modules. diff --git a/docs/usage/output.mdx b/docs/usage/output.mdx index 72b36bea..c9403603 100644 --- a/docs/usage/output.mdx +++ b/docs/usage/output.mdx @@ -19,7 +19,7 @@ This page focuses on the general options available for all users. See [VSCode](. ### Verbosity -This option controls the general level of console output. Pester v5 supports the following levels: +This option controls the general level of console output. Pester supports the following levels: - **None**: No console output is shown. Typically used in combination with `Run.PassThru / -PassThru` to do custom post-processing of the results. - **Normal (default)**: Focus on successful containers and failed tests/blocks. Shows basic discovery information and the summary of all tests.
@@ -31,7 +31,6 @@ This option controls the general level of console output. Pester v5 supports the ### StackTraceVerbosity -**New in Pester 5.3!** When an error is shown due to a failed setup or test, a stacktrace is included to help you identify where the problem occured. Users might not care much about this while developers need it to identify and fix any issues. This option lets you control how much of the stacktrace that will be printed using one of the following levels: @@ -50,7 +49,6 @@ The result-object returned from `Run.PassThru / -PassThru` includes a `ErrorReco ### CIFormat -**New in Pester 5.3!** Pester supports CI-specific output syntaxes to highlight, log and navigate to errors in your tests for a few popular CI systems. This options lets your control how this behavior should work. The following levels are currently supported: - **None**: Disable all CI-specific syntax. Error messages are presented in the format you're familiar with. @@ -78,7 +76,6 @@ Auto-detection works by checking if `GITHUB_ACTIONS` environment variable is equ ### RenderMode -**New in Pester 5.4!** Pester supports multiple render modes for console output, including ANSI escape sequences which enables colors in CI-logs. The currently supported modes are: - **Auto (default)**: Automatically enables the recommended mode using the following rules: @@ -86,9 +83,5 @@ Pester supports multiple render modes for console output, including ANSI escape - `ANSI` when a supported PowerShell host is being used. - `ConsoleColor` used as fallback. - **ANSI**: Render using ANSI escape sequences. Colors are shown in ANSI-supported console hosts, redirected output, CI-logs etc. -- **ConsoleColor**: Uses default `Write-Host` behavior. Colors are shown in console but not in CI, redirected output etc. Same mode is used prior to Pester 5.4. +- **ConsoleColor**: Uses default `Write-Host` behavior. Colors are shown in console but not in CI, redirected output etc. This mode was used prior to Pester 5.4. - **Plaintext**: Render output without colors. - -:::note Using ANSI with PowerShell 3 and 4 -ANSI support is auto-detected using the property `$host.UI.SupportsVirtualTerminal` which was introduced in PowerShell 5. If you are running PowerShell 3 or 4 in a known supported host or CI, you need to enable it explictly using `Output.RenderMode = 'Ansi'`. -::: diff --git a/docs/usage/tags.mdx b/docs/usage/tags.mdx index e95e0787..153684db 100644 --- a/docs/usage/tags.mdx +++ b/docs/usage/tags.mdx @@ -5,7 +5,7 @@ description: Use tags on tests and blocks to categorize code and easily choose w The tag parameter is now available on `Describe`, `Context` and `It` and it is possible to filter tags on any level. You can then use `-TagFilter` and `-ExcludeTagFilter` to run just the tests that you want. -Here you can see an example of a test suite that has acceptance tests and unit tests, and some of the tests are slow, some are flaky, and some only work on Linux. Pester v5 makes running all reliable acceptance tests, that can run on Windows is as simple as: +Here you can see an example of a test suite that has acceptance tests and unit tests. Some of the tests are slow, some are flaky, and some only work on Linux. Pester makes running all reliable Windows-compatible acceptance tests as simple as: ```powershell diff --git a/docs/usage/testdrive.mdx b/docs/usage/testdrive.mdx index 02484b17..b5852af8 100644 --- a/docs/usage/testdrive.mdx +++ b/docs/usage/testdrive.mdx @@ -59,7 +59,7 @@ system path to the root of the TestDrive PSDrive, rather than a PowerShell path 'TestDrive:\'. ```powershell -#eg. C:\Users\nohwnd\AppData\Local\Temp\264f1c74-464f-4387-b908-79e5eecba982\somefile.txt +#eg. C:\Users\nohwnd\AppData\Local\Temp\Pester_3ap5\somefile.txt $pathOne = Join-Path $TestDrive 'somefile.txt' $pathTwo = 'TestDrive:\somefile.txt' diff --git a/docs/usage/testregistry.mdx b/docs/usage/testregistry.mdx index b00d7595..f39e2c70 100644 --- a/docs/usage/testregistry.mdx +++ b/docs/usage/testregistry.mdx @@ -7,7 +7,7 @@ description: TestRegistry is a PowerShell PSDrive (Windows only) to help your st TestRegistry is a Windows-only PowerShell PSDrive used to isolate registry based tests. -Pester creates a temporary, randomly named (a guid), registry key in the current user's hive under `HKCU:\Software\Pester` which is accessible as `TestRegistry:`. +Pester creates a temporary, randomly named, registry key in the current user's hive under `HKCU:\Software\Pester` which is accessible as `TestRegistry:`. ## Scoping @@ -24,14 +24,17 @@ Be aware that cleanup in TestRegistry currently works on registry key-level. Val ## Example ```powershell -Function Get-InstallPath($path, $key) { - Get-ItemProperty -Path $path -Name $key | Select-Object -ExpandProperty $key +BeforeAll { + function Get-InstallPath($path, $key) { + Get-ItemProperty -Path $path -Name $key | Select-Object -ExpandProperty $key + } } Describe "Get-InstallPath" { - - New-Item -Path TestRegistry:\ -Name TestLocation - New-ItemProperty -Path "TestRegistry:\TestLocation" -Name "InstallPath" -Value "C:\Program Files\MyApplication" + BeforeAll { + New-Item -Path TestRegistry:\ -Name TestLocation + New-ItemProperty -Path "TestRegistry:\TestLocation" -Name "InstallPath" -Value "C:\Program Files\MyApplication" + } It 'reads the install path from the registry' { Get-InstallPath -Path "TestRegistry:\TestLocation" -Key "InstallPath" | Should -Be "C:\Program Files\MyApplication" diff --git a/docusaurus.config.js b/docusaurus.config.js index 914cf21b..382f0e48 100644 --- a/docusaurus.config.js +++ b/docusaurus.config.js @@ -156,13 +156,19 @@ const config = { docs: { sidebarPath: './sidebars.js', editUrl: 'https://github.com/pester/docs/edit/main', - lastVersion: "current", + // Define which version ("current" vs versioned docs like "v5") that will use unversioned URIs /docs/... + // Using v5 while it's latest stable. + // When updated, also update static/_redirects to always support versioned URIs + lastVersion: "v5", includeCurrentVersion: true, disableVersioning: false, versions: { + // "current" is content in /docs folder current: { - label: "v5", - path: "", + label: "v6 (preview) 🚧", + // path is /docs/next by default unless lastVersion is set to "current" + // overriden to /docs/v6 during preview + path: "v6" } }, }, diff --git a/generate-command-reference.ps1 b/generate-command-reference.ps1 index aaffa2e6..43798a18 100644 --- a/generate-command-reference.ps1 +++ b/generate-command-reference.ps1 @@ -16,85 +16,89 @@ #> [CmdletBinding()] param ( - [Parameter(Mandatory = $False)][string] $PesterVersion, - - [Parameter(Mandatory = $False)][string] $PlatyPSVersion, - - [Parameter(Mandatory = $False)][string] $DocusaurusVersion, - - [switch]$SkipModuleImport + [string] $PesterVersion, + [string] $PlatyPSVersion, + [string] $DocusaurusVersion, + [switch] $SkipModuleImport, + [ValidateSet('Current','v4','v5')] + [string] $DocsVersion = 'Current' ) Set-StrictMode -Version Latest -$PSDefaultParameterValues['*:ErrorAction'] = "Stop" +$PSDefaultParameterValues['*:ErrorAction'] = 'Stop' -Write-Host "Generating MDX files for website Command Reference" -BackgroundColor DarkGreen +Write-Host 'Generating MDX files for website Command Reference' -BackgroundColor DarkGreen # ----------------------------------------------------------------------------- # Install required modules # ----------------------------------------------------------------------------- $ModuleList = [ordered]@{ - 'PlatyPS' = $PlatyPSVersion - 'Alt3.Docusaurus.PowerShell' = $DocusaurusVersion - 'Pester' = $PesterVersion + 'PlatyPS' = $PlatyPSVersion + 'Alt3.Docusaurus.PowerShell' = $DocusaurusVersion + 'Pester' = $PesterVersion } # Can't use the original enumerator here because we may modify the dictionary mid-process $ModuleList.Keys.Clone() | ForEach-Object { - $ModuleName = $_ - $RequestedVersion = $ModuleList.Item($ModuleName) - Write-Host "Requires $ModuleName $RequestedVersion" - - if ([String]::IsNullOrEmpty($RequestedVersion)) { - Write-Host "=> Fetching module versions of $ModuleName from PSGallery..." - $RequestedVersion = (Find-Module -Name $ModuleName).Version - $ModuleList.Item($ModuleName) = $RequestedVersion - Write-Host "=> PSGallery version is $RequestedVersion" - } + $ModuleName = $_ + $RequestedVersion = $ModuleList.Item($ModuleName) + Write-Host "Requires $ModuleName $RequestedVersion" + + if ([String]::IsNullOrEmpty($RequestedVersion)) { + Write-Host "=> Fetching latest stable version of $ModuleName from PSGallery..." + $RequestedVersion = (Find-Module -Name $ModuleName).Version + $ModuleList.Item($ModuleName) = $RequestedVersion + Write-Host "=> PSGallery version is $RequestedVersion" + } - $Installed = Get-Module -ListAvailable $ModuleName - if ($Installed -and ($Installed.Version -contains $RequestedVersion)) { - Write-Host "=> required version already installed" - } else { - if (-not $Installed) { - Write-Host "=> no versions installed: installing $RequestedVersion" + $Installed = Get-Module -ListAvailable $ModuleName + if ($Installed -and ($Installed.Version -contains $RequestedVersion)) { + Write-Host '=> required version already installed' } else { - Write-Host "=> no matching version installed: installing $RequestedVersion" + if (-not $Installed) { + Write-Host "=> no versions installed: installing $RequestedVersion" + } else { + Write-Host "=> no matching version installed: installing $RequestedVersion" + } + Install-Module $ModuleName -RequiredVersion $RequestedVersion -AllowPrerelease -Force -SkipPublisherCheck -AllowClobber -Scope CurrentUser } - Install-Module $ModuleName -RequiredVersion $RequestedVersion -Force -SkipPublisherCheck -AllowClobber -Scope CurrentUser - } - if (-not $SkipModuleImport) { - Write-Host "=> importing" - Import-Module -Name $ModuleName -RequiredVersion $RequestedVersion -Force - } + if (-not $SkipModuleImport) { + Write-Host '=> importing' + # Import doesn't support prerelease-version. Only one x.y.z* version can be installed at any time, so just strip suffix + Import-Module -Name $ModuleName -RequiredVersion ($RequestedVersion -replace '-\w+$') -Force + } } # ----------------------------------------------------------------------------- # Use below settings to manipulate the rendered MDX files # ----------------------------------------------------------------------------- $docusaurusOptions = @{ - Module = "Pester" - DocsFolder = "./docs" - SideBar = "commands" - EditUrl = "null" # prevent the `Edit this Page` button from appearing - Exclude = @( - "Get-MockDynamicParameter" - "Invoke-Mock" - "SafeGetCommand" - "Set-DynamicParameterVariable" - ) - MetaDescription = 'Help page for the PowerShell Pester "%1" command' - MetaKeywords = @( - "PowerShell" - "Pester" - "Help" - "Documentation" - ) - PrependMarkdown = @" + Module = 'Pester' + DocsFolder = switch ($DocsVersion) { + 'Current' { "$PSScriptRoot/docs" } + 'v5' { "$PSScriptRoot/versioned_docs/version-v5" } + 'v4' { "$PSScriptRoot/versioned_docs/version-v4" } + } + SideBar = 'commands' + EditUrl = 'null' # prevent the `Edit this Page` button from appearing + Exclude = @( + 'Get-MockDynamicParameter' + 'Invoke-Mock' + 'SafeGetCommand' + 'Set-DynamicParameterVariable' + ) + MetaDescription = 'Help page for the PowerShell Pester "%1" command' + MetaKeywords = @( + 'PowerShell' + 'Pester' + 'Help' + 'Documentation' + ) + PrependMarkdown = @' :::info This page was generated Contributions are welcome in [Pester-repo](https://github.com/pester/pester). ::: -"@ - AppendMarkdown = @" +'@ + AppendMarkdown = @" ## VERSION *This page was generated using comment-based help in [Pester $($ModuleList.Pester)](https://github.com/pester/pester).* "@ @@ -106,19 +110,19 @@ Contributions are welcome in [Pester-repo](https://github.com/pester/pester). Push-Location $PSScriptRoot Write-Host (Get-Location) -Write-Host "Removing existing MDX files" -ForegroundColor Magenta -$outputFolder = Join-Path -Path $docusaurusOptions.DocsFolder -ChildPath $docusaurusOptions.Sidebar | Join-Path -ChildPath "*.*" +Write-Host 'Removing existing MDX files' -ForegroundColor Magenta +$outputFolder = Join-Path -Path $docusaurusOptions.DocsFolder -ChildPath $docusaurusOptions.Sidebar | Join-Path -ChildPath '*.*' if (Test-Path -Path $outputFolder) { - Remove-Item -Path $outputFolder + Remove-Item -Path $outputFolder } -Write-Host "Generating new MDX files" -ForegroundColor Magenta +Write-Host 'Generating new MDX files' -ForegroundColor Magenta New-DocusaurusHelp @docusaurusOptions -Write-Host "Render completed successfully" -BackgroundColor DarkGreen +Write-Host 'Render completed successfully' -BackgroundColor DarkGreen Pop-Location if ($ENV:GITHUB_ACTIONS) { - # Output Workflow information - Write-Host "::set-output name=pester-version::$($ModuleList.Item('Pester'))" + # Output Workflow information + "pester-version=$($ModuleList.Pester))" >> $env:GITHUB_OUTPUT } diff --git a/generate-pesterconfiguration-docs.ps1 b/generate-pesterconfiguration-docs.ps1 new file mode 100644 index 00000000..82ccd910 --- /dev/null +++ b/generate-pesterconfiguration-docs.ps1 @@ -0,0 +1,164 @@ +<# + .SYNOPSIS + Updates the Configuration page with latest PesterConfiguration Sections and Options +#> +[CmdletBinding()] +param ( + [Parameter(Mandatory = $False)] + [string] $PesterVersion, + [ValidateSet('Current','v5')] + [string] $DocsVersion = 'Current', + [ValidateSet('List','Table')] + [string] $Style = 'List' +) + +#region helpers +function Format-NicelyMini ($value) { + if ($value -is [bool]) { + if ($value) { + '$true' + } else { + '$false' + } + } + + if ($value -is [int] -or $value -is [decimal]) { + return $value + } + + if ($value -is [string]) { + if ([String]::IsNullOrEmpty($value)) { + return '$null' + } else { + return "'$value'" + } + } + + # does not work with [object[]] when building for some reason + if ($value -is [System.Collections.IEnumerable]) { + if (0 -eq $value.Count) { + return '@()' + } + $v = foreach ($i in $value) { + Format-NicelyMini $i + } + return "@($($v -join ', '))" + } +} + +function generateSectionsMarkdownAsTable { + $configObject = New-PesterConfiguration + foreach ($configSection in $configObject.PSObject.Properties) { + $sectionName = $configSection.Name + $sectionDescription = $configSection.Value -as [string] + $section = $configSection.Value + + $options = foreach ($configOption in $section.PSObject.Properties) { + $optionName = $configOption.Name + $option = $configOption.Value + $default = Format-NicelyMini $option.Default + $type = $option.Default.GetType() -as [string] -replace '^Pester\.' + "| $sectionName.$optionName | $($option.Description) | ``$type`` | ``$default`` |" + } + + @" +### ${sectionName} + +$sectionDescription + +
+| Option | Description | Type | Default | +|--------|-------------|-----:|--------:| +$($options -join $eol) +
+ +"@ + } +} + +function generateSectionsMarkdownAsList { + $configObject = New-PesterConfiguration + foreach ($configSection in $configObject.PSObject.Properties) { + $sectionName = $configSection.Name + $sectionDescription = $configSection.Value -as [string] + $section = $configSection.Value + + $options = foreach ($configOption in $section.PSObject.Properties) { + $optionName = $configOption.Name + $option = $configOption.Value + $default = Format-NicelyMini $option.Default + $type = $option.Default.GetType() -as [string] + @" +#### $sectionName.$optionName + +**Type:** ``$type``
+**Default:** ``$default`` + +$($option.Description) + +"@ + } + + # Output markdown string per section + @" +### ${sectionName} + +$sectionDescription + +$($options -join $eol) +"@ + } +} +#endregion + +$loadedModule = if ($PSBoundParameters.ContainsKey('PesterVersion')) { + Import-Module Pester -RequiredVersion ($PesterVersion -replace '-\w+$') -PassThru +} else { + Import-Module Pester -PassThru +} + +$loadedVersion = if ($loadedModule.PrivateData -and $loadedModule.PrivateData.PSData -and $loadedModule.PrivateData.PSData.PreRelease) { + "$($loadedModule.Version)-$($loadedModule.PrivateData.PSData.PreRelease)" +} else { + $loadedModule.Version +} + +if ($PSBoundParameters.ContainsKey('PesterVersion') -and $loadedVersion -ne $PesterVersion) { + throw "Pester $PesterVersion was requested, but version '$loadedVersion' was loaded. Aborting." +} + +# generate help for config object and insert it +$startComment = 'GENERATED_PESTER_CONFIGURATION_DOCS_START' +$endComment = 'GENERATED_PESTER_CONFIGURATION_DOCS_END' +$eol = "`n" +$encoding = 'UTF8' + +$ConfigurationPagePath = switch ($DocsVersion) { + 'Current' { "$PSScriptRoot/docs/usage/configuration.mdx" } + 'v5' { "$PSScriptRoot/versioned_docs/version-v5/usage/configuration.mdx" } +} + +$generatedConfigDocs = switch ($Style) { + 'List' { generateSectionsMarkdownAsList } + 'Table' { generateSectionsMarkdownAsTable } +} + +$pageContent = Get-Content $ConfigurationPagePath -Encoding $encoding +$sbf = [System.Text.StringBuilder]'' +$sectionFound = $false + +foreach ($line in $pageContent) { + if (-not $sectionFound -and $line -match $startComment) { + $null = $sbf.AppendLine("$line$eol") + $null = $sbf.AppendLine("*This section was generated using Pester $loadedVersion.*$eol") + $sectionFound = $true + $null = $sbf.AppendJoin($eol, $generatedConfigDocs) + } elseif ($sectionFound -and ($line -match $endComment)) { + $sectionFound = $false + } + if (-not $sectionFound) { + $null = $sbf.AppendLine($line) + } +} + +Set-Content -Encoding $encoding -Value $sbf.ToString().TrimEnd() -Path $ConfigurationPagePath diff --git a/sidebars.js b/sidebars.js index b2303dfa..02c56cff 100644 --- a/sidebars.js +++ b/sidebars.js @@ -54,6 +54,7 @@ module.exports = { "assertions/custom-assertions", ], "Migration Guides": [ + "migrations/v5-to-v6", "migrations/v4-to-v5", "migrations/breaking-changes-in-v5", "migrations/v3-to-v4", diff --git a/static/_redirects b/static/_redirects index e101e5aa..f77cb5fa 100644 --- a/static/_redirects +++ b/static/_redirects @@ -2,3 +2,6 @@ /issues https://github.com/pester/pester/issues/new/choose /issues/docs https://github.com/pester/docs/issues/new/choose /releases/:v https://github.com/pester/pester/releases/tag/:v + +# Redirect versioned URLs for latest (e.g. /docs/v5 -> /docs) +/docs/v5/* /docs/:splat 302 diff --git a/versioned_docs/version-v5/additional-resources/articles.mdx b/versioned_docs/version-v5/additional-resources/articles.mdx new file mode 100644 index 00000000..f13ded06 --- /dev/null +++ b/versioned_docs/version-v5/additional-resources/articles.mdx @@ -0,0 +1,20 @@ +--- +id: articles +title: Articles +sidebar_label: Articles +custom_edit_url: null +description: Published articles about using Pester for testing PowerShell code, infrastructure and more +--- + +import { PesterDataTable, PesterDataButton } from "@site/src/components/PesterDataTable"; +import { columns, articles, moduleTests } from "./articles.table"; + + + + diff --git a/versioned_docs/version-v5/additional-resources/articles.table.js b/versioned_docs/version-v5/additional-resources/articles.table.js new file mode 100644 index 00000000..83287a1f --- /dev/null +++ b/versioned_docs/version-v5/additional-resources/articles.table.js @@ -0,0 +1,427 @@ +import React from "react"; + +// ---------------------------------------------------------------------------- +// Please respect chronological (date) order when adding new entries. +// ---------------------------------------------------------------------------- +export const articles = [ + { + title: "Adding a code coverage badge to a PowerShell project", + author: "Mark Wragg", + date: "2018-05-14", + url: "http://wragg.io/add-a-code-coverage-badge-to-your-powershell-deployment-pipeline/", + }, + { + title: "Azure Security Audits With Pester", + author: "Sam Cogan", + date: "2017-12-20", + url: "https://samcogan.com/azure-security-audits-with-pester", + }, + { + title: "Handling Missing Instances when Looping with Pester", + author: "Rob Sewell", + date: "2017-11-30", + url: "https://sqldbawithabeard.com/2017/11/30/handling-missing-instances-when-looping-with-pester/", + }, + { + title: "2 Ways to Loop through collections in Pester", + author: "Rob Sewell", + date: "2017-11-28", + url: "https://sqldbawithabeard.com/2017/11/28/2-ways-to-loop-through-collections-in-pester/", + }, + { + title: "Building An Infrastructure Pipeline Part 2 - Testing", + author: "Sam Cogan", + date: "2017-11-27", + url: "https://samcogan.com/building-an-infrastructure-pipeline-part-2/", + }, + { + title: "Writing and Using Custom Assertions for Pester Tests", + author: "Mathieu Buisson", + date: "2017-10-31", + url: "https://mathieubuisson.github.io/pester-custom-assertions/", + }, + { + title: "Getting Started with Pester", + author: "Josh Duffney", + date: "2017-08-23", + url: "http://duffney.io/GettingStartedWithPester", + }, + { + title: "Writing Dynamic and Random Tests Cases for Pester", + author: "Rob Sewell", + date: "2017-07-06", + url: "https://sqldbawithabeard.com/2017/07/06/writing-dynamic-and-random-tests-cases-for-pester/", + }, + { + title: "Unit Testing with Pester : Storing complex Mock objects in a JSON file", + author: "Mathieu Buisson", + date: "2017-02-14", + url: "https://mathieubuisson.github.io/storing-mock-objects-in-json/", + }, + { + title: "Mocking New-Object in Pester with PowerShell classes", + author: "Ben Taylor", + date: "2017-01-10", + url: "https://bentaylor.work/2017/01/mocking-new-object-in-pester-with-powershell-classes/", + }, + { + title: "Writing Pester Tests", + author: "PowerShell Community", + date: "2016-11-07", + url: "https://github.com/PowerShell/PowerShell/blob/master/docs/testing-guidelines/WritingPesterTests.md", + }, + { + title: "Functional / Non-Functional Pester Tests and why I think you really should have a form of both.", + author: "Ryan Yates", + date: "2016-07-21", + url: + "http://blog.kilasuit.org/2016/07/21/functional-non-functional-pester-tests-and-why-i-think-you-really-should-have-a-form-of-both/", + }, + { + title: "Unit tests versus integration tests in Pester", + author: "Adam Bertram", + date: "2016-07-21", + url: "https://4sysops.com/archives/unit-tests-versus-integration-tests-in-pester/#integration-tests", + }, + { + title: "A Boilerplate for Unit testing DSC resources with Pester", + author: "Mathieu Buisson", + date: "2016-07-12", + url: "https://mathieubuisson.github.io/unit-testing-dsc-resources/", + }, + { + title: "Pester, Jenkins, Remote & ExitCode", + author: "Fabien Dibot", + date: "2016-07-02", + url: "https://pwrshell.net/pester-jenkins-remote-exitcode/", + }, + { + title: "Using Visual Studio Code to develop VSTS Build Tasks with PowerShell and Pester tests", + author: "Richard Fennell", + date: "2016-06-27", + url: + "http://blogs.blackmarble.co.uk/blogs/rfennell/post/2016/06/21/Using-Visual-Studio-Code-to-develop-VSTS-Build-Tasks-with-PowerShell-and-Pester-tests", + }, + { + title: "Visualizing Operational Tests with Jenkins and Pester", + author: "Bill Hurt", + date: "2016-06-25", + url: "https://scripting.tech/2016/06/25/visualizing-operational-tests-with-jenkins-and-pester/", + }, + { + title: "Testing Pester Code Coverage", + author: "June Blender", + date: "2016-06-24", + url: "https://www.sapien.com/blog/2016/06/24/testing-pester-code-coverage/", + }, + { + title: "The Pester Pipeline", + author: "Christopher Hunt", + date: "2016-06-21", + url: "https://www.automatedops.com/blog/2016/06/21/the-pester-pipeline/", + }, + { + title: "How to Pass Parameters to a Pester Test Script", + author: "June Blender", + date: "2016-06-17", + url: "https://www.sapien.com/blog/2016/06/17/how-to-pass-parameters-to-a-pester-test-script/", + }, + + { + title: "Remediating vSphere Configuration Drift with PowerShell Pester Tests", + author: "Chris Wahl", + date: "2016-06-17", + url: "http://wahlnetwork.com/2016/06/16/remediating-vsphere-configuration-drift-powershell-pester-tests/", + }, + { + title: "Generic Pester Tests", + author: "Nicholas M. Getchell", + date: "2016-06-16", + url: "https://powershell.getchell.org/2016/05/16/generic-pester-tests/", + }, + { + title: "Invoke-Pester: Running Selected Tests", + author: "June Blender", + date: "2016-06-15", + url: "https://www.sapien.com/blog/2016/06/15/invoke-pester-run-selected-tests", + }, + { + title: "How to Run a Pester Test", + author: "June Blender", + date: "2016-06-13", + url: "https://www.sapien.com/blog/2016/06/13/how-to-run-a-pester-test", + }, + { + title: "Testing Active Directory with Pester and Powershell", + author: "Mark Wragg", + date: "2016-06-13", + url: "http://wragg.io/testing-active-directory-with-pester-and-powershell/", + }, + { + title: "Active Directory ReportUnit Pester results", + author: "Irwin Strachan", + date: "2016-06-10", + url: "https://pshirwin.wordpress.com/2016/06/10/active-directory-reportunit-pester-results/", + }, + + { + title: "A different pitch for Pester", + author: "James O'Neill", + date: "2016-06-01", + url: "https://jamesone111.wordpress.com/2016/06/01/a-different-pitch-for-pester/", + }, + { + title: "Help = Spec = Test", + author: "James O'Neill", + date: "2016-05-31", + url: "https://jamesone111.wordpress.com/2016/05/31/help-spec-test/", + }, + { + title: "Writing #Pester based Unit Tests for #PowerShell Remoting", + author: "Nicholas Dille", + date: "2016-05-30", + url: "http://dille.name/blog/2016/05/30/writing-pester-based-unit-tests-for-powershell-remoting/", + }, + { + title: "PowerShell – Pester and Invoke-ScriptAnalyzer", + author: "Ben Taylor", + date: "2016-05-27", + url: "http://bentaylor.work/2016/05/powershell-pester-and-invoke-scriptanalyzer/", + }, + { + title: + "Creating a set of simple Pester Tests for existing or old PowerShell Modules & making them easier to update in future.", + author: "Ryan Yates", + date: "2016-05-24", + url: + "http://blog.kilasuit.org/2016/05/24/creating-a-set-of-simple-pester-tests-for-existing-or-old-powershell-modules-making-them-easier-to-update-in-future", + }, + { + title: "PowerShell Pester assertions – Testing with the should command", + author: "Adam Bertram", + date: "2016-05-24", + url: "https://4sysops.com/archives/powershell-pester-assertions-testing-with-the-should-command", + }, + { + title: "How To Test PowerShell Modules with Pester", + author: "Adam Bertram", + date: "2016-05-19", + url: "http://mattmcnabb.github.io/Pester-For-PowerShell-Gallery", + }, + { + title: "Download Free Pester Cheat Sheet", + author: "Kaj Bonfils", + date: "2016-05-18", + url: "https://kajbonfils.com/2016/05/download-free-pester-cheat-sheet/", + }, + { + title: "Testing Your Module Manifest With Pester - Revisited", + author: "Matt McNabb", + date: "2016-05-18", + url: "http://mattmcnabb.github.io/Pester-For-PowerShell-Gallery", + }, + { + title: "Using Pester to test your Manifest File", + author: "Francois-Xavier Cat", + date: "2016-05-11", + url: "http://www.lazywinadmin.com/2016/05/using-pester-to-test-your-manifest-file.html", + }, + { + title: "Using Pester to test your Comment Based Help", + author: "Francois-Xavier Cat", + date: "2016-05-10", + url: "http://www.lazywinadmin.com/2016/05/using-pester-to-test-your-comment-based.html", + }, + { + title: "Mocking SQL Results in Pester", + author: "Nick Hudacin", + date: "2016-04-28", + url: "https://nickhudacin.wordpress.com/2016/04/28/mocking-sql-results-in-pester/", + }, + { + title: "Constructing Private Test Credentials for Pester Testing", + author: "Chris Wahl", + date: "2016-04-27", + url: "http://wahlnetwork.com/2016/04/27/private-test-credentials-pester-testing/", + }, + { + title: "Write Dynamic Unit Tests for your PowerShell Code with Pester", + author: "Mike F Robbins", + date: "2016-04-14", + url: "http://mikefrobbins.com/2016/04/14/write-dynamic-unit-tests-for-your-powershell-code-with-pester", + }, + { + title: "Building a Simple Release Pipeline in PowerShell Using psake, Pester, and PSDeploy", + author: "Brandon Olin", + date: "2016-04-06", + url: "https://devblackops.io/building-a-simple-release-pipeline-in-powershell-using-psake-pester-and-psdeploy/", + }, + { + title: "Invoking PSScriptAnalyzer in Pester Tests for each Rule", + author: "Ryan Yates", + date: "2016-03-29", + url: "http://blog.kilasuit.org/2016/03/29/invoking-psscriptanalyzer-in-pester-tests-for-each-rule/", + }, + { + title: "An Easier Way to Control Pester Tests", + author: "Adam Bertram", + date: "2016-03-24", + url: "http://www.adamtheautomator.com/easier-way-control-pester-tests", + }, + { + title: "Testing Script Modules with Pester", + author: "Dave Wyatt", + date: "2015-12-17", + url: "https://blogs.technet.microsoft.com/heyscriptingguy/2015/12/17/testing-script-modules-with-pester", + }, + { + title: "Testing Script Modules with Pester - series", + author: "Dave Wyatt", + date: "2015-12-14", + url: "https://blogs.technet.microsoft.com/heyscriptingguy/2015/12/14/what-is-pester-and-why-should-i-care", + }, + { + title: "Pester Explained: Describe, Context, and It Blocks", + author: "Jakub Jares", + date: "2015-12-03", + url: "http://www.powershellmagazine.com/2015/12/03/pester-explained-describe-context-and-it-blocks/", + }, + { + title: "Pester Explained: Should", + author: "Jakub Jares", + date: "2015-12-02", + url: "http://www.powershellmagazine.com/2015/12/02/pester-explained-should/", + }, + { + title: "Pester Explained: Introduction and Assertions", + author: "Jakub Jares", + date: "2015-12-01", + url: "http://www.powershellmagazine.com/2015/12/01/pester-explained-introduction-and-assertions/", + }, + { + title: "Comparing Objects using JSON in PowerShell for Pester Tests", + author: "Daniel Scott-Raynsford", + date: "2015-08-23", + url: + "https://dscottraynsford.wordpress.com/2015/08/23/comparing-objects-using-json-in-powershell-for-pester-tests/", + }, + { + title: "Pester: Triangulation and reusing test cases", + author: "Jakub Jares", + date: "2015-06-04", + url: "http://www.powershellmagazine.com/2015/06/04/pester-triangulation-and-reusing-test-cases/", + }, + { + title: "Boost your productivity with Pester snippets", + author: "Jakub Jares", + date: "2015-01-13", + url: "http://www.powershellmagazine.com/2015/01/13/boost-your-productivity-with-pester-snippets/", + }, + { + title: "Build your Azure lab with DSC and validate it using Pester – 2/3", + author: "Fabien Dibot", + date: "2015-01-04", + url: "https://pwrshell.net/build-your-azure-lab-with-dsc-and-validate-it-using-pester-23/", + }, + { + title: "Build your Azure lab with DSC and validate it using Pester – 1/3", + author: "Fabien Dibot", + date: "2014-12-27", + url: "https://pwrshell.net/build-your-azure-lab-with-dsc-and-validate-it-using-pester-13/", + }, + { + title: "Create your first Pester script to test a DSC resource", + author: "Fabien Dibot", + date: "2014-11-30", + url: "https://pwrshell.net/create-your-first-pester-script-to-test-a-dsc-resource/", + }, + { + title: "Practical PowerShell Unit-Testing: Checking program flow", + author: "Michael Sorens", + date: "2014-11-05", + url: "https://www.simple-talk.com/sysadmin/powershell/practical-powershell-unit-testing-checking-program-flow", + }, + { + title: "Practical PowerShell Unit-Testing: Mock Objects", + author: "Michael Sorens", + date: "2014-11-04", + url: "https://www.simple-talk.com/sysadmin/powershell/practical-powershell-unit-testing-mock-objects", + }, + { + title: "Practical PowerShell Unit-Testing: Getting Started", + author: "Michael Sorens", + date: "2014-11-03", + url: "https://www.simple-talk.com/sysadmin/powershell/practical-powershell-unit-testing-getting-started", + }, + { + title: + "Configure and test windows infrastructure using Powershell technologies DSC and Pester running from Chef and Test-Kitchen", + author: "Matt Wrock", + date: "2014-10-13", + url: + "http://www.hurryupandwait.io/blog/configure-and-test-windows-infrastructure-using-powershell-technologies-dsc-and-pester-running-from-chef-and-test-kitchen", + }, + { + title: "Pester Mock and TestDrive", + author: "Jakub Jares", + date: "2014-09-30", + url: "http://www.powershellmagazine.com/2014/09/30/pester-mock-and-testdrive/", + }, + { + title: "Growing an Open Source Project: The Pester Story", + author: "Scott Muc", + date: "2014-08-07", + url: "http://scottmuc.com/growing-an-open-source-project-the-pester-story/", + }, + { + title: "Testing your PowerShell scripts with Pester: Assertions and more", + author: "Jakub Jares", + date: "2014-03-27", + url: + "http://www.powershellmagazine.com/2014/03/27/testing-your-powershell-scripts-with-pester-assertions-and-more/", + }, + { + title: "Get started with Pester (PowerShell unit testing framework", + author: "Jakub Jares", + date: "2014-03-12", + url: "http://www.powershellmagazine.com/2014/03/12/get-started-with-pester-powershell-unit-testing-framework/", + }, + { + title: "PowerShell BDD Testing - Pester Screencast", + author: "Scott Muc", + date: "2011-08-25", + url: "http://scottmuc.com/blog/development/powershell-bdd-testing-pester-screencast/", + }, + { + title: "Pester - PowerShell BDD Style Testing for the System Administrator", + author: "Scott Muc", + date: "2011-03-11", + url: "http://scottmuc.com/blog/development/pester-bdd-for-the-system-administrator/", + }, +]; + +// ---------------------------------------------------------------------------- +// PesterDataTable column definition +// ---------------------------------------------------------------------------- +export const columns = [ + { + header: "Title", + accessorKey: "title", + className: "pester-data-table left", + cell: ({ cell, row: { original } }) => ( + + {cell.getValue()} + + ), + }, + { + header: "Author", + accessorKey: "author", + className: "pester-data-table left", + }, + { + header: "Date", + accessorKey: "date", + className: "pester-data-table nowrap", + }, +]; diff --git a/versioned_docs/version-v5/additional-resources/courses.mdx b/versioned_docs/version-v5/additional-resources/courses.mdx new file mode 100644 index 00000000..51a2e9e7 --- /dev/null +++ b/versioned_docs/version-v5/additional-resources/courses.mdx @@ -0,0 +1,20 @@ +--- +id: courses +title: Courses +sidebar_label: Courses +custom_edit_url: null +description: List of known courses about learning and using Pester for testing PowerShell +--- + +import { PesterDataTable, PesterDataButton } from "@site/src/components/PesterDataTable"; +import { columns, courses } from "./courses.table"; + + + + diff --git a/versioned_docs/version-v5/additional-resources/courses.table.js b/versioned_docs/version-v5/additional-resources/courses.table.js new file mode 100644 index 00000000..b5069ccb --- /dev/null +++ b/versioned_docs/version-v5/additional-resources/courses.table.js @@ -0,0 +1,38 @@ +import React from "react"; + +// ---------------------------------------------------------------------------- +// Please respect alphabetical (title) order when adding new entries. +// ---------------------------------------------------------------------------- +export const courses = [ + { + title: "Testing PowerShell with Pester", + author: "Ashley McGlone, Adam Bertram", + url: "https://mva.microsoft.com/en-US/training-courses/17650?l=mg8oBM9vD_8811787177", + }, + { + title: "PSKoans - A simple, fun, and interactive way to learn the PowerShell language through Pester unit testing", + author: "Joel Sallow and a Community", + url: "https://github.com/vexx32/PSKoans", + }, +]; + +// ---------------------------------------------------------------------------- +// PesterDataTable column definition +// ---------------------------------------------------------------------------- +export const columns = [ + { + header: "Title", + accessorKey: "title", + className: "pester-data-table left", + cell: ({ cell, row: { original } }) => ( + + {cell.getValue()} + + ), + }, + { + header: "Author", + accessorKey: "author", + className: "pester-data-table left", + }, +]; diff --git a/versioned_docs/version-v5/additional-resources/misc.mdx b/versioned_docs/version-v5/additional-resources/misc.mdx new file mode 100644 index 00000000..f0d8c5f9 --- /dev/null +++ b/versioned_docs/version-v5/additional-resources/misc.mdx @@ -0,0 +1,38 @@ +--- +id: misc +title: Miscellaneous +sidebar_label: Misc +custom_edit_url: null +description: Integrations, books and other resources about using Pester +--- + +import { PesterDataTable, PesterDataButton } from "@site/src/components/PesterDataTable"; +import { columns, integrations, books } from "./misc.table"; + +## Integrations + + + +## Paid resources + +### Books + + + +## TBD + +Waiting to be re-read and added + +- [mikefrobbins.com](http://mikefrobbins.com/?s=pester) +- [powershell.org](https://powershell.org) + + diff --git a/versioned_docs/version-v5/additional-resources/misc.table.js b/versioned_docs/version-v5/additional-resources/misc.table.js new file mode 100644 index 00000000..a52af9cb --- /dev/null +++ b/versioned_docs/version-v5/additional-resources/misc.table.js @@ -0,0 +1,51 @@ +import React from "react"; + +// ---------------------------------------------------------------------------- +// Please respect chronological (date) order when adding new integrations. +// ---------------------------------------------------------------------------- +export const integrations = [ + { + title: "VSCode snippets for Pester", + author: "Adam Bertram", + date: "2017-03-07", + url: "https://forums.powershell.org/t/vscode-snippets-for-pester/8195", + }, +]; + +// ---------------------------------------------------------------------------- +// Please respect chronological (date) order when adding new books. +// ---------------------------------------------------------------------------- +export const books = [ + { + title: "The Pester Book", + author: "Adam Bertram", + date: "2017-08-01", + url: "http://www.leanpub.com/pesterbook", + }, +]; + +// ---------------------------------------------------------------------------- +// PesterDataTable column definition +// ---------------------------------------------------------------------------- +export const columns = [ + { + header: "Title", + accessorKey: "title", + className: "pester-data-table left", + cell: ({ cell, row: { original } }) => ( + + {cell.getValue()} + + ), + }, + { + header: "Author", + accessorKey: "author", + className: "pester-data-table left", + }, + { + header: "Date", + accessorKey: "date", + className: "pester-data-table nowrap", + }, +]; diff --git a/versioned_docs/version-v5/additional-resources/projects.mdx b/versioned_docs/version-v5/additional-resources/projects.mdx new file mode 100644 index 00000000..1ba1690c --- /dev/null +++ b/versioned_docs/version-v5/additional-resources/projects.mdx @@ -0,0 +1,24 @@ +--- +id: projects +title: Projects +sidebar_label: Projects +custom_edit_url: null +description: List of third-party modules and projects that extend or compliment Pester +--- + +import { PesterDataTable, PesterDataButton } from "@site/src/components/PesterDataTable"; +import { columns, projects } from "./projects.table"; + + + +:::note Compatibility +Many projects above were designed for earlier versions of Pester and might not yet be updated to support Pester v5. +::: + + diff --git a/versioned_docs/version-v5/additional-resources/projects.table.js b/versioned_docs/version-v5/additional-resources/projects.table.js new file mode 100644 index 00000000..7cb6ef7e --- /dev/null +++ b/versioned_docs/version-v5/additional-resources/projects.table.js @@ -0,0 +1,93 @@ +import React from "react"; + +// ---------------------------------------------------------------------------- +// Please respect alphabetical (title) order when adding new entries. +// ---------------------------------------------------------------------------- +export const projects = [ + { + title: "Assert", + author: "Jakub Jares", + url: "https://github.com/nohwnd/Assert", + }, + { + title: "Format-Pester", + author: "Erwan Quelin", + url: "https://github.com/equelin/Format-Pester", + }, + { + title: "PesterHelpers", + author: "Ryan Yates", + url: "https://github.com/PowerShellModules/PesterHelpers", + }, + { + title: "PowershellGuard", + author: "Steven Murawski", + url: "https://github.com/smurawski/PowerShellGuard", + }, + { + title: "PesterOperationsTest", + author: "Tore Groneng", + url: "https://github.com/torgro/PesterOperationTest", + }, + { + title: "PestWatch", + author: "Ed Elliott", + url: "https://github.com/GOEddie/PestWatch", + }, + { + title: "PoshSpec", + author: "Chris Hunt", + url: "https://github.com/Ticketmaster/poshspec", + }, + { + title: "PowerShell Pester Dashboard Kickstarter", + author: "Josh Castillo", + url: "https://github.com/doesitscript/PSPesterDashboardKickstarter/tree/develop", + }, + { + title: "PesterMatchArray", + author: "Stuart Leeks", + url: "https://github.com/stuartleeks/PesterMatchArray", + }, + { + title: "PesterMatchHashtable", + author: "Stuart Leeks", + url: "https://github.com/stuartleeks/PesterMatchHashtable", + }, + { + title: "Remotely", + author: "Ravikanth Chaganti", + url: "https://github.com/rchaganti/Remotely", + }, + { + title: "Vester", + author: "Chris Wahl", + url: "https://github.com/WahlNetwork/Vester", + }, + { + title: "Watchmen", + author: "Brandon Olin", + url: "https://github.com/devblackops/watchmen", + }, +]; + +// ---------------------------------------------------------------------------- +// PesterDataTable column definition +// ---------------------------------------------------------------------------- +export const columns = [ + { + header: "Title", + accessorKey: "title", + className: "pester-data-table left", + cell: ({ cell, row: { original } }) => ( + + {cell.getValue()} + + ), + }, + { + header: "Author", + accessorKey: "author", + className: "pester-data-table left", + }, +]; diff --git a/versioned_docs/version-v5/additional-resources/videos.mdx b/versioned_docs/version-v5/additional-resources/videos.mdx new file mode 100644 index 00000000..4ecbce6b --- /dev/null +++ b/versioned_docs/version-v5/additional-resources/videos.mdx @@ -0,0 +1,20 @@ +--- +id: videos +title: Videos +sidebar_label: Videos +custom_edit_url: null +description: List of videos about using Pester and PowerShell testing provided by the community +--- + +import { PesterDataTable, PesterDataButton } from "@site/src/components/PesterDataTable"; +import { columns, videos } from "./videos.table"; + + + + diff --git a/versioned_docs/version-v5/additional-resources/videos.table.js b/versioned_docs/version-v5/additional-resources/videos.table.js new file mode 100644 index 00000000..a91f1140 --- /dev/null +++ b/versioned_docs/version-v5/additional-resources/videos.table.js @@ -0,0 +1,87 @@ +import React from "react"; + +// ---------------------------------------------------------------------------- +// Please respect chronological (date) order when adding new entries. +// ---------------------------------------------------------------------------- +export const videos = [ + { + title: "Custom Pester assertions are the vocabulary of your tests", + author: "Jakub Jares", + date: "2019-07-19", + url: "https://www.youtube.com/watch?v=WYw23cGoKco", + }, + { + title: "Beyond Pester 102: Acceptance testing with PowerShell", + author: "Glenn Sarti", + date: "2019-05-18", + url: "https://www.youtube.com/watch?v=L-1nXtaQ6YM", + }, + { + title: "Mastering PowerShell testing with Pester", + author: "Mark Wragg", + date: "2018-10-10", + url: "https://www.youtube.com/watch?v=BbOiQCgDDR8", + }, + { + title: "Beyond Pester 101: Applying testing principles to PowerShell", + author: "Glenn Sarti", + date: "2018-05-03", + url: "https://www.youtube.com/watch?v=NrUxgSaFvtk", + }, + { + title: "Introduction to testing with Pester", + author: "Jakub Jares", + date: "2017-04-08", + url: "https://www.youtube.com/watch?v=F3oOk0BC9B4", + }, + { + title: "Testing PowerShell with Pester", + author: "Robert Cain", + date: "2016-06-18", + url: "https://www.pluralsight.com/courses/powershell-testing-pester", + }, + { + title: "Pester the Tester PowerShell Bugs Beware", + author: "Robert Cain", + date: "2016-06-14", + url: "https://www.youtube.com/watch?v=o4ihc7atwYQ", + }, + { + title: "Test-Driven Development with Pester", + author: "June Blender", + date: "2016-05-21", + url: "https://www.youtube.com/watch?v=gssAtCeMOoo", + }, + { + title: "Pester in Action - series", + author: "Kevin Marquett", + date: "2015-11-11", + url: "https://www.youtube.com/playlist?list=PLOcTmsj9WHDo2_FfKePLaq_mJTcnW_fEJ", + }, +]; + +// ---------------------------------------------------------------------------- +// PesterDataTable column definition +// ---------------------------------------------------------------------------- +export const columns = [ + { + header: "Title", + accessorKey: "title", + className: "pester-data-table left", + cell: ({ cell, row: { original } }) => ( + + {cell.getValue()} + + ), + }, + { + header: "Author", + accessorKey: "author", + className: "pester-data-table left", + }, + { + header: "Date", + accessorKey: "date", + className: "pester-data-table nowrap", + }, +]; diff --git a/versioned_docs/version-v5/assertions/assertions.mdx b/versioned_docs/version-v5/assertions/assertions.mdx new file mode 100644 index 00000000..2c67cb75 --- /dev/null +++ b/versioned_docs/version-v5/assertions/assertions.mdx @@ -0,0 +1,392 @@ +--- +id: assertions +title: Assertion Reference +description: Introduction to the built-in assertion operators in Pester to get you started with the most common scenarios +--- + +`Should` is a command that provides assertion convenience methods for comparing objects and throwing test failures when test expectations fail. `Should` is used inside `It` blocks of a Pester test script. + +## Common parameters + +### Negative Assertions + +When reviewing the operators listed below, keep in mind that all of them can be negated by putting the word "Not" between "Should" and the operator. For example: + +```powershell +$true | Should -Be $true +$true | Should -Not -Be $false +``` + +### Because + +Lets you to add an optional message to the default test error message to tell the user why the test should pass. Example using `Get-Planet` from [Quick Start](../quick-start#creating-a-pester-test): + +```powershell +$mPlanets = Get-Planet -Name M* +$mPlanets.Name + @('Earth') | Should -Be 'Mercury','Mars' -Because 'those are the only two planets starting with M' +# OUTPUT +# Expected @('Mercury', 'Mars'), because those are the only two planets starting with M, but got @('Mercury', 'Mars', 'Earth'). +``` + +## Should Operators + +You can find a list of all operators included in Pester below. You may also use [Get-ShouldOperator](../commands/Get-ShouldOperator) to list the available operators, their aliases and help inside PowerShell. + +You may also create custom operators to support more complex assertions, see [Custom Assertions](./custom-assertions). + +### Be + +Compares one object with another for equality and throws if the two objects are not the same. This comparison is not case sensitive. + +```powershell +$actual="Actual value" +$actual | Should -Be "actual value" # Test will pass +$actual | Should -Be "not actual value" # Test will fail +``` + +Also compares an entire array for equality and throws if the array is not the same. + +```powershell +$array = @(1, 2, 3, 4, 'I am a string', (New-Object psobject -Property @{ IAm = 'An Object' })) +$array | Should -Be $array # Test will pass + +$string = 'I am a string' +$array = @(1, 2, 3, 4, $string) +$arrayWithCaps = @(1, 2, 3, 4, $string.ToUpper()) +$array | Should -Be $arrayWithCaps # Test will pass +``` + +Comparisons will fail if the arrays have the same values, but not the same order. + +```powershell +[int32[]]$array = (1..10) +$arrayoutoforder = (1,10,2,3,4,5,6,7,8,9) +$array | Should -Be $arrayOutOfOrder # Test will fail +``` + +### BeExactly + +Compares one object with another for equality and throws if the two objects are not the same. This comparison is case sensitive. + +```powershell +$actual="Actual value" +$actual | Should -BeExactly "Actual value" # Test will pass +$actual | Should -BeExactly "actual value" # Test will fail +``` + +### BeFalse + +Asserts that the value is false, or falsy. + +```powershell +$false | Should -BeFalse +0 | Should -BeFalse +$null | Should -BeFalse +``` + +### BeGreaterOrEqual + +Asserts that a number (or other comparable value) is greater than or equal to an expected value. Uses PowerShell's -ge operator to compare the two values. + +```powershell +2 | Should -BeGreaterOrEqual 0 +2 | Should -BeGreaterOrEqual 2 +``` + +### BeGreaterThan + +Asserts that a number is greater than an expected value. Uses PowerShell's -gt operator to compare the two values. + +```powershell +$Error.Count | Should -BeGreaterThan 0 +[version]'2.3.4.5' | Should -BeGreaterThan ([version]'1.0.0.1') +(Get-Date).AddMinutes(5) | Should -BeGreaterThan (Get-Date) +``` + +### BeIn + +Asserts that the actual value is present in the array/collection + +```powershell +'b' | Should -BeIn @('a','b','c') +27 | Should -BeIn (1..100) +``` + +### BeLessOrEqual + +Asserts that a number (or other comparable value) is lower than, or equal to an expected value. Uses PowerShell's -le operator to compare the two values. + +```powershell +1 | Should -BeLessOrEqual 10 +10 | Should -BeLessOrEqual 10 +``` + +### BeLessThan + +Asserts that a number is less than an expected value. Uses PowerShell's -lt operator to compare the two values. + +```powershell +$Error.Count | Should -BeLessThan 1 +``` + +### BeLike + +Asserts that the actual value matches a wildcard pattern using PowerShell's -like operator. This comparison is not case-sensitive. + +```powershell +$actual="Actual value" +$actual | Should -BeLike "actual *" # Test will pass +$actual | Should -BeLike "not actual *" # Test will fail +``` + +### BeLikeExactly + +Asserts that the actual value matches a wildcard pattern using PowerShell's -clike operator. This comparison is case-sensitive. + +```powershell +$actual="Actual value" +$actual | Should -BeLikeExactly "Actual *" # Test will pass +$actual | Should -BeLikeExactly "actual *" # Test will fail +``` + +### BeNullOrEmpty + +Checks values for null or empty (strings). The static [String]::IsNullOrEmpty() method is used to do the comparison. + +```powershell +$null | Should -BeNullOrEmpty # Test will pass +@() | Should -BeNullOrEmpty # Test will pass +"" | Should -BeNullOrEmpty # Test will pass + +$null | Should -Not -BeNullOrEmpty # Test will fail +``` + +### BeOfType + +Asserts that the actual value should be an object of a specified type (or a subclass of the specified type) using PowerShell's -is operator: + +```powershell +$actual = Get-Item $env:SystemRoot +$actual | Should -BeOfType System.IO.DirectoryInfo # Test will pass; object is a DirectoryInfo +$actual | Should -BeOfType System.IO.FileSystemInfo # Test will pass; DirectoryInfo base class is FileSystemInfo + +$actual | Should -BeOfType System.IO.FileInfo # Test will fail; FileInfo is not a base class of DirectoryInfo +``` + +:::note + +This currently only works for .NET types. For custom type name, added using PSTypeNames, you need to use `$MyClass.GetType().Name | Should -Be "MyClassName"`. See [this issue](https://github.com/pester/Pester/issues/1315) for more information. + +::: + +### BeTrue + +Asserts that the value is true, or truthy. + +```powershell +$true | Should -BeTrue +1 | Should -BeTrue +1,2,3 | Should -BeTrue +``` + +### Contain + +Asserts that the collection contains value specified using PowerShell's -contains operator. + +```powershell +'a','b','c' | Should -Contain b +1..100 | Should -Contain 42 +``` + +### Exist + +Does not perform any comparison but checks if the object calling Exist is present in a PS Provider. The object must have valid path syntax. It essentially must pass a Test-Path call. + +```powershell +$actual=(Dir . )[0].FullName +Remove-Item $actual +$actual | Should -Exist # Test will fail +``` + +To test path containing `[ ]` wildcards, escape each bracket with two back-ticks as such `"TestDrive:\``[test``].txt"` or use `Test-Path -LiteralPath $something | Should -Be $true`. + +### FileContentMatch + +Checks to see if a file contains the specified text. This search is not case sensitive and uses regular expressions. + +```powershell +Set-Content -Path TestDrive:\file.txt -Value 'I am a file' +'TestDrive:\file.txt' | Should -FileContentMatch 'I Am' # Test will pass +'TestDrive:\file.txt' | Should -FileContentMatch '^I.*file$' # Test will pass + +'TestDrive:\file.txt' | Should -FileContentMatch 'I Am Not' # Test will fail +``` + +:::tip +Use `[regex]::Escape("pattern")` to match the exact text. + +```powershell +Set-Content -Path TestDrive:\file.txt -Value 'I am a file.' +'TestDrive:\file.txt' | Should -FileContentMatch 'I.am.a.file' # Test will pass +'TestDrive:\file.txt' | Should -FileContentMatch ([regex]::Escape('I.am.a.file')) # Test will fail +``` +::: + +:::warning +Make sure the input is either a quoted string or an Item object. Otherwise PowerShell will try to invoke the +path, likely throwing an error `Cannot run a document in the middle of a pipeline`. + +```powershell +c:\file.txt | Should -FileContentMatch something # Will throw an error +'c:\file.txt' | Should -FileContentMatch something # Will evaluate correctly +``` +::: + +### FileContentMatchExactly + +Checks to see if a file contains the specified text. This search is case sensitive and uses regular expressions to match the text. + +```powershell +Set-Content -Path TestDrive:\file.txt -Value 'I am a file.' +'TestDrive:\file.txt' | Should -FileContentMatchExactly 'I am' # Test will pass +'TestDrive:\file.txt' | Should -FileContentMatchExactly 'I Am' # Test will fail +``` + +### FileContentMatchMultiline + +As opposed to FileContentMatch and FileContentMatchExactly operators, FileContentMatchMultiline presents content of the file being tested as one string object, so that the expression you are comparing it to can consist of several lines. + +```powershell +$Content = "I am the first line.`nI am the second line." +Set-Content -Path TestDrive:\file.txt -Value $Content -NoNewline +'TestDrive:\file.txt' | Should -FileContentMatchMultiline 'first line\.\r?\nI am' # Test will pass +'TestDrive:\file.txt' | Should -FileContentMatchMultiline '^I am the first.*\n.*second line\.$' # Test will pass. +``` + +When using FileContentMatchMultiline operator, `^` and `$` represent the beginning and end of the whole file, instead of the beginning and end of a line. + +```powershell +$Content = "I am the first line.`nI am the second line." +Set-Content -Path TestDrive:\file.txt -Value $Content -NoNewline +'TestDrive:\file.txt' | Should -FileContentMatchMultiline '^I am the first line\.$' # Test will fail. +``` + +### FileContentMatchMultilineExactly + +As opposed to FileContentMatch and FileContentMatchExactly operators, FileContentMatchMultilineExactly presents content of the file being tested as one string object, so that the expression you are comparing it to can consist of several lines. This search is case sensitive and uses regular expressions to match the text. + +```powershell +$Content = "I am the first line.`nI am the second line." +Set-Content -Path TestDrive:\file.txt -Value $Content -NoNewline +'TestDrive:\file.txt' | Should -FileContentMatchMultilineExactly 'first line\.\r?\nI am' # Test will pass +'TestDrive:\file.txt' | Should -FileContentMatchMultilineExactly 'first line\.\r?\nI AM' # Test will fail +'TestDrive:\file.txt' | Should -FileContentMatchMultilineExactly '^I am the first.*\n.*second line\.$' # Test will pass. +'TestDrive:\file.txt' | Should -FileContentMatchMultilineExactly '^I AM THE FIRST.*\n.*second line\.$' # Test will fail. +``` + +When using FileContentMatchMultilineExactly operator, `^` and `$` represent the beginning and end of the whole file, instead of the beginning and end of a line. + +```powershell +$Content = "I am the first line.`nI am the second line." +Set-Content -Path TestDrive:\file.txt -Value $Content -NoNewline +'TestDrive:\file.txt' | Should -FileContentMatchMultilineExactly '^I am the first line\.$' # Test will fail. +``` + +### HaveCount + +Asserts that a collection has the expected amount of items. + +```powershell +1,2,3 | Should -HaveCount 3 +``` + +### HaveParameter + +An assertion operator `-HaveParameter` allows you to check function parameters, and their properties like this: + +```powershell +Get-Command "Invoke-WebRequest" | Should -HaveParameter Uri -Mandatory +function f ([String] $Value = 8) { } +Get-Command f | Should -HaveParameter Value -Type String +Get-Command f | Should -Not -HaveParameter Name +Get-Command f | Should -HaveParameter Value -DefaultValue 8 +Get-Command f | Should -HaveParameter Value -Not -Mandatory +``` + +### Invoke + +Checks if a mocked command has been called a certain number of times and throws an exception if it has not. See [Mocking](../usage/mocking) for more details. + +### InvokeVerifiable + +Checks if any verifiable Mock have not been invoked. If so, this will throw an exception. See [Mocking](../usage/mocking) for more details. + +### Match + +Uses a regular expression to compare two objects. This comparison is not case sensitive. + +```powershell +"I am a value" | Should -Match "I Am" # Test will pass +"I am a value" | Should -Match "I am a bad person" # Test will fail +``` + +:::tip +Use `[regex]::Escape("pattern")` to match the exact text. + +```powershell +"Greg" | Should -Match ".reg" # Test will pass +"Greg" | Should -Match ([regex]::Escape(".reg")) # Test will fail +``` +::: + +### MatchExactly + +Uses a regular expression to compare two objects. This comparison is case sensitive. + +```powershell +"I am a value" | Should -MatchExactly "I am" # Test will pass +"I am a value" | Should -MatchExactly "I Am" # Test will fail +``` + +### Throw + +Checks if an exception was thrown in the input ScriptBlock. Takes an optional argument to indicate the expected exception message. + +```powershell +{ foo } | Should -Throw # Test will pass +{ $foo = 1 } | Should -Throw # Test will fail +{ foo } | Should -Not -Throw # Test will fail +{ $foo = 1 } | Should -Not -Throw # Test will pass +{ throw "This is a test" } | Should -Throw "This is a test" # Test will pass +{ throw "bar" } | Should -Throw "This is a test" # Test will fail +``` + +:::info +The exception message match is a `-like` +[wildcard match](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_comparison_operators?view=powershell-7#matching-operators), +so the following assertion will pass: + +```powershell +{throw "foo bar baz"} | Should -Throw "*bar*" # Test will pass +``` + +Wildcard-characters `?*[]` can be escaped using backtick, ex `` `*``. +::: + +:::warning +The input object must be a ScriptBlock, otherwise it is processed outside of the assertion. + +```powershell +Get-Process -Name "process" -ErrorAction Stop | Should -Throw # Should pass but fails the test +``` +::: + + +:::tip +`Throw` is used to validate terminating errors (i.e. exceptions that were thrown). +If you want to perform validation against non-terminating errors (i.e. `Write-Error` messages), you can [use the technique described here](https://github.com/pester/Pester/issues/366#issuecomment-489377880). +::: + +:::tip +If you are calling a cmdlet and want to force all errors to be terminating errors so that they can be caught by `| -Should -Throw`, then append `-ErrorAction Stop` to the cmdlet parameters as shown in the example above. +::: diff --git a/versioned_docs/version-v5/assertions/custom-assertions.mdx b/versioned_docs/version-v5/assertions/custom-assertions.mdx new file mode 100644 index 00000000..ca6ef5fe --- /dev/null +++ b/versioned_docs/version-v5/assertions/custom-assertions.mdx @@ -0,0 +1,232 @@ +--- +title: Custom Assertions +description: A guide for creating your own custom operators for more advanced or user-specific assertion needs +--- + +Pester allows users to create their own `Should`-operators for more advanced assertions. This is done by defining a test-function and registering it with Pester using the guidelines below. + +## Create the function + +### Requirements / Interface + +[Should](../commands/Add-ShouldOperator) will automatically pass on values from pipeline to your function as `ActualValue`. +This can be an array or a single object depending on whether you register the function with `-SupportsArrayInput`. + +When `Should` calls your custom assertion, it will invoke it with the following parameters: +- **ActualValue**: The value passed to `Should` to assert. +- **Negate**: Internal switch/bool parameter used to declare if the user called `Should -Not ...`. +- **CallerSessionState**: Used by some internal assertions to invoke code in the user's state. This can usually be ignored. +- *Remaining bound parameters*, typically matching the parameters your accept in your assertion, like `ExpectedValue`, `Because`, `MyCustomParameter` etc. + +The function should return a object with the following properties: +- **Succeeded**: Bool result of assert +- **FailureMessage**: Message to the user explaining why the assert failed, typically in the format `Expected , but got `. If the function supports the commonly used `-Because` parameter, this property should include that message. + +If a problem occurs in your function, ex. it was called with invalid parameters, throw an exception. This will also fail the `Should` assertion, while making it clear to the user that it's not normal behavior. + +:::tip ActualValue is provided as a single parameter +`Should` accepts the value to assert by pipeline but passes it to the assertion using `-ActualValue $ActualValue`. This means `ValueFromPipelineByPropertyName` is not available inside your function, but you can write your own logic to work with complex types provided to `ActualValue`. +::: + +:::warning Using advanced functions as assertions +Advanced functions, typically enabled by using `[CmdletBinding()]` or `[Parameter()]`, disallows arguments by default. In this scenario, make sure to accept all mandatory parameters in your param-block to avoid errors even if you don't use them. They are `ActualValue`, `Negate` and `CallerSessionState`. +::: + +### Good practices + +- Support `-Not` for negative assertions. If not supported, throw an exception when used. + - Note that this is passed as `$Negate` to the function. +- Support `-Because` to let users customize the error message on failure. +- Write tests for you custom assertions to make sure they work the way you intended. + - `Should` will create error records for failed assertions with the `FullyQualifiedErrorId` set to `PesterAssertionFailed`. +- Provide comment-based help with synopsis and examples so users can find it using `Get-ShouldOperator`. + - If you register an operator with a different name than the internal function, specify `-InternalName YourFunctionName` in `Add-ShouldOperator`. + This is required for `Get-ShouldOperator` to retrieve your comment-bases help. + +## Register function as operator + +When your function is ready you need to register it with Pester. See [Add-ShouldOperator](../commands/Add-ShouldOperator) for help or check out the examples below. Remember: + +- If `-Name` is different from the actual function name, make sure to specify `-InternalName` with your function name. This is used to retrieve help in `Get-ShouldOperator`. +- Specify `-SupportsArrayInput` if your function should work with array input, ex. `1,2,3 | Should -BeNumber` + +Example registering a assertion function named `Should-BeNumber`: + +```powershell +Add-ShouldOperator -Name BeNumber ` + -InternalName 'Should-BeNumber' ` + -Test ${function:Should-BeNumber} ` + -Alias 'BeNum' ` + -SupportsArrayInput +``` + +:::note Maxmimum number of Should operators +Due to a limitation in PowerShell and the current design on `Should`, Pester is limited to a maximum of 32 Should operators. Pester currently includes 25 built-in operators, which limits how many custom operators you can register in a single session. +The limitation is tracked in [this issue](https://github.com/pester/Pester/issues/1355) +::: + +## Examples + +### Simple example + +```powershell title="MyCustomAssertions.psm1" +#Requires -Module Pester + +function Should-BeUpperCaseOnly ([string] $ActualValue, [switch] $Negate, [string] $Because) { + <# + .SYNOPSIS + Checks provided string for only uppercase letters + .EXAMPLE + "ABC" | Should -BeUpperCaseOnly + + Checks if "ABC" only contains uppercase letters. This should pass. + .EXAMPLE + "aBc" | Should -Not -BeUpperCaseOnly + + Checks if "aBc" does NOT contain only uppercase. Since there are lowercase letters in the string, this should pass. + #> + $arr = $ActualValue.ToCharArray() + [bool] $succeeded = @($arr | Where-Object { [char]::IsLetter($_) -and [char]::IsUpper($_) }).Count -eq $arr.Count + if ($Negate) { $succeeded = -not $succeeded } + + if (-not $succeeded) { + if ($Negate) { + $failureMessage = "Expected '$ActualValue' to not only contain uppercase letters$(if($Because) { " because $Because"})." + } + else { + $failureMessage = "Expected '$ActualValue' to only contain uppercase letters$(if($Because) { " because $Because"})." + } + } + + return [pscustomobject]@{ + Succeeded = $succeeded + FailureMessage = $failureMessage + } +} + +Add-ShouldOperator -Name BeUpperCaseOnly ` + -InternalName 'Should-BeUpperCaseOnly' ` + -Test ${function:Should-BeUpperCaseOnly} ` + -Alias 'BU' +``` + +```powershell title="demo.tests.ps1" +BeforeDiscovery { + # Loads and registers my custom assertion. Ignores usage of unapproved verb with -DisableNameChecking + Import-Module "$PSScriptRoot/MyCustomAssertions.psm1" -DisableNameChecking +} + +Describe 'Testing Should -BeUpperCaseOnly' { + It 'Success' { + "HELLO" | Should -BeUpperCaseOnly + } + + It 'Failure' { + "HeLLo" | Should -BeUpperCaseOnly -Because "it looks cooler" + } + + It 'Not all characters are uppercase' { + "hELLO" | Should -Not -BeUpperCaseOnly + } + + It 'We can test failed assertions' { + { "fails" | Should -BeUpperCaseOnly } | Should -Throw -ErrorId 'PesterAssertionFailed' + } +} +``` + +#### Demo + +```powershell +Invoke-Pester ./demo.tests.ps1 + +Starting discovery in 1 files. +Discovery found 4 tests in 181ms. +Running tests. +[-] Testing custom assertion.Failure 22ms (20ms|3ms) + Expected 'HeLLo' to only contain uppercase letters because it looks cooler. + at "HeLLo" | Should -BeUpperCaseOnly -Because "it looks cooler", /workspaces/Pester/Samples/demo.tests.ps1:11 + at , /workspaces/Pester/Samples/demo.tests.ps1:11 +Tests completed in 651ms +Tests Passed: 3, Failed: 1, Skipped: 0 NotRun: 0 +``` + +### SupportsArrayInput example + +```powershell title="MyCustomAssertions.psm1" +#Requires -Module Pester + +function Should-ContainOnlyValuesOf ($ActualValue, [int]$ExpectedValue, [switch] $Negate, [string] $Because) { + <# + .SYNOPSIS + Asserts if collection contains only the expected value + .EXAMPLE + 3,3,3 | Should -ContainOnlyValuesOf 3 + + Checks if the array contains only values of 3. This should pass. + + .EXAMPLE + 1,2,3 | Should -Not -ContainOnlyValuesOf 3 + + Checks if the array contains other values than 3. This should pass. + #> + + $notEqual = foreach ($val in $ActualValue) { + if ($val -ne $ExpectedValue) { $val } + } + [bool] $succeeded = @($notEqual).Count -eq 0 + if ($Negate) { $succeeded = -not $succeeded } + + if (-not $succeeded) { + if ($Negate) { + $failureMessage = "Expected values not equal to $ExpectedValue to be in collection @($($ActualValue -join ', '))$(if($Because) { " because $Because"})." + } + else { + $failureMessage = "Expected only values equal to $ExpectedValue in collection @($($ActualValue -join ', '))$(if($Because) { " because $Because"})." + } + } + + return [pscustomobject]@{ + Succeeded = $succeeded + FailureMessage = $failureMessage + } +} + +Add-ShouldOperator -Name ContainOnlyValuesOf ` + -InternalName 'Should-ContainOnlyValuesOf' ` + -Test ${function:Should-ContainOnlyValuesOf} ` + -SupportsArrayInput +``` + +```powershell title="demo.tests.ps1" +BeforeDiscovery { + # Loads and registers my custom assertion. Ignores usage of unapproved verb with -DisableNameChecking + Import-Module "$PSScriptRoot/MyCustomAssertions.psm1" -DisableNameChecking +} + +Describe 'Testing Should -ContainOnlyValuesOf' { + It 'All values are as expected' { + 3, 3, 3 | Should -ContainOnlyValuesOf 3 + } + + It 'Failure' { + 3, 3, 3 | Should -Not -ContainOnlyValuesOf 3 + } +} +``` + +#### Demo + +```powershell +Invoke-Pester ./demo.tests.ps1 + +Starting discovery in 1 files. +Discovery found 2 tests in 25ms. +Running tests. +[-] Testing Should -ContainOnlyValuesOf.Failure 8ms (6ms|2ms) + Expected values not equal to 3 to be in collection @(3, 3, 3). + at 3, 3, 3 | Should -Not -ContainOnlyValuesOf 3, /workspaces/Pester/Samples/demo.tests.ps1:11 + at , /workspaces/Pester/Samples/demo.tests.ps1:11 +Tests completed in 83ms +Tests Passed: 1, Failed: 1, Skipped: 0 NotRun: 0 +``` diff --git a/versioned_docs/version-v5/assertions/should-command.mdx b/versioned_docs/version-v5/assertions/should-command.mdx new file mode 100644 index 00000000..6ed5c677 --- /dev/null +++ b/versioned_docs/version-v5/assertions/should-command.mdx @@ -0,0 +1,76 @@ +--- +title: Should +description: Introduction to the Should command that's used to define assertions that fail or pass the test +--- + +`Should` is used to do an assertion that fails or passes the test. + +An example of assertion is comparing two strings in case insensitive manner: + +```powershell +"Pester is bad." | Should -Be "Pester is awesome!" +``` + +Which throws an exception with this text to fail the test: + +``` +Expected strings to be the same, but they were different. +Expected length: 18 +Actual length: 14 +Strings differ at index 10. +Expected: 'Pester is awesome!' +But was: 'Pester is bad.' + ----------^ +``` + +Other assertion types can be found in [Assertion Reference](.). + + +### Collect all Should failures + +`Should` can now be configured to continue on failure. This will report the error to Pester, but won't fail the test immediately. Instead, all the Should failures are collected and reported at the end of the test. This allows you to put multiple assertions into one It and still get complete information on failure. + +This new Should behavior is opt-in and can be enabled via `Should.ErrorAction = 'Continue'` on the configuration object or via `$PesterPreference`. + +```powershell + BeforeAll { + function Get-User { + @{ + Name = "Jakub" + Age = 31 + } + } +} + +Describe "describe" { + It "user" { + $user = Get-User + + $user | Should -Not -BeNullOrEmpty -ErrorAction Stop + $user.Name | Should -Be "Tomas" + $user.Age | Should -Be 27 + + } +} + +``` + +``` +Starting test discovery in 1 files. +Found 1 tests. 51ms +Test discovery finished. 83ms +Describing describe + [-] user 124ms (109ms|15ms) + [0] Expected strings to be the same, but they were different. + String lengths are both 5. + Strings differ at index 0. + Expected: 'Tomas' + But was: 'Jakub' + at $user.Name | Should -Be "Tomas" + [1] Expected 27, but got 31. + at $user.Age | Should -Be 27 +Tests completed in 286ms +Tests Passed: 0, Failed: 1, Skipped: 0, Total: 1, NotRun: 0 +``` + +This allows you to check complex objects easily without writing It for each of the properties that you want to test. You can also use `-ErrorAction Stop` to force a failure when a pre-condition is not met. In our case if `$user` was null, there would be no point in testing the object further and we would fail the test immediately. diff --git a/versioned_docs/version-v5/commands/Add-ShouldOperator.mdx b/versioned_docs/version-v5/commands/Add-ShouldOperator.mdx new file mode 100644 index 00000000..b56e1445 --- /dev/null +++ b/versioned_docs/version-v5/commands/Add-ShouldOperator.mdx @@ -0,0 +1,169 @@ +--- +id: Add-ShouldOperator +title: Add-ShouldOperator +description: Help page for the PowerShell Pester "Add-ShouldOperator" command +keywords: + - PowerShell + - Pester + - Help + - Documentation +hide_title: false +hide_table_of_contents: false +custom_edit_url: null +--- + +:::info This page was generated +Contributions are welcome in [Pester-repo](https://github.com/pester/pester). +::: + +## SYNOPSIS + +Register a Should Operator with Pester + +## SYNTAX + +```powershell +Add-ShouldOperator [-Name] [-Test] [[-Alias] ] [[-InternalName] ] + [-SupportsArrayInput] [] +``` + +## DESCRIPTION + +This function allows you to create custom Should assertions. + +## EXAMPLES + +### EXAMPLE 1 + +```powershell +function BeAwesome($ActualValue, [switch] $Negate) { + [bool] $succeeded = $ActualValue -eq 'Awesome' + if ($Negate) { $succeeded = -not $succeeded } + + if (-not $succeeded) { + if ($Negate) { + $failureMessage = "{$ActualValue} is Awesome" + } + else { + $failureMessage = "{$ActualValue} is not Awesome" + } + } + + return New-Object psobject -Property @{ + Succeeded = $succeeded + FailureMessage = $failureMessage + } +} + +Add-ShouldOperator -Name BeAwesome ` + -Test $function:BeAwesome ` + -Alias 'BA' + +PS C:\> "bad" | Should -BeAwesome +{bad} is not Awesome +``` + +Example of how to create a simple custom assertion that checks if the input string is 'Awesome' + +## PARAMETERS + +### -Name + +The name of the assertion. +This will become a Named Parameter of Should. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Test + +The test function. +The function must return a PSObject with a [Bool]succeeded and a [string]failureMessage property. + +```yaml +Type: ScriptBlock +Parameter Sets: (All) +Aliases: + +Required: True +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Alias + +A list of aliases for the Named Parameter. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: 3 +Default value: @() +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -InternalName + +If -Name is different from the actual function name, record the actual function name here. +Used by Get-ShouldOperator to pull function help. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 4 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SupportsArrayInput + +Does the test function support the passing an array of values to test. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS + +[https://pester.dev/docs/commands/Add-ShouldOperator](https://pester.dev/docs/commands/Add-ShouldOperator) + +## VERSION + +*This page was generated using comment-based help in [Pester 5.6.0](https://github.com/pester/pester).* diff --git a/versioned_docs/version-v5/commands/AfterAll.mdx b/versioned_docs/version-v5/commands/AfterAll.mdx new file mode 100644 index 00000000..66f2e673 --- /dev/null +++ b/versioned_docs/version-v5/commands/AfterAll.mdx @@ -0,0 +1,110 @@ +--- +id: AfterAll +title: AfterAll +description: Help page for the PowerShell Pester "AfterAll" command +keywords: + - PowerShell + - Pester + - Help + - Documentation +hide_title: false +hide_table_of_contents: false +custom_edit_url: null +--- + +:::info This page was generated +Contributions are welcome in [Pester-repo](https://github.com/pester/pester). +::: + +## SYNOPSIS + +Defines a series of steps to perform at the end of the current container, +Context or Describe block. + +## SYNTAX + +```powershell +AfterAll [-Scriptblock] [] +``` + +## DESCRIPTION + +AfterAll is used to share teardown after all the tests in a container, Describe +or Context including all child blocks and tests. +AfterAll runs during Run phase +and runs only once in the current block. +It's guaranteed to run even if tests +fail. + +The typical usage is to clean up state or temporary used in tests. + +BeforeAll and AfterAll are unique in that they apply to the entire container, +Context or Describe block regardless of the order of the statements compared to +other Context or Describe blocks at the same level. + +## EXAMPLES + +### EXAMPLE 1 + +```powershell +Describe "Validate important file" { + BeforeAll { + $samplePath = "$([IO.Path]::GetTempPath())/$([Guid]::NewGuid()).txt" + Write-Host $samplePath + 1..100 | Set-Content -Path $samplePath + } + + It "File Contains 100 lines" { + @(Get-Content $samplePath).Count | Should -Be 100 + } + + It "First ten lines should be 1 -> 10" { + @(Get-Content $samplePath -TotalCount 10) | Should -Be @(1..10) + } + + AfterAll { + Remove-Item -Path $samplePath + } +} +``` + +This example uses AfterAll to clean up a sample-file generated only for +the tests in the Describe-block. + +## PARAMETERS + +### -Scriptblock + +A scriptblock with steps to be executed during teardown. + +```yaml +Type: ScriptBlock +Parameter Sets: (All) +Aliases: + +Required: True +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS + +[https://pester.dev/docs/commands/AfterAll](https://pester.dev/docs/commands/AfterAll) + +[https://pester.dev/docs/usage/setup-and-teardown](https://pester.dev/docs/usage/setup-and-teardown) + +## VERSION + +*This page was generated using comment-based help in [Pester 5.6.0](https://github.com/pester/pester).* diff --git a/versioned_docs/version-v5/commands/AfterEach.mdx b/versioned_docs/version-v5/commands/AfterEach.mdx new file mode 100644 index 00000000..49b971e8 --- /dev/null +++ b/versioned_docs/version-v5/commands/AfterEach.mdx @@ -0,0 +1,107 @@ +--- +id: AfterEach +title: AfterEach +description: Help page for the PowerShell Pester "AfterEach" command +keywords: + - PowerShell + - Pester + - Help + - Documentation +hide_title: false +hide_table_of_contents: false +custom_edit_url: null +--- + +:::info This page was generated +Contributions are welcome in [Pester-repo](https://github.com/pester/pester). +::: + +## SYNOPSIS + +Defines a series of steps to perform at the end of every It block within +the current Context or Describe block. + +## SYNTAX + +```powershell +AfterEach [-Scriptblock] [] +``` + +## DESCRIPTION + +AfterEach runs once after every test in the current or any child blocks. +Typically this is used to clean up resources created by the test or its setups. +AfterEach runs in a finally block, and is guaranteed to run even if the test +(or setup) fails. + +BeforeEach and AfterEach are unique in that they apply to the entire Context +or Describe block, regardless of the order of the statements in the +Context or Describe. + +## EXAMPLES + +### EXAMPLE 1 + +```powershell +Describe "Testing export formats" { + BeforeAll { + $filePath = "$([IO.Path]::GetTempPath())/$([Guid]::NewGuid())" + } + It "Test Export-CSV" { + Get-ChildItem | Export-CSV -Path $filePath -NoTypeInformation + $dir = Import-CSV -Path $filePath + # ... + } + It "Test Export-Clixml" { + Get-ChildItem | Export-Clixml -Path $filePath + $dir = Import-Clixml -Path $filePath + # ... + } + + AfterEach { + if (Test-Path $file) { + Remove-Item $file -Force + } + } +} +``` + +The example uses AfterEach to remove a temporary file after each test. + +## PARAMETERS + +### -Scriptblock + +A scriptblock with steps to be executed during teardown. + +```yaml +Type: ScriptBlock +Parameter Sets: (All) +Aliases: + +Required: True +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS + +[https://pester.dev/docs/commands/AfterEach](https://pester.dev/docs/commands/AfterEach) + +[https://pester.dev/docs/usage/setup-and-teardown](https://pester.dev/docs/usage/setup-and-teardown) + +## VERSION + +*This page was generated using comment-based help in [Pester 5.6.0](https://github.com/pester/pester).* diff --git a/docs/commands/Assert-MockCalled.mdx b/versioned_docs/version-v5/commands/Assert-MockCalled.mdx similarity index 100% rename from docs/commands/Assert-MockCalled.mdx rename to versioned_docs/version-v5/commands/Assert-MockCalled.mdx diff --git a/docs/commands/Assert-VerifiableMock.mdx b/versioned_docs/version-v5/commands/Assert-VerifiableMock.mdx similarity index 100% rename from docs/commands/Assert-VerifiableMock.mdx rename to versioned_docs/version-v5/commands/Assert-VerifiableMock.mdx diff --git a/versioned_docs/version-v5/commands/BeforeAll.mdx b/versioned_docs/version-v5/commands/BeforeAll.mdx new file mode 100644 index 00000000..2f43f3c0 --- /dev/null +++ b/versioned_docs/version-v5/commands/BeforeAll.mdx @@ -0,0 +1,119 @@ +--- +id: BeforeAll +title: BeforeAll +description: Help page for the PowerShell Pester "BeforeAll" command +keywords: + - PowerShell + - Pester + - Help + - Documentation +hide_title: false +hide_table_of_contents: false +custom_edit_url: null +--- + +:::info This page was generated +Contributions are welcome in [Pester-repo](https://github.com/pester/pester). +::: + +## SYNOPSIS + +Defines a series of steps to perform at the beginning of the current container, +Context or Describe block. + +## SYNTAX + +```powershell +BeforeAll [-Scriptblock] [] +``` + +## DESCRIPTION + +BeforeAll is used to share setup among all the tests in a container, Describe +or Context including all child blocks and tests. +BeforeAll runs during Run phase +and runs only once in the current level. + +The typical usage is to setup the whole test script, most commonly to +import the tested function, by dot-sourcing the script file that contains it. + +BeforeAll and AfterAll are unique in that they apply to the entire container, +Context or Describe block regardless of the order of the statements compared to +other Context or Describe blocks at the same level. + +## EXAMPLES + +### EXAMPLE 1 + +```powershell +BeforeAll { + . $PSCommandPath.Replace('.Tests.ps1','.ps1') +} + +Describe "API validation" { + # ... +} +``` + +This example uses dot-sourcing in BeforeAll to make functions in the script-file +available for the tests. + +### EXAMPLE 2 + +```powershell +Describe "API validation" { + BeforeAll { + # this calls REST API and takes roughly 1 second + $response = Get-Pokemon -Name Pikachu + } + + It "response has Name = 'Pikachu'" { + $response.Name | Should -Be 'Pikachu' + } + + It "response has Type = 'electric'" { + $response.Type | Should -Be 'electric' + } +} +``` + +This example uses BeforeAll to perform an expensive operation only once, before validating +the results in separate tests. + +## PARAMETERS + +### -Scriptblock + +A scriptblock with steps to be executed during setup. + +```yaml +Type: ScriptBlock +Parameter Sets: (All) +Aliases: + +Required: True +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS + +[https://pester.dev/docs/commands/BeforeAll](https://pester.dev/docs/commands/BeforeAll) + +[https://pester.dev/docs/usage/setup-and-teardown](https://pester.dev/docs/usage/setup-and-teardown) + +## VERSION + +*This page was generated using comment-based help in [Pester 5.6.0](https://github.com/pester/pester).* diff --git a/versioned_docs/version-v5/commands/BeforeDiscovery.mdx b/versioned_docs/version-v5/commands/BeforeDiscovery.mdx new file mode 100644 index 00000000..9d58752d --- /dev/null +++ b/versioned_docs/version-v5/commands/BeforeDiscovery.mdx @@ -0,0 +1,97 @@ +--- +id: BeforeDiscovery +title: BeforeDiscovery +description: Help page for the PowerShell Pester "BeforeDiscovery" command +keywords: + - PowerShell + - Pester + - Help + - Documentation +hide_title: false +hide_table_of_contents: false +custom_edit_url: null +--- + +:::info This page was generated +Contributions are welcome in [Pester-repo](https://github.com/pester/pester). +::: + +## SYNOPSIS + +Runs setup code that is used during Discovery phase. + +## SYNTAX + +```powershell +BeforeDiscovery [-ScriptBlock] [] +``` + +## DESCRIPTION + +Runs your code as is, in the place where this function is defined. +This is a semantic block to allow you +to be explicit about code that you need to run during Discovery, instead of just +putting code directly inside of Describe / Context. + +## EXAMPLES + +### EXAMPLE 1 + +```powershell +BeforeDiscovery { + $files = Get-ChildItem -Path $PSScriptRoot -Filter '*.ps1' -Recurse +} + +Describe "File - <_>" -ForEach $files { + Context "Whitespace" { + It "There is no extra whitespace following a line" { + # ... + } + + It "File ends with an empty line" { + # ... + } + } +} +``` + +BeforeDiscovery is used to gather a list of script-files during Discovery-phase to +dynamically create a Describe-block and tests for each file found. + +## PARAMETERS + +### -ScriptBlock + +The ScriptBlock to run. + +```yaml +Type: ScriptBlock +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS + +[https://pester.dev/docs/commands/BeforeDiscovery](https://pester.dev/docs/commands/BeforeDiscovery) + +[https://pester.dev/docs/usage/data-driven-tests](https://pester.dev/docs/usage/data-driven-tests) + +## VERSION + +*This page was generated using comment-based help in [Pester 5.6.0](https://github.com/pester/pester).* diff --git a/versioned_docs/version-v5/commands/BeforeEach.mdx b/versioned_docs/version-v5/commands/BeforeEach.mdx new file mode 100644 index 00000000..88015aaf --- /dev/null +++ b/versioned_docs/version-v5/commands/BeforeEach.mdx @@ -0,0 +1,104 @@ +--- +id: BeforeEach +title: BeforeEach +description: Help page for the PowerShell Pester "BeforeEach" command +keywords: + - PowerShell + - Pester + - Help + - Documentation +hide_title: false +hide_table_of_contents: false +custom_edit_url: null +--- + +:::info This page was generated +Contributions are welcome in [Pester-repo](https://github.com/pester/pester). +::: + +## SYNOPSIS + +Defines a series of steps to perform at the beginning of every It block within +the current Context or Describe block. + +## SYNTAX + +```powershell +BeforeEach [-Scriptblock] [] +``` + +## DESCRIPTION + +BeforeEach runs once before every test in the current or any child blocks. +Typically this is used to create all the prerequisites for the current test, +such as writing content to a file. + +BeforeEach and AfterEach are unique in that they apply to the entire Context +or Describe block, regardless of the order of the statements in the +Context or Describe. + +## EXAMPLES + +### EXAMPLE 1 + +```powershell +Describe "File parsing" { + BeforeEach { + # randomized path, to get fresh file for each test + $file = "$([IO.Path]::GetTempPath())/$([Guid]::NewGuid())_form.xml" + Copy-Item -Source $template -Destination $file -Force | Out-Null + } + + It "Writes username" { + Write-XmlForm -Path $file -Field "username" -Value "nohwnd" + $content = Get-Content $file + # ... + } + + It "Writes name" { + Write-XmlForm -Path $file -Field "name" -Value "Jakub" + $content = Get-Content $file + # ... + } +} +``` + +The example uses BeforeEach to ensure a clean sample-file is used for each test. + +## PARAMETERS + +### -Scriptblock + +A scriptblock with steps to be executed during setup. + +```yaml +Type: ScriptBlock +Parameter Sets: (All) +Aliases: + +Required: True +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS + +[https://pester.dev/docs/commands/BeforeEach](https://pester.dev/docs/commands/BeforeEach) + +[https://pester.dev/docs/usage/setup-and-teardown](https://pester.dev/docs/usage/setup-and-teardown) + +## VERSION + +*This page was generated using comment-based help in [Pester 5.6.0](https://github.com/pester/pester).* diff --git a/versioned_docs/version-v5/commands/Context.mdx b/versioned_docs/version-v5/commands/Context.mdx new file mode 100644 index 00000000..4b2013ba --- /dev/null +++ b/versioned_docs/version-v5/commands/Context.mdx @@ -0,0 +1,186 @@ +--- +id: Context +title: Context +description: Help page for the PowerShell Pester "Context" command +keywords: + - PowerShell + - Pester + - Help + - Documentation +hide_title: false +hide_table_of_contents: false +custom_edit_url: null +--- + +:::info This page was generated +Contributions are welcome in [Pester-repo](https://github.com/pester/pester). +::: + +## SYNOPSIS + +Provides logical grouping of It blocks within a single Describe block. + +## SYNTAX + +```powershell +Context [-Name] [-Tag ] [[-Fixture] ] [-Skip] [-ForEach ] + [] +``` + +## DESCRIPTION + +Provides logical grouping of It blocks within a single Describe block. +Any Mocks defined inside a Context are removed at the end of the Context scope, +as are any files or folders added to the TestDrive during the Context block's +execution. +Any BeforeEach or AfterEach blocks defined inside a Context also only +apply to tests within that Context . + +## EXAMPLES + +### EXAMPLE 1 + +```powershell +BeforeAll { + function Add-Numbers($a, $b) { + return $a + $b + } +} + +Describe 'Add-Numbers' { + Context 'when adding positive values' { + It '...' { + # ... + } + } + + Context 'when adding negative values' { + It '...' { + # ... + } + It '...' { + # ... + } + } +} +``` + +Example of how to use Context for grouping different tests + +## PARAMETERS + +### -Name + +The name of the Context. +This is a phrase describing a set of tests within a describe. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Tag + +Optional parameter containing an array of strings. +When calling Invoke-Pester, +it is possible to specify a -Tag parameter which will only execute Context blocks +containing the same Tag. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: Tags + +Required: False +Position: Named +Default value: @() +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Fixture + +Script that is executed. +This may include setup specific to the context +and one or more It blocks that validate the expected outcomes. + +```yaml +Type: ScriptBlock +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Skip + +Use this parameter to explicitly mark the block to be skipped. +This is preferable to temporarily +commenting out a block, because it remains listed in the output. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ForEach + +Allows data driven tests to be written. +Takes an array of data and generates one block for each item in the array, and makes the item +available as $_ in all child blocks. +When the array is an array of hashtables, it additionally +defines each key in the hashtable as variable. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS + +[https://pester.dev/docs/commands/Context](https://pester.dev/docs/commands/Context) + +[https://pester.dev/docs/usage/test-file-structure](https://pester.dev/docs/usage/test-file-structure) + +[https://pester.dev/docs/usage/mocking](https://pester.dev/docs/usage/mocking) + +[https://pester.dev/docs/usage/testdrive](https://pester.dev/docs/usage/testdrive) + +## VERSION + +*This page was generated using comment-based help in [Pester 5.6.0](https://github.com/pester/pester).* diff --git a/versioned_docs/version-v5/commands/ConvertTo-JUnitReport.mdx b/versioned_docs/version-v5/commands/ConvertTo-JUnitReport.mdx new file mode 100644 index 00000000..09fb6e61 --- /dev/null +++ b/versioned_docs/version-v5/commands/ConvertTo-JUnitReport.mdx @@ -0,0 +1,121 @@ +--- +id: ConvertTo-JUnitReport +title: ConvertTo-JUnitReport +description: Help page for the PowerShell Pester "ConvertTo-JUnitReport" command +keywords: + - PowerShell + - Pester + - Help + - Documentation +hide_title: false +hide_table_of_contents: false +custom_edit_url: null +--- + +:::info This page was generated +Contributions are welcome in [Pester-repo](https://github.com/pester/pester). +::: + +## SYNOPSIS + +Converts a Pester result-object to an JUnit-compatible XML report + +## SYNTAX + +```powershell +ConvertTo-JUnitReport [-Result] [-AsString] [] +``` + +## DESCRIPTION + +Pester can generate a result-object containing information about all +tests that are processed in a run. +This objects can then be converted to an +NUnit-compatible XML-report using this function. +The report is generated +using the JUnit 4-schema. + +The function can convert to both XML-object or a string containing the XML. +This can be useful for further processing or publishing of test results, +e.g. +as part of a CI/CD pipeline. + +## EXAMPLES + +### EXAMPLE 1 + +```powershell +$p = Invoke-Pester -Passthru +$p | ConvertTo-JUnitReport +``` + +This example runs Pester using the Passthru option to retrieve the result-object and +converts it to an JUnit 4-compatible XML-report. +The report is returned as an XML-object. + +### EXAMPLE 2 + +```powershell +$p = Invoke-Pester -Passthru +$p | ConvertTo-JUnitReport -AsString +``` + +This example runs Pester using the Passthru option to retrieve the result-object and +converts it to an JUnit 4-compatible XML-report. +The returned object is a string. + +## PARAMETERS + +### -Result + +Result object from a Pester-run. +This can be retrieved using Invoke-Pester +-Passthru or by using the Run.PassThru configuration-option. + +```yaml +Type: Run +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -AsString + +Returns the XML-report as a string. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS + +[https://pester.dev/docs/commands/ConvertTo-JUnitReport](https://pester.dev/docs/commands/ConvertTo-JUnitReport) + +[https://pester.dev/docs/commands/Invoke-Pester](https://pester.dev/docs/commands/Invoke-Pester) + +## VERSION + +*This page was generated using comment-based help in [Pester 5.6.0](https://github.com/pester/pester).* diff --git a/versioned_docs/version-v5/commands/ConvertTo-NUnitReport.mdx b/versioned_docs/version-v5/commands/ConvertTo-NUnitReport.mdx new file mode 100644 index 00000000..6850dd87 --- /dev/null +++ b/versioned_docs/version-v5/commands/ConvertTo-NUnitReport.mdx @@ -0,0 +1,148 @@ +--- +id: ConvertTo-NUnitReport +title: ConvertTo-NUnitReport +description: Help page for the PowerShell Pester "ConvertTo-NUnitReport" command +keywords: + - PowerShell + - Pester + - Help + - Documentation +hide_title: false +hide_table_of_contents: false +custom_edit_url: null +--- + +:::info This page was generated +Contributions are welcome in [Pester-repo](https://github.com/pester/pester). +::: + +## SYNOPSIS + +Converts a Pester result-object to an NUnit 2.5 or 3-compatible XML-report + +## SYNTAX + +```powershell +ConvertTo-NUnitReport [-Result] [-AsString] [[-Format] ] [] +``` + +## DESCRIPTION + +Pester can generate a result-object containing information about all +tests that are processed in a run. +This objects can then be converted to an +NUnit-compatible XML-report using this function. +The report is generated +using either the NUnit 2.5 or 3-schema. + +The function can convert to both XML-object or a string containing the XML. +This can be useful for further processing or publishing of test results, +e.g. +as part of a CI/CD pipeline. + +## EXAMPLES + +### EXAMPLE 1 + +```powershell +$p = Invoke-Pester -Passthru +$p | ConvertTo-NUnitReport +``` + +This example runs Pester using the Passthru option to retrieve the result-object and +converts it to an NUnit 2.5-compatible XML-report. +The report is returned as an XML-object. + +### EXAMPLE 2 + +```powershell +$p = Invoke-Pester -Passthru +$p | ConvertTo-NUnitReport -Format NUnit3 +``` + +This example runs Pester using the Passthru option to retrieve the result-object and +converts it to an NUnit 3-compatible XML-report. +The report is returned as an XML-object. + +### EXAMPLE 3 + +```powershell +$p = Invoke-Pester -Passthru +$p | ConvertTo-NUnitReport -AsString +``` + +This example runs Pester using the Passthru option to retrieve the result-object and +converts it to an NUnit 2.5-compatible XML-report. +The returned object is a string. + +## PARAMETERS + +### -Result + +Result object from a Pester-run. +This can be retrieved using Invoke-Pester +-Passthru or by using the Run.PassThru configuration-option. + +```yaml +Type: Run +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -AsString + +Returns the XML-report as a string. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Format + +Specifies the NUnit-schema to be used. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: NUnit2.5 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS + +[https://pester.dev/docs/commands/ConvertTo-NUnitReport](https://pester.dev/docs/commands/ConvertTo-NUnitReport) + +[https://pester.dev/docs/commands/Invoke-Pester](https://pester.dev/docs/commands/Invoke-Pester) + +## VERSION + +*This page was generated using comment-based help in [Pester 5.6.0](https://github.com/pester/pester).* diff --git a/versioned_docs/version-v5/commands/ConvertTo-Pester4Result.mdx b/versioned_docs/version-v5/commands/ConvertTo-Pester4Result.mdx new file mode 100644 index 00000000..d515ed7e --- /dev/null +++ b/versioned_docs/version-v5/commands/ConvertTo-Pester4Result.mdx @@ -0,0 +1,89 @@ +--- +id: ConvertTo-Pester4Result +title: ConvertTo-Pester4Result +description: Help page for the PowerShell Pester "ConvertTo-Pester4Result" command +keywords: + - PowerShell + - Pester + - Help + - Documentation +hide_title: false +hide_table_of_contents: false +custom_edit_url: null +--- + +:::info This page was generated +Contributions are welcome in [Pester-repo](https://github.com/pester/pester). +::: + +## SYNOPSIS + +Converts a Pester 5 result-object to an Pester 4-compatible object + +## SYNTAX + +```powershell +ConvertTo-Pester4Result [-PesterResult] [] +``` + +## DESCRIPTION + +Pester 5 uses a new format for it's result-object compared to previous +versions of Pester. +This function is provided as a way to convert the +result-object into an object using the previous format. +This can be +useful as a temporary measure to easier migrate to Pester 5 without +having to redesign complex CI/CD-pipelines. + +## EXAMPLES + +### EXAMPLE 1 + +```powershell +$pester5Result = Invoke-Pester -Passthru +$pester4Result = $pester5Result | ConvertTo-Pester4Result +``` + +This example runs Pester using the Passthru option to retrieve a result-object +in the Pester 5 format and converts it to a new Pester 4-compatible result-object. + +## PARAMETERS + +### -PesterResult + +Result object from a Pester 5-run. +This can be retrieved using Invoke-Pester +-Passthru or by using the Run.PassThru configuration-option. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS + +[https://pester.dev/docs/commands/ConvertTo-Pester4Result](https://pester.dev/docs/commands/ConvertTo-Pester4Result) + +[https://pester.dev/docs/commands/Invoke-Pester](https://pester.dev/docs/commands/Invoke-Pester) + +## VERSION + +*This page was generated using comment-based help in [Pester 5.6.0](https://github.com/pester/pester).* diff --git a/versioned_docs/version-v5/commands/Describe.mdx b/versioned_docs/version-v5/commands/Describe.mdx new file mode 100644 index 00000000..fcf82020 --- /dev/null +++ b/versioned_docs/version-v5/commands/Describe.mdx @@ -0,0 +1,196 @@ +--- +id: Describe +title: Describe +description: Help page for the PowerShell Pester "Describe" command +keywords: + - PowerShell + - Pester + - Help + - Documentation +hide_title: false +hide_table_of_contents: false +custom_edit_url: null +--- + +:::info This page was generated +Contributions are welcome in [Pester-repo](https://github.com/pester/pester). +::: + +## SYNOPSIS + +Creates a logical group of tests. + +## SYNTAX + +```powershell +Describe [-Name] [-Tag ] [[-Fixture] ] [-Skip] [-ForEach ] + [] +``` + +## DESCRIPTION + +Creates a logical group of tests. +All Mocks, TestDrive and TestRegistry contents +defined within a Describe block are scoped to that Describe; they +will no longer be present when the Describe block exits. +A Describe +block may contain any number of Context and It blocks. + +## EXAMPLES + +### EXAMPLE 1 + +```powershell +BeforeAll { + function Add-Numbers($a, $b) { + return $a + $b + } +} + +Describe "Add-Numbers" { + It "adds positive numbers" { + $sum = Add-Numbers 2 3 + $sum | Should -Be 5 + } + + It "adds negative numbers" { + $sum = Add-Numbers (-2) (-2) + $sum | Should -Be (-4) + } + + It "adds one negative number to positive number" { + $sum = Add-Numbers (-2) 2 + $sum | Should -Be 0 + } + + It "concatenates strings if given strings" { + $sum = Add-Numbers two three + $sum | Should -Be "twothree" + } +} +``` + +Using Describe to group tests logically at the root of the script/container + +## PARAMETERS + +### -Name + +The name of the test group. +This is often an expressive phrase describing +the scenario being tested. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Tag + +Optional parameter containing an array of strings. +When calling Invoke-Pester, +it is possible to specify a -Tag parameter which will only execute Describe blocks +containing the same Tag. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: Tags + +Required: False +Position: Named +Default value: @() +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Fixture + +The actual test script. +If you are following the AAA pattern (Arrange-Act-Assert), +this typically holds the arrange and act sections. +The Asserts will also lie +in this block but are typically nested each in its own It block. +Assertions are +typically performed by the Should command within the It blocks. + +```yaml +Type: ScriptBlock +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Skip + +Use this parameter to explicitly mark the block to be skipped. +This is preferable to temporarily +commenting out a block, because it remains listed in the output. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ForEach + +Allows data driven tests to be written. +Takes an array of data and generates one block for each item in the array, and makes the item +available as $_ in all child blocks. +When the array is an array of hashtables, it additionally +defines each key in the hashtable as variable. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS + +[https://pester.dev/docs/commands/Describe](https://pester.dev/docs/commands/Describe) + +[https://pester.dev/docs/usage/test-file-structure](https://pester.dev/docs/usage/test-file-structure) + +[https://pester.dev/docs/usage/mocking](https://pester.dev/docs/usage/mocking) + +[https://pester.dev/docs/usage/testdrive](https://pester.dev/docs/usage/testdrive) + +## VERSION + +*This page was generated using comment-based help in [Pester 5.6.0](https://github.com/pester/pester).* diff --git a/versioned_docs/version-v5/commands/Export-JUnitReport.mdx b/versioned_docs/version-v5/commands/Export-JUnitReport.mdx new file mode 100644 index 00000000..74665c5c --- /dev/null +++ b/versioned_docs/version-v5/commands/Export-JUnitReport.mdx @@ -0,0 +1,108 @@ +--- +id: Export-JUnitReport +title: Export-JUnitReport +description: Help page for the PowerShell Pester "Export-JUnitReport" command +keywords: + - PowerShell + - Pester + - Help + - Documentation +hide_title: false +hide_table_of_contents: false +custom_edit_url: null +--- + +:::info This page was generated +Contributions are welcome in [Pester-repo](https://github.com/pester/pester). +::: + +## SYNOPSIS + +Exports a Pester result-object to an JUnit-compatible XML-report + +## SYNTAX + +```powershell +Export-JUnitReport [-Result] [-Path] [] +``` + +## DESCRIPTION + +Pester can generate a result-object containing information about all +tests that are processed in a run. +This object can then be exported to an +JUnit-compatible XML-report using this function. +The report is generated +using the JUnit 4-schema. + +This can be useful for further processing or publishing of test results, +e.g. +as part of a CI/CD pipeline. + +## EXAMPLES + +### EXAMPLE 1 + +```powershell +$p = Invoke-Pester -Passthru +$p | Export-JUnitReport -Path TestResults.xml +``` + +This example runs Pester using the Passthru option to retrieve the result-object and +exports it as an JUnit 4-compatible XML-report. + +## PARAMETERS + +### -Result + +Result object from a Pester-run. +This can be retrieved using Invoke-Pester +-Passthru or by using the Run.PassThru configuration-option. + +```yaml +Type: Run +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Path + +The path where the XML-report should be saved. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS + +[https://pester.dev/docs/commands/Export-JUnitReport](https://pester.dev/docs/commands/Export-JUnitReport) + +[https://pester.dev/docs/commands/Invoke-Pester](https://pester.dev/docs/commands/Invoke-Pester) + +## VERSION + +*This page was generated using comment-based help in [Pester 5.6.0](https://github.com/pester/pester).* diff --git a/versioned_docs/version-v5/commands/Export-NUnitReport.mdx b/versioned_docs/version-v5/commands/Export-NUnitReport.mdx new file mode 100644 index 00000000..7f0b487c --- /dev/null +++ b/versioned_docs/version-v5/commands/Export-NUnitReport.mdx @@ -0,0 +1,124 @@ +--- +id: Export-NUnitReport +title: Export-NUnitReport +description: Help page for the PowerShell Pester "Export-NUnitReport" command +keywords: + - PowerShell + - Pester + - Help + - Documentation +hide_title: false +hide_table_of_contents: false +custom_edit_url: null +--- + +:::info This page was generated +Contributions are welcome in [Pester-repo](https://github.com/pester/pester). +::: + +## SYNOPSIS + +Exports a Pester result-object to an NUnit-compatible XML-report + +## SYNTAX + +```powershell +Export-NUnitReport [-Result] [-Path] [[-Format] ] [] +``` + +## DESCRIPTION + +Pester can generate a result-object containing information about all +tests that are processed in a run. +This object can then be exported to an +NUnit-compatible XML-report using this function. +The report is generated +using the NUnit 2.5-schema (default) or NUnit3-compatible format. + +This can be useful for further processing or publishing of test results, +e.g. +as part of a CI/CD pipeline. + +## EXAMPLES + +### EXAMPLE 1 + +```powershell +$p = Invoke-Pester -Passthru +$p | Export-NUnitReport -Path TestResults.xml +``` + +This example runs Pester using the Passthru option to retrieve the result-object and +exports it as an NUnit 2.5-compatible XML-report. + +## PARAMETERS + +### -Result + +Result object from a Pester-run. +This can be retrieved using Invoke-Pester +-Passthru or by using the Run.PassThru configuration-option. + +```yaml +Type: Run +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Path + +The path where the XML-report should be saved. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Format + +Specifies the NUnit-schema to be used. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 3 +Default value: NUnit2.5 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS + +[https://pester.dev/docs/commands/Export-NUnitReport](https://pester.dev/docs/commands/Export-NUnitReport) + +[https://pester.dev/docs/commands/Invoke-Pester](https://pester.dev/docs/commands/Invoke-Pester) + +## VERSION + +*This page was generated using comment-based help in [Pester 5.6.0](https://github.com/pester/pester).* diff --git a/versioned_docs/version-v5/commands/Get-ShouldOperator.mdx b/versioned_docs/version-v5/commands/Get-ShouldOperator.mdx new file mode 100644 index 00000000..1b9b5769 --- /dev/null +++ b/versioned_docs/version-v5/commands/Get-ShouldOperator.mdx @@ -0,0 +1,97 @@ +--- +id: Get-ShouldOperator +title: Get-ShouldOperator +description: Help page for the PowerShell Pester "Get-ShouldOperator" command +keywords: + - PowerShell + - Pester + - Help + - Documentation +hide_title: false +hide_table_of_contents: false +custom_edit_url: null +--- + +:::info This page was generated +Contributions are welcome in [Pester-repo](https://github.com/pester/pester). +::: + +## SYNOPSIS + +Display the assertion operators available for use with Should. + +## SYNTAX + +```powershell +Get-ShouldOperator [-Name ] [] +``` + +## DESCRIPTION + +Get-ShouldOperator returns a list of available Should parameters, +their aliases, and examples to help you craft the tests you need. + +Get-ShouldOperator will list all available operators, +including any registered by the user with Add-ShouldOperator. + +## EXAMPLES + +### EXAMPLE 1 + +```powershell +Get-ShouldOperator +``` + +Return all available Should assertion operators and their aliases. + +### EXAMPLE 2 + +```powershell +Get-ShouldOperator -Name Be +``` + +Return help examples for the Be assertion operator. +-Name is a dynamic parameter that tab completes all available options. + +## PARAMETERS + +### -Name + +Name or alias of operator + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +Pester uses dynamic parameters to populate Should arguments. + +This limits the user's ability to discover the available assertions via +standard PowerShell discovery patterns (like `Get-Help Should -Parameter *`). + +## RELATED LINKS + +[https://pester.dev/docs/commands/Get-ShouldOperator](https://pester.dev/docs/commands/Get-ShouldOperator) + +[https://pester.dev/docs/commands/Should](https://pester.dev/docs/commands/Should) + +## VERSION + +*This page was generated using comment-based help in [Pester 5.6.0](https://github.com/pester/pester).* diff --git a/versioned_docs/version-v5/commands/InModuleScope.mdx b/versioned_docs/version-v5/commands/InModuleScope.mdx new file mode 100644 index 00000000..8a1afbe6 --- /dev/null +++ b/versioned_docs/version-v5/commands/InModuleScope.mdx @@ -0,0 +1,207 @@ +--- +id: InModuleScope +title: InModuleScope +description: Help page for the PowerShell Pester "InModuleScope" command +keywords: + - PowerShell + - Pester + - Help + - Documentation +hide_title: false +hide_table_of_contents: false +custom_edit_url: null +--- + +:::info This page was generated +Contributions are welcome in [Pester-repo](https://github.com/pester/pester). +::: + +## SYNOPSIS + +Allows you to execute parts of a test script within the +scope of a PowerShell script or manifest module. + +## SYNTAX + +```powershell +InModuleScope [-ModuleName] [-ScriptBlock] [[-Parameters] ] + [[-ArgumentList] ] [] +``` + +## DESCRIPTION + +By injecting some test code into the scope of a PowerShell +script or manifest module, you can use non-exported functions, aliases +and variables inside that module, to perform unit tests on +its internal implementation. + +InModuleScope may be used anywhere inside a Pester script, +either inside or outside a Describe block. + +## EXAMPLES + +### EXAMPLE 1 + +```powershell +# The script module: +function PublicFunction { + # Does something +} + +function PrivateFunction { + return $true +} + +Export-ModuleMember -Function PublicFunction + +# The test script: + +Import-Module MyModule + +InModuleScope MyModule { + Describe 'Testing MyModule' { + It 'Tests the Private function' { + PrivateFunction | Should -Be $true + } + } +} +``` + +Normally you would not be able to access "PrivateFunction" from +the PowerShell session, because the module only exported +"PublicFunction". +Using InModuleScope allowed this call to +"PrivateFunction" to work successfully. + +### EXAMPLE 2 + +```powershell +# The script module: +function PublicFunction { + # Does something +} + +function PrivateFunction ($MyParam) { + return $MyParam +} + +Export-ModuleMember -Function PublicFunction + +# The test script: + +Describe 'Testing MyModule' { + BeforeAll { + Import-Module MyModule + } + + It 'passing in parameter' { + $SomeVar = 123 + InModuleScope 'MyModule' -Parameters @{ MyVar = $SomeVar } { + $MyVar | Should -Be 123 + } + } + + It 'accessing whole testcase in module scope' -TestCases @( + @{ Name = 'Foo'; Bool = $true } + ) { + # Passes the whole testcase-dictionary available in $_ to InModuleScope + InModuleScope 'MyModule' -Parameters $_ { + $Name | Should -Be 'Foo' + PrivateFunction -MyParam $Bool | Should -BeTrue + } + } +} +``` + +This example shows two ways of using `-Parameters` to pass variables created in a +testfile into the module scope where the scriptblock provided to InModuleScope is executed. +No variables from the outside are available inside the scriptblock without explicitly passing +them in using `-Parameters` or `-ArgumentList`. + +## PARAMETERS + +### -ModuleName + +The name of the module into which the test code should be +injected. +This module must already be loaded into the current +PowerShell session. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ScriptBlock + +The code to be executed within the script or manifest module. + +```yaml +Type: ScriptBlock +Parameter Sets: (All) +Aliases: + +Required: True +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Parameters + +A optional hashtable of parameters to be passed to the scriptblock. +Parameters are automatically made available as variables in the scriptblock. + +```yaml +Type: Hashtable +Parameter Sets: (All) +Aliases: + +Required: False +Position: 3 +Default value: @{} +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ArgumentList + +A optional list of arguments to be passed to the scriptblock. + +```yaml +Type: Object[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: 4 +Default value: @() +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS + +[https://pester.dev/docs/commands/InModuleScope](https://pester.dev/docs/commands/InModuleScope) + +## VERSION + +*This page was generated using comment-based help in [Pester 5.6.0](https://github.com/pester/pester).* diff --git a/versioned_docs/version-v5/commands/Invoke-Pester.mdx b/versioned_docs/version-v5/commands/Invoke-Pester.mdx new file mode 100644 index 00000000..59c7806f --- /dev/null +++ b/versioned_docs/version-v5/commands/Invoke-Pester.mdx @@ -0,0 +1,656 @@ +--- +id: Invoke-Pester +title: Invoke-Pester +description: Help page for the PowerShell Pester "Invoke-Pester" command +keywords: + - PowerShell + - Pester + - Help + - Documentation +hide_title: false +hide_table_of_contents: false +custom_edit_url: null +--- + +:::info This page was generated +Contributions are welcome in [Pester-repo](https://github.com/pester/pester). +::: + +## SYNOPSIS + +Runs Pester tests + +## SYNTAX + +### Simple (Default) + +```powershell +Invoke-Pester [[-Path] ] [-ExcludePath ] [-TagFilter ] + [-ExcludeTagFilter ] [-FullNameFilter ] [-CI] [-Output ] [-PassThru] + [-Container ] [] +``` + +### Legacy + +```powershell +Invoke-Pester [[-Path] ] [-TagFilter ] [-ExcludeTagFilter ] + [-FullNameFilter ] [-PassThru] [-EnableExit] [-CodeCoverage ] + [-CodeCoverageOutputFile ] [-CodeCoverageOutputFileEncoding ] + [-CodeCoverageOutputFileFormat ] [-Strict] [-OutputFile ] [-OutputFormat ] [-Quiet] + [-PesterOption ] [-Show ] [] +``` + +### Advanced + +```powershell +Invoke-Pester [-Configuration ] [] +``` + +## DESCRIPTION + +The Invoke-Pester function runs Pester tests, including *.Tests.ps1 files and +Pester tests in PowerShell scripts. + +You can run scripts that include Pester tests just as you would any other +Windows PowerShell script, including typing the full path at the command line +and running in a script editing program. +Typically, you use Invoke-Pester to run +all Pester tests in a directory, or to use its many helpful parameters, +including parameters that generate custom objects or XML files. + +By default, Invoke-Pester runs all *.Tests.ps1 files in the current directory +and all subdirectories recursively. +You can use its parameters to select tests +by file name, test name, or tag. + +To run Pester tests in scripts that take parameter values, use the Script +parameter with a hash table value. + +Also, by default, Pester tests write test results to the console host, much like +Write-Host does, but you can use the Show parameter set to None to suppress the host +messages, use the PassThru parameter to generate a custom object +(PSCustomObject) that contains the test results, use the OutputXml and +OutputFormat parameters to write the test results to an XML file, and use the +EnableExit parameter to return an exit code that contains the number of failed +tests. + +You can also use the Strict parameter to fail all pending and skipped tests. +This feature is ideal for build systems and other processes that require success +on every test. + +To help with test design, Invoke-Pester includes a CodeCoverage parameter that +lists commands, classes, functions, and lines of code that did not run during test +execution and returns the code that ran as a percentage of all tested code. + +Invoke-Pester, and the Pester module that exports it, are products of an +open-source project hosted on GitHub. +To view, comment, or contribute to the +repository, see https://github.com/Pester. + +## EXAMPLES + +### EXAMPLE 1 + +```powershell +Invoke-Pester +``` + +This command runs all *.Tests.ps1 files in the current directory and its subdirectories. + +### EXAMPLE 2 + +```powershell +Invoke-Pester -Path .\Util* +``` + +This commands runs all *.Tests.ps1 files in subdirectories with names that begin +with 'Util' and their subdirectories. + +### EXAMPLE 3 + +```powershell +$config = [PesterConfiguration]@{ + Should = @{ # <- Should configuration. + ErrorAction = 'Continue' # <- Always run all Should-assertions in a test + } +} + +Invoke-Pester -Configuration $config +``` + +This example runs all *.Tests.ps1 files in the current directory and its subdirectories. +It shows how advanced configuration can be used by casting a hashtable to override +default settings, in this case to make Pester run all Should-assertions in a test +even if the first fails. + +### EXAMPLE 4 + +```powershell +$config = [PesterConfiguration]::Default +$config.TestResult.Enabled = $true +Invoke-Pester -Configuration $config +``` + +This example runs all *.Tests.ps1 files in the current directory and its subdirectories. +It uses advanced configuration to enable testresult-output to file. +Access $config.TestResult +to see other testresult options like output path and format and their default values. + +## PARAMETERS + +### -Path + +Aliases Script +Specifies one or more paths to files containing tests. +The value is a path\file +name or name pattern. +Wildcards are permitted. + +```yaml +Type: String[] +Parameter Sets: Simple, Legacy +Aliases: Script + +Required: False +Position: 1 +Default value: . +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ExcludePath + +(Deprecated v4) +Replace with ConfigurationProperty Run.ExcludePath + +```yaml +Type: String[] +Parameter Sets: Simple +Aliases: + +Required: False +Position: Named +Default value: @() +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -TagFilter + +(Deprecated v4) +Aliases Tag, Tags +Replace with ConfigurationProperty Filter.Tag + +```yaml +Type: String[] +Parameter Sets: Simple, Legacy +Aliases: Tags, Tag + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ExcludeTagFilter + +(Deprecated v4) +Replace with ConfigurationProperty Filter.ExcludeTag + +```yaml +Type: String[] +Parameter Sets: Simple, Legacy +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -FullNameFilter + +(Deprecated v4) +Replace with ConfigurationProperty Filter.FullName + +```yaml +Type: String[] +Parameter Sets: Simple, Legacy +Aliases: Name + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -CI + +(Introduced v5) +Enable Test Results and Exit after Run. + +Replace with ConfigurationProperty + TestResult.Enabled = $true + Run.Exit = $true + +Since 5.2.0, this option no longer enables CodeCoverage. +To also enable CodeCoverage use this configuration option: + CodeCoverage.Enabled = $true + +```yaml +Type: SwitchParameter +Parameter Sets: Simple +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Output + +(Deprecated v4) +Replace with ConfigurationProperty Output.Verbosity +Supports Diagnostic, Detailed, Normal, Minimal, None + +Default value is: Normal + +```yaml +Type: String +Parameter Sets: Simple +Aliases: + +Required: False +Position: Named +Default value: Normal +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PassThru + +Replace with ConfigurationProperty Run.PassThru +Returns a custom object (PSCustomObject) that contains the test results. +By default, Invoke-Pester writes to the host program, not to the output stream (stdout). +If you try to save the result in a variable, the variable is empty unless you +use the PassThru parameter. +To suppress the host output, use the Show parameter set to None. + +```yaml +Type: SwitchParameter +Parameter Sets: Simple, Legacy +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Container + +Specifies one or more ContainerInfo-objects that define containers with tests. +ContainerInfo-objects are generated using New-PesterContainer. +Useful for +scenarios where data-driven test are generated, e.g. +parametrized test files. + +```yaml +Type: ContainerInfo[] +Parameter Sets: Simple +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Configuration + +(Introduced v5) +[PesterConfiguration] object for Advanced Configuration + +Pester supports Simple and Advanced Configuration. + +Invoke-Pester -Configuration <PesterConfiguration> [<CommonParameters>] + +Default is New-PesterConfiguration. + +For help on each option see New-PesterConfiguration, or inspect the object it returns. + +```yaml +Type: PesterConfiguration +Parameter Sets: Advanced +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -EnableExit + +(Deprecated v4) +Replace with ConfigurationProperty Run.Exit +Will cause Invoke-Pester to exit with a exit code equal to the number of failed +tests once all tests have been run. +Use this to "fail" a build when any tests fail. + +```yaml +Type: SwitchParameter +Parameter Sets: Legacy +Aliases: + +Required: False +Position: 3 +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -CodeCoverage + +(Deprecated v4) +Replace with ConfigurationProperty CodeCoverage.Enabled = $true +Adds a code coverage report to the Pester tests. +Takes strings or hash table values. +A code coverage report lists the lines of code that did and did not run during +a Pester test. +This report does not tell whether code was tested; only whether +the code ran during the test. +By default, the code coverage report is written to the host program +(like Write-Host). +When you use the PassThru parameter, the custom object +that Invoke-Pester returns has an additional CodeCoverage property that contains +a custom object with detailed results of the code coverage test, including lines +hit, lines missed, and helpful statistics. +However, NUnitXml and JUnitXml output (OutputXML, OutputFormat) do not include +any code coverage information, because it's not supported by the schema. +Enter the path to the files of code under test (not the test file). +Wildcard characters are supported. +If you omit the path, the default is local +directory, not the directory specified by the Script parameter. +Pester test files +are by default excluded from code coverage when a directory is provided. +When you +provide a test file directly using string, code coverage will be measured. +To include +tests in code coverage of a directory, use the dictionary syntax and provide +IncludeTests = $true option, as shown below. +To run a code coverage test only on selected classes, functions or lines in a script, +enter a hash table value with the following keys: +-- Path (P)(mandatory) <string>: Enter one path to the files. +Wildcard characters +are supported, but only one string is permitted. +-- IncludeTests <bool>: Includes code coverage for Pester test files (*.tests.ps1). +Default is false. +One of the following: Class/Function or StartLine/EndLine +-- Class (C) <string>: Enter the class name. +Wildcard characters are +supported, but only one string is permitted. +Default is *. +-- Function (F) <string>: Enter the function name. +Wildcard characters are +supported, but only one string is permitted. +Default is *. +-or- +-- StartLine (S): Performs code coverage analysis beginning with the specified +line. +Default is line 1. +-- EndLine (E): Performs code coverage analysis ending with the specified line. +Default is the last line of the script. + +```yaml +Type: Object[] +Parameter Sets: Legacy +Aliases: + +Required: False +Position: Named +Default value: @() +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -CodeCoverageOutputFile + +(Deprecated v4) +Replace with ConfigurationProperty CodeCoverage.OutputPath +The path where Invoke-Pester will save formatted code coverage results file. +The path must include the location and name of the folder and file name with +a required extension (usually the xml). +If this path is not provided, no file will be generated. + +```yaml +Type: String +Parameter Sets: Legacy +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -CodeCoverageOutputFileEncoding + +(Deprecated v4) +Replace with ConfigurationProperty CodeCoverage.OutputEncoding +Sets the output encoding of CodeCoverageOutputFileFormat +Default is utf8 + +```yaml +Type: String +Parameter Sets: Legacy +Aliases: + +Required: False +Position: Named +Default value: Utf8 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -CodeCoverageOutputFileFormat + +(Deprecated v4) +Replace with ConfigurationProperty CodeCoverage.OutputFormat +The name of a code coverage report file format. +Default value is: JaCoCo. +Currently supported formats are: +- JaCoCo - this XML file format is compatible with Azure Devops, VSTS/TFS + +The ReportGenerator tool can be used to consolidate multiple reports and provide code coverage reporting. +https://github.com/danielpalme/ReportGenerator + +```yaml +Type: String +Parameter Sets: Legacy +Aliases: + +Required: False +Position: Named +Default value: JaCoCo +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Strict + +(Deprecated v4) +Makes Pending and Skipped tests to Failed tests. +Useful for continuous +integration where you need to make sure all tests passed. + +```yaml +Type: SwitchParameter +Parameter Sets: Legacy +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -OutputFile + +(Deprecated v4) +Replace with ConfigurationProperty TestResult.OutputPath +The path where Invoke-Pester will save formatted test results log file. +The path must include the location and name of the folder and file name with +the xml extension. +If this path is not provided, no log will be generated. + +```yaml +Type: String +Parameter Sets: Legacy +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -OutputFormat + +(Deprecated v4) +Replace with ConfigurationProperty TestResult.OutputFormat +The format of output. +Currently NUnitXml and JUnitXml is supported. + +```yaml +Type: String +Parameter Sets: Legacy +Aliases: + +Required: False +Position: Named +Default value: NUnitXml +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Quiet + +(Deprecated v4) +The parameter Quiet is deprecated since Pester v4.0 and will be deleted +in the next major version of Pester. +Please use the parameter Show +with value 'None' instead. +The parameter Quiet suppresses the output that Pester writes to the host program, +including the result summary and CodeCoverage output. +This parameter does not affect the PassThru custom object or the XML output that +is written when you use the Output parameters. + +```yaml +Type: SwitchParameter +Parameter Sets: Legacy +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PesterOption + +(Deprecated v4) +This parameter is ignored in v5, and is only present for backwards compatibility +when migrating from v4. + +Sets advanced options for the test execution. +Enter a PesterOption object, +such as one that you create by using the New-PesterOption cmdlet, or a hash table +in which the keys are option names and the values are option values. +For more information on the options available, see the help for New-PesterOption. + +```yaml +Type: Object +Parameter Sets: Legacy +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Show + +(Deprecated v4) +Replace with ConfigurationProperty Output.Verbosity +Customizes the output Pester writes to the screen. +Available options are None, Default, +Passed, Failed, Pending, Skipped, Inconclusive, Describe, Context, Summary, Header, All, Fails. +The options can be combined to define presets. +ConfigurationProperty Output.Verbosity supports the following values: +None +Minimal +Normal +Detailed +Diagnostic + +Show parameter supports the following parameter values: +None - (None) to write no output to the screen. +All - (Detailed) to write all available information (this is default option). +Default - (Detailed) +Detailed - (Detailed) +Fails - (Normal) to write everything except Passed (but including Describes etc.). +Diagnostic - (Diagnostic) +Normal - (Normal) +Minimal - (Minimal) + +A common setting is also Failed, Summary, to write only failed tests and test summary. +This parameter does not affect the PassThru custom object or the XML output that +is written when you use the Output parameters. + +```yaml +Type: OutputTypes +Parameter Sets: Legacy +Aliases: +Accepted values: None, Default, Passed, Failed, Pending, Skipped, Inconclusive, Describe, Context, Summary, Header, Fails, All + +Required: False +Position: Named +Default value: All +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS + +[https://pester.dev/docs/commands/Invoke-Pester](https://pester.dev/docs/commands/Invoke-Pester) + +[https://pester.dev/docs/quick-start](https://pester.dev/docs/quick-start) + +## VERSION + +*This page was generated using comment-based help in [Pester 5.6.0](https://github.com/pester/pester).* diff --git a/versioned_docs/version-v5/commands/It.mdx b/versioned_docs/version-v5/commands/It.mdx new file mode 100644 index 00000000..54712351 --- /dev/null +++ b/versioned_docs/version-v5/commands/It.mdx @@ -0,0 +1,265 @@ +--- +id: It +title: It +description: Help page for the PowerShell Pester "It" command +keywords: + - PowerShell + - Pester + - Help + - Documentation +hide_title: false +hide_table_of_contents: false +custom_edit_url: null +--- + +:::info This page was generated +Contributions are welcome in [Pester-repo](https://github.com/pester/pester). +::: + +## SYNOPSIS + +Validates the results of a test inside of a Describe block. + +## SYNTAX + +### Normal (Default) + +```powershell +It [-Name] [[-Test] ] [-ForEach ] [-Tag ] [] +``` + +### Pending + +```powershell +It [-Name] [[-Test] ] [-ForEach ] [-Tag ] [-Pending] + [] +``` + +### Skip + +```powershell +It [-Name] [[-Test] ] [-ForEach ] [-Tag ] [-Skip] + [] +``` + +## DESCRIPTION + +The It command is intended to be used inside of a Describe or Context Block. +If you are familiar with the AAA pattern (Arrange-Act-Assert), the body of +the It block is the appropriate location for an assert. +The convention is to +assert a single expectation for each It block. +The code inside of the It block +should throw a terminating error if the expectation of the test is not met and +thus cause the test to fail. +The name of the It block should expressively state +the expectation of the test. + +In addition to using your own logic to test expectations and throw exceptions, +you may also use Pester's Should command to perform assertions in plain language. + +You can intentionally mark It block result as inconclusive by using Set-ItResult -Inconclusive +command as the first tested statement in the It block. + +## EXAMPLES + +### EXAMPLE 1 + +```powershell +BeforeAll { + function Add-Numbers($a, $b) { + return $a + $b + } +} + +Describe "Add-Numbers" { + It "adds positive numbers" { + $sum = Add-Numbers 2 3 + $sum | Should -Be 5 + } + + It "adds negative numbers" { + $sum = Add-Numbers (-2) (-2) + $sum | Should -Be (-4) + } + + It "adds one negative number to positive number" { + $sum = Add-Numbers (-2) 2 + $sum | Should -Be 0 + } + + It "concatenates strings if given strings" { + $sum = Add-Numbers two three + $sum | Should -Be "twothree" + } +} +``` + +Example of a simple Pester file. +It-blocks are used to define the different tests. + +### EXAMPLE 2 + +```powershell +function Add-Numbers($a, $b) { + return $a + $b +} + +Describe "Add-Numbers" { + $testCases = @( + @{ a = 2; b = 3; expectedResult = 5 } + @{ a = -2; b = -2; expectedResult = -4 } + @{ a = -2; b = 2; expectedResult = 0 } + @{ a = 'two'; b = 'three'; expectedResult = 'twothree' } + ) + + It 'Correctly adds and to get ' -ForEach $testCases { + $sum = Add-Numbers $a $b + $sum | Should -Be $expectedResult + } +} +``` + +Using It with -ForEach to run the same tests with different parameters and expected results. +Each hashtable in the `$testCases`-array generates one tests to a total of four. +Each key-value pair in the +current hashtable are made available as variables inside It. + +## PARAMETERS + +### -Name + +An expressive phrase describing the expected test outcome. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Test + +The script block that should throw an exception if the +expectation of the test is not met.If you are following the +AAA pattern (Arrange-Act-Assert), this typically holds the +Assert. + +```yaml +Type: ScriptBlock +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ForEach + +(Formerly called TestCases.) Optional array of hashtable (or any IDictionary) objects. +If this parameter is used, Pester will call the test script block once for each table in +the ForEach array, splatting the dictionary to the test script block as input. +If you want +the name of the test to appear differently for each test case, you can embed tokens into the Name +parameter with the syntax 'Adds numbers <A> and <B>' (assuming you have keys named A and B +in your ForEach hashtables.) + +```yaml +Type: Object[] +Parameter Sets: (All) +Aliases: TestCases + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Tag + +Optional parameter containing an array of strings. +When calling Invoke-Pester, +it is possible to include or exclude tests containing the same Tag. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Pending + +Use this parameter to explicitly mark the test as work-in-progress/not implemented/pending when you +need to distinguish a test that fails because it is not finished yet from a tests +that fail as a result of changes being made in the code base. +An empty test, that is a +test that contains nothing except whitespace or comments is marked as Pending by default. + +```yaml +Type: SwitchParameter +Parameter Sets: Pending +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Skip + +Use this parameter to explicitly mark the test to be skipped. +This is preferable to temporarily +commenting out a test, because the test remains listed in the output. + +```yaml +Type: SwitchParameter +Parameter Sets: Skip +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS + +[https://pester.dev/docs/commands/It](https://pester.dev/docs/commands/It) + +[https://pester.dev/docs/commands/Describe](https://pester.dev/docs/commands/Describe) + +[https://pester.dev/docs/commands/Context](https://pester.dev/docs/commands/Context) + +[https://pester.dev/docs/commands/Set-ItResult](https://pester.dev/docs/commands/Set-ItResult) + +## VERSION + +*This page was generated using comment-based help in [Pester 5.6.0](https://github.com/pester/pester).* diff --git a/versioned_docs/version-v5/commands/Mock.mdx b/versioned_docs/version-v5/commands/Mock.mdx new file mode 100644 index 00000000..5b75de86 --- /dev/null +++ b/versioned_docs/version-v5/commands/Mock.mdx @@ -0,0 +1,342 @@ +--- +id: Mock +title: Mock +description: Help page for the PowerShell Pester "Mock" command +keywords: + - PowerShell + - Pester + - Help + - Documentation +hide_title: false +hide_table_of_contents: false +custom_edit_url: null +--- + +:::info This page was generated +Contributions are welcome in [Pester-repo](https://github.com/pester/pester). +::: + +## SYNOPSIS + +Mocks the behavior of an existing command with an alternate +implementation. + +## SYNTAX + +```powershell +Mock [[-CommandName] ] [[-MockWith] ] [-Verifiable] [[-ParameterFilter] ] + [[-ModuleName] ] [[-RemoveParameterType] ] [[-RemoveParameterValidation] ] + [] +``` + +## DESCRIPTION + +This creates new behavior for any existing command within the scope of a +Describe or Context block. +The function allows you to specify a script block +that will become the command's new behavior. + +Optionally, you may create a Parameter Filter which will examine the +parameters passed to the mocked command and will invoke the mocked +behavior only if the values of the parameter values pass the filter. +If +they do not, the original command implementation will be invoked instead +of a mock. + +You may create multiple mocks for the same command, each using a different +ParameterFilter. +ParameterFilters will be evaluated in reverse order of +their creation. +The last one created will be the first to be evaluated. +The mock of the first filter to pass will be used. +The exception to this +rule are Mocks with no filters. +They will always be evaluated last since +they will act as a "catch all" mock. + +Mocks can be marked Verifiable. +If so, the Should -InvokeVerifiable command +can be used to check if all Verifiable mocks were actually called. +If any +verifiable mock is not called, Should -InvokeVerifiable will throw an +exception and indicate all mocks not called. + +If you wish to mock commands that are called from inside a script or manifest +module, you can do so by using the -ModuleName parameter to the Mock command. +This injects the mock into the specified module. +If you do not specify a +module name, the mock will be created in the same scope as the test script. +You may mock the same command multiple times, in different scopes, as needed. +Each module's mock maintains a separate call history and verified status. + +## EXAMPLES + +### EXAMPLE 1 + +```powershell +Mock Get-ChildItem { return @{FullName = "A_File.TXT"} } +``` + +Using this Mock, all calls to Get-ChildItem will return a hashtable with a FullName property returning "A_File.TXT" + +### EXAMPLE 2 + +```powershell +Mock Get-ChildItem { return @{FullName = "A_File.TXT"} } -ParameterFilter { $Path -and $Path.StartsWith($env:temp) } +``` + +This Mock will only be applied to Get-ChildItem calls within the user's temp directory. + +### EXAMPLE 3 + +```powershell +Mock Set-Content {} -Verifiable -ParameterFilter { $Path -eq "some_path" -and $Value -eq "Expected Value" } +``` + +When this mock is used, if the Mock is never invoked and Should -InvokeVerifiable is called, an exception will be thrown. +The command behavior will do nothing since the ScriptBlock is empty. + +### EXAMPLE 4 + +```powershell +Mock Get-ChildItem { return @{FullName = "A_File.TXT"} } -ParameterFilter { $Path -and $Path.StartsWith($env:temp\1) } +Mock Get-ChildItem { return @{FullName = "B_File.TXT"} } -ParameterFilter { $Path -and $Path.StartsWith($env:temp\2) } +Mock Get-ChildItem { return @{FullName = "C_File.TXT"} } -ParameterFilter { $Path -and $Path.StartsWith($env:temp\3) } +``` + +Multiple mocks of the same command may be used. +The parameter filter determines which is invoked. +Here, if Get-ChildItem is called on the "2" directory of the temp folder, then B_File.txt will be returned. + +### EXAMPLE 5 + +```powershell +Mock Get-ChildItem { return @{FullName="B_File.TXT"} } -ParameterFilter { $Path -eq "$env:temp\me" } +Mock Get-ChildItem { return @{FullName="A_File.TXT"} } -ParameterFilter { $Path -and $Path.StartsWith($env:temp) } + +Get-ChildItem $env:temp\me +``` + +Here, both mocks could apply since both filters will pass. +A_File.TXT will be returned because it was the most recent Mock created. + +### EXAMPLE 6 + +```powershell +Mock Get-ChildItem { return @{FullName = "B_File.TXT"} } -ParameterFilter { $Path -eq "$env:temp\me" } +Mock Get-ChildItem { return @{FullName = "A_File.TXT"} } + +Get-ChildItem c:\windows +``` + +Here, A_File.TXT will be returned. +Since no filter was specified, it will apply to any call to Get-ChildItem that does not pass another filter. + +### EXAMPLE 7 + +```powershell +Mock Get-ChildItem { return @{FullName = "B_File.TXT"} } -ParameterFilter { $Path -eq "$env:temp\me" } +Mock Get-ChildItem { return @{FullName = "A_File.TXT"} } + +Get-ChildItem $env:temp\me +``` + +Here, B_File.TXT will be returned. +Even though the filterless mock was created more recently. +This illustrates that filterless Mocks are always evaluated last regardless of their creation order. + +### EXAMPLE 8 + +```powershell +Mock Get-ChildItem { return @{FullName = "A_File.TXT"} } -ModuleName MyTestModule +``` + +Using this Mock, all calls to Get-ChildItem from within the MyTestModule module +will return a hashtable with a FullName property returning "A_File.TXT" + +### EXAMPLE 9 + +```powershell +Get-Module -Name ModuleMockExample | Remove-Module +New-Module -Name ModuleMockExample -ScriptBlock { + function Hidden { "Internal Module Function" } + function Exported { Hidden } + +Export-ModuleMember -Function Exported +} | Import-Module -Force + +Describe "ModuleMockExample" { + It "Hidden function is not directly accessible outside the module" { + { Hidden } | Should -Throw + } + + It "Original Hidden function is called" { + Exported | Should -Be "Internal Module Function" + } + + It "Hidden is replaced with our implementation" { + Mock Hidden { "Mocked" } -ModuleName ModuleMockExample + Exported | Should -Be "Mocked" + } +} +``` + +This example shows how calls to commands made from inside a module can be +mocked by using the -ModuleName parameter. + +## PARAMETERS + +### -CommandName + +The name of the command to be mocked. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -MockWith + +A ScriptBlock specifying the behavior that will be used to mock CommandName. +The default is an empty ScriptBlock. +NOTE: Do not specify param or dynamicparam blocks in this script block. +These will be injected automatically based on the signature of the command +being mocked, and the MockWith script block can contain references to the +mocked commands parameter variables. + +```yaml +Type: ScriptBlock +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: {} +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Verifiable + +When this is set, the mock will be checked when Should -InvokeVerifiable is +called. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ParameterFilter + +An optional filter to limit mocking behavior only to usages of +CommandName where the values of the parameters passed to the command +pass the filter. + +This ScriptBlock must return a boolean value. +See examples for usage. + +```yaml +Type: ScriptBlock +Parameter Sets: (All) +Aliases: + +Required: False +Position: 3 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ModuleName + +Optional string specifying the name of the module where this command +is to be mocked. +This should be a module that _calls_ the mocked +command; it doesn't necessarily have to be the same module which +originally implemented the command. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 4 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -RemoveParameterType + +Optional list of parameter names that should use Object as the parameter +type instead of the parameter type defined by the function. +This relaxes the +type requirements and allows some strongly typed functions to be mocked +more easily. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: 5 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -RemoveParameterValidation + +Optional list of parameter names in the original command +that should not have any validation rules applied. +This relaxes the +validation requirements, and allows functions that are strict about their +parameter validation to be mocked more easily. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: 6 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS + +[https://pester.dev/docs/commands/Mock](https://pester.dev/docs/commands/Mock) + +[https://pester.dev/docs/usage/mocking](https://pester.dev/docs/usage/mocking) + +## VERSION + +*This page was generated using comment-based help in [Pester 5.6.0](https://github.com/pester/pester).* diff --git a/versioned_docs/version-v5/commands/New-Fixture.mdx b/versioned_docs/version-v5/commands/New-Fixture.mdx new file mode 100644 index 00000000..2fde74ae --- /dev/null +++ b/versioned_docs/version-v5/commands/New-Fixture.mdx @@ -0,0 +1,145 @@ +--- +id: New-Fixture +title: New-Fixture +description: Help page for the PowerShell Pester "New-Fixture" command +keywords: + - PowerShell + - Pester + - Help + - Documentation +hide_title: false +hide_table_of_contents: false +custom_edit_url: null +--- + +:::info This page was generated +Contributions are welcome in [Pester-repo](https://github.com/pester/pester). +::: + +## SYNOPSIS + +This function generates two scripts, one that defines a function +and another one that contains its tests. + +## SYNTAX + +```powershell +New-Fixture [-Name] [[-Path] ] [] +``` + +## DESCRIPTION + +This function generates two scripts, one that defines a function +and another one that contains its tests. +The files are by default +placed in the current directory and are called and populated as such: + +The script defining the function: .\Clean.ps1: + +```powershell +function Clean { + throw [NotImplementedException]'Clean is not implemented.' +} +``` + +The script containing the example test .\Clean.Tests.ps1: + +```powershell +BeforeAll { + . +$PSCommandPath.Replace('.Tests.ps1', '.ps1') +} + +Describe "Clean" { + It "Returns expected output" { + Clean | Should -Be "YOUR_EXPECTED_VALUE" + } +} +``` + +## EXAMPLES + +### EXAMPLE 1 + +```powershell +New-Fixture -Name Clean +``` + +Creates the scripts in the current directory. + +### EXAMPLE 2 + +```powershell +New-Fixture Clean C:\Projects\Cleaner +``` + +Creates the scripts in the C:\Projects\Cleaner directory. + +### EXAMPLE 3 + +```powershell +New-Fixture -Name Clean -Path Cleaner +``` + +Creates a new folder named Cleaner in the current directory and creates the scripts in it. + +## PARAMETERS + +### -Name + +Defines the name of the function and the name of the test to be created. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Path + +Defines path where the test and the function should be created, you can use full or relative path. +If the parameter is not specified the scripts are created in the current directory. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: $PWD +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS + +[https://pester.dev/docs/commands/New-Fixture](https://pester.dev/docs/commands/New-Fixture) + +[https://pester.dev/docs/commands/Describe](https://pester.dev/docs/commands/Describe) + +[https://pester.dev/docs/commands/Context](https://pester.dev/docs/commands/Context) + +[https://pester.dev/docs/commands/It](https://pester.dev/docs/commands/It) + +[https://pester.dev/docs/commands/Should](https://pester.dev/docs/commands/Should) + +## VERSION + +*This page was generated using comment-based help in [Pester 5.6.0](https://github.com/pester/pester).* diff --git a/versioned_docs/version-v5/commands/New-MockObject.mdx b/versioned_docs/version-v5/commands/New-MockObject.mdx new file mode 100644 index 00000000..5cf702a9 --- /dev/null +++ b/versioned_docs/version-v5/commands/New-MockObject.mdx @@ -0,0 +1,197 @@ +--- +id: New-MockObject +title: New-MockObject +description: Help page for the PowerShell Pester "New-MockObject" command +keywords: + - PowerShell + - Pester + - Help + - Documentation +hide_title: false +hide_table_of_contents: false +custom_edit_url: null +--- + +:::info This page was generated +Contributions are welcome in [Pester-repo](https://github.com/pester/pester). +::: + +## SYNOPSIS + +This function instantiates a .NET object from a type. + +## SYNTAX + +### Type (Default) + +```powershell +New-MockObject [-Type] [-Properties ] [-Methods ] [-MethodHistoryPrefix ] + [] +``` + +### InputObject + +```powershell +New-MockObject -InputObject [-Properties ] [-Methods ] + [-MethodHistoryPrefix ] [] +``` + +## DESCRIPTION + +Using the New-MockObject you can mock an object based on .NET type. + +An .NET assembly for the particular type must be available in the system and loaded. + +## EXAMPLES + +### EXAMPLE 1 + +```powershell +$obj = New-MockObject -Type 'System.Diagnostics.Process' +$obj.GetType().FullName + System.Diagnostics.Process +``` + +Creates a mock of a process-object with default property-values. + +### EXAMPLE 2 + +```powershell +$obj = New-MockObject -Type 'System.Diagnostics.Process' -Properties @{ Id = 123 } +``` + +Create a mock of a process-object with the Id-property specified. + +### EXAMPLE 3 + +```powershell +$obj = New-MockObject -Type 'System.Diagnostics.Process' -Methods @{ Kill = { param($entireProcessTree) "killed" } } +$obj.Kill() +$obj.Kill($true) +$obj.Kill($false) + +$obj._Kill + +Call Arguments +---- --------- + 1 {} + 2 {True} + 3 {False} +``` + +Create a mock of a process-object and mocks the object's `Kill()`-method. +The mocked method will keep a history +of any call and the associated arguments in a property named `_Kill` + +## PARAMETERS + +### -Type + +The .NET type to create. +This creates the object without calling any of its constructors or initializers. +Use this to instantiate an object that does not have a public constructor. +If your object has a constructor, or is giving you errors, try using the constructor and provide the object using the InputObject parameter to decorate it. + +```yaml +Type: Type +Parameter Sets: Type +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -InputObject + +An already constructed object to decorate. +Use `New-Object` or `[typeName]::new()` to create it. + +```yaml +Type: Object +Parameter Sets: InputObject +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Properties + +Properties to define, specified as a hashtable, in format `@{ PropertyName = value }`. + +```yaml +Type: Hashtable +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Methods + +Methods to define, specified as a hashtable, in format `@{ MethodName = scriptBlock }`. + +ScriptBlock can define param block, and it will receive arguments that were provided to the function call based on order. + +Method overloads are not supported because ScriptMethods are used to decorate the object, and ScriptMethods do not support method overloads. + +For each method a property named `_MethodName` (if using default `-MethodHistoryPrefix`) is defined which holds history of the invocations of the method and the arguments that were provided. + +```yaml +Type: Hashtable +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -MethodHistoryPrefix + +Prefix for the history-property created for each mocked method. +Default is '_' which would create the property '_MethodName'. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: _ +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS + +[https://pester.dev/docs/commands/New-MockObject](https://pester.dev/docs/commands/New-MockObject) + +[https://pester.dev/docs/usage/mocking](https://pester.dev/docs/usage/mocking) + +## VERSION + +*This page was generated using comment-based help in [Pester 5.6.0](https://github.com/pester/pester).* diff --git a/versioned_docs/version-v5/commands/New-PesterConfiguration.mdx b/versioned_docs/version-v5/commands/New-PesterConfiguration.mdx new file mode 100644 index 00000000..1ce368fc --- /dev/null +++ b/versioned_docs/version-v5/commands/New-PesterConfiguration.mdx @@ -0,0 +1,275 @@ +--- +id: New-PesterConfiguration +title: New-PesterConfiguration +description: Help page for the PowerShell Pester "New-PesterConfiguration" command +keywords: + - PowerShell + - Pester + - Help + - Documentation +hide_title: false +hide_table_of_contents: false +custom_edit_url: null +--- + +:::info This page was generated +Contributions are welcome in [Pester-repo](https://github.com/pester/pester). +::: + +## SYNOPSIS + +Creates a new PesterConfiguration object for advanced configuration of Invoke-Pester. + +## SYNTAX + +```powershell +New-PesterConfiguration [[-Hashtable] ] [] +``` + +## DESCRIPTION + +The New-PesterConfiguration function creates a new PesterConfiguration-object +to enable advanced configurations for runnings tests using Invoke-Pester. + +Without parameters, the function generates a configuration-object with default +options. +The returned PesterConfiguration-object can be modified to suit your +requirements. + +Calling New-PesterConfiguration is equivalent to calling [PesterConfiguration]::Default which was used in early versions of Pester 5. + +Sections and options: + +``` +Run: + Path: Directories to be searched for tests, paths directly to test files, or combination of both. + Default value: @('.') + + ExcludePath: Directories or files to be excluded from the run. + Default value: @() + + ScriptBlock: ScriptBlocks containing tests to be executed. + Default value: @() + + Container: ContainerInfo objects containing tests to be executed. + Default value: @() + + TestExtension: Filter used to identify test files. + Default value: '.Tests.ps1' + + Exit: Exit with non-zero exit code when the test run fails. +Exit code is always set to `$LASTEXITCODE` even when this option is `$false`. +When used together with Throw, throwing an exception is preferred. + Default value: $false + + Throw: Throw an exception when test run fails. +When used together with Exit, throwing an exception is preferred. + Default value: $false + + PassThru: Return result object to the pipeline after finishing the test run. + Default value: $false + + SkipRun: Runs the discovery phase but skips run. +Use it with PassThru to get object populated with all tests. + Default value: $false + + SkipRemainingOnFailure: Skips remaining tests after failure for selected scope, options are None, Run, Container and Block. + Default value: 'None' + +Filter: + Tag: Tags of Describe, Context or It to be run. + Default value: @() + + ExcludeTag: Tags of Describe, Context or It to be excluded from the run. + Default value: @() + + Line: Filter by file and scriptblock start line, useful to run parsed tests programmatically to avoid problems with expanded names. +Example: 'C:\tests\file1.Tests.ps1:37' + Default value: @() + + ExcludeLine: Exclude by file and scriptblock start line, takes precedence over Line. + Default value: @() + + FullName: Full name of test with -like wildcards, joined by dot. +Example: '*.describe Get-Item.test1' + Default value: @() + +CodeCoverage: + Enabled: Enable CodeCoverage. + Default value: $false + + OutputFormat: Format to use for code coverage report. +Possible values: JaCoCo, CoverageGutters + Default value: 'JaCoCo' + + OutputPath: Path relative to the current directory where code coverage report is saved. + Default value: 'coverage.xml' + + OutputEncoding: Encoding of the output file. + Default value: 'UTF8' + + Path: Directories or files to be used for code coverage, by default the Path(s) from general settings are used, unless overridden here. + Default value: @() + + ExcludeTests: Exclude tests from code coverage. +This uses the TestFilter from general configuration. + Default value: $true + + RecursePaths: Will recurse through directories in the Path option. + Default value: $true + + CoveragePercentTarget: Target percent of code coverage that you want to achieve, default 75%. + Default value: 75 + + UseBreakpoints: EXPERIMENTAL: When false, use Profiler based tracer to do CodeCoverage instead of using breakpoints. + Default value: $true + + SingleHitBreakpoints: Remove breakpoint when it is hit. + Default value: $true + +TestResult: + Enabled: Enable TestResult. + Default value: $false + + OutputFormat: Format to use for test result report. +Possible values: NUnitXml, NUnit2.5, NUnit3 or JUnitXml + Default value: 'NUnitXml' + + OutputPath: Path relative to the current directory where test result report is saved. + Default value: 'testResults.xml' + + OutputEncoding: Encoding of the output file. + Default value: 'UTF8' + + TestSuiteName: Set the name assigned to the root 'test-suite' element. + Default value: 'Pester' + +Should: + ErrorAction: Controls if Should throws on error. +Use 'Stop' to throw on error, or 'Continue' to fail at the end of the test. + Default value: 'Stop' + +Debug: + ShowFullErrors: Show full errors including Pester internal stack. +This property is deprecated, and if set to true it will override Output.StackTraceVerbosity to 'Full'. + Default value: $false + + WriteDebugMessages: Write Debug messages to screen. + Default value: $false + + WriteDebugMessagesFrom: Write Debug messages from a given source, WriteDebugMessages must be set to true for this to work. +You can use like wildcards to get messages from multiple sources, as well as * to get everything. + Default value: @('Discovery', 'Skip', 'Mock', 'CodeCoverage') + + ShowNavigationMarkers: Write paths after every block and test, for easy navigation in VSCode. + Default value: $false + + ReturnRawResultObject: Returns unfiltered result object, this is for development only. +Do not rely on this object for additional properties, non-public properties will be renamed without previous notice. + Default value: $false + +Output: + Verbosity: The verbosity of output, options are None, Normal, Detailed and Diagnostic. + Default value: 'Normal' + + StackTraceVerbosity: The verbosity of stacktrace output, options are None, FirstLine, Filtered and Full. + Default value: 'Filtered' + + CIFormat: The CI format of error output in build logs, options are None, Auto, AzureDevops and GithubActions. + Default value: 'Auto' + + CILogLevel: The CI log level in build logs, options are Error and Warning. + Default value: 'Error' + + RenderMode: The mode used to render console output, options are Auto, Ansi, ConsoleColor and Plaintext. + Default value: 'Auto' + +TestDrive: + Enabled: Enable TestDrive. + Default value: $true + +TestRegistry: + Enabled: Enable TestRegistry. + Default value: $true +``` + +## EXAMPLES + +### EXAMPLE 1 + +```powershell +$config = New-PesterConfiguration +$config.Run.PassThru = $true + +Invoke-Pester -Configuration $config +``` + +Creates a default PesterConfiguration-object and changes the Run.PassThru option +to return the result object after the test run. +The configuration object is +provided to Invoke-Pester to alter the default behaviour. + +### EXAMPLE 2 + +```powershell +$MyOptions = @{ + Run = @{ # Run configuration. + PassThru = $true # Return result object after finishing the test run. + } + Filter = @{ # Filter configuration + Tag = "Core","Integration" # Run only Describe/Context/It-blocks with 'Core' or 'Integration' tags + } +} + +$config = New-PesterConfiguration -Hashtable $MyOptions + +Invoke-Pester -Configuration $config +``` + +A hashtable is created with custom options and passed to the New-PesterConfiguration to merge +with the default configuration. +The options in the hashtable will override the default values. +The configuration object is then provided to Invoke-Pester to begin the test run using +the new configuration. + +## PARAMETERS + +### -Hashtable + +Override the default values for the options defined in the provided dictionary/hashtable. +See Description in this help or inspect a PesterConfiguration-object to learn about the schema and +available options. + +```yaml +Type: IDictionary +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS + +[https://pester.dev/docs/commands/New-PesterConfiguration](https://pester.dev/docs/commands/New-PesterConfiguration) + +[https://pester.dev/docs/usage/Configuration](https://pester.dev/docs/usage/Configuration) + +[https://pester.dev/docs/commands/Invoke-Pester](https://pester.dev/docs/commands/Invoke-Pester) + +## VERSION + +*This page was generated using comment-based help in [Pester 5.6.0](https://github.com/pester/pester).* diff --git a/versioned_docs/version-v5/commands/New-PesterContainer.mdx b/versioned_docs/version-v5/commands/New-PesterContainer.mdx new file mode 100644 index 00000000..127f5249 --- /dev/null +++ b/versioned_docs/version-v5/commands/New-PesterContainer.mdx @@ -0,0 +1,155 @@ +--- +id: New-PesterContainer +title: New-PesterContainer +description: Help page for the PowerShell Pester "New-PesterContainer" command +keywords: + - PowerShell + - Pester + - Help + - Documentation +hide_title: false +hide_table_of_contents: false +custom_edit_url: null +--- + +:::info This page was generated +Contributions are welcome in [Pester-repo](https://github.com/pester/pester). +::: + +## SYNOPSIS + +Generates ContainerInfo-objects used as for Invoke-Pester -Container + +## SYNTAX + +### Path (Default) + +```powershell +New-PesterContainer -Path [-Data ] [] +``` + +### ScriptBlock + +```powershell +New-PesterContainer -ScriptBlock [-Data ] [] +``` + +## DESCRIPTION + +Pester 5 supports running tests files and scriptblocks using parameter-input. +To use this feature, Invoke-Pester expects one or more ContainerInfo-objects +created using this function, that specify test containers in the form of paths +to the test files or scriptblocks containing the tests directly. + +A optional Data-dictionary can be provided to supply the containers with any +required parameter-values. +This is useful in when tests are generated dynamically +based on parameter-input. +This method enables complex test-solutions while being +able to re-use a lot of test-code. + +## EXAMPLES + +### EXAMPLE 1 + +```powershell +$container = New-PesterContainer -Path 'CodingStyle.Tests.ps1' -Data @{ File = "Get-Emoji.ps1" } +Invoke-Pester -Container $container +``` + +This example runs Pester using a generated ContainerInfo-object referencing a file and +required parameters that's provided to the test-file during execution. + +### EXAMPLE 2 + +```powershell +$sb = { + Describe 'Testing New-PesterContainer' { + It 'Useless test' { + "foo" | Should -Not -Be "bar" + } + } +} +$container = New-PesterContainer -ScriptBlock $sb +Invoke-Pester -Container $container +``` + +This example runs Pester against a scriptblock. +New-PesterContainer is used to generate +the required ContainerInfo-object that enables us to do this directly. + +## PARAMETERS + +### -Path + +Specifies one or more paths to files containing tests. +The value is a path\file +name or name pattern. +Wildcards are permitted. + +```yaml +Type: String[] +Parameter Sets: Path +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ScriptBlock + +Specifies one or more scriptblocks containing tests. + +```yaml +Type: ScriptBlock[] +Parameter Sets: ScriptBlock +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Data + +Allows a dictionary to be provided with parameter-values that should be used during +execution of the test containers defined in Path or ScriptBlock. + +```yaml +Type: IDictionary[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS + +[https://pester.dev/docs/commands/New-PesterContainer](https://pester.dev/docs/commands/New-PesterContainer) + +[https://pester.dev/docs/commands/Invoke-Pester](https://pester.dev/docs/commands/Invoke-Pester) + +[https://pester.dev/docs/usage/data-driven-tests](https://pester.dev/docs/usage/data-driven-tests) + +## VERSION + +*This page was generated using comment-based help in [Pester 5.6.0](https://github.com/pester/pester).* diff --git a/versioned_docs/version-v5/commands/Set-ItResult.mdx b/versioned_docs/version-v5/commands/Set-ItResult.mdx new file mode 100644 index 00000000..3728c807 --- /dev/null +++ b/versioned_docs/version-v5/commands/Set-ItResult.mdx @@ -0,0 +1,166 @@ +--- +id: Set-ItResult +title: Set-ItResult +description: Help page for the PowerShell Pester "Set-ItResult" command +keywords: + - PowerShell + - Pester + - Help + - Documentation +hide_title: false +hide_table_of_contents: false +custom_edit_url: null +--- + +:::info This page was generated +Contributions are welcome in [Pester-repo](https://github.com/pester/pester). +::: + +## SYNOPSIS + +Set-ItResult is used inside the It block to explicitly set the test result + +## SYNTAX + +### Inconclusive + +```powershell +Set-ItResult [-Inconclusive] [-Because ] [] +``` + +### Pending + +```powershell +Set-ItResult [-Pending] [-Because ] [] +``` + +### Skipped + +```powershell +Set-ItResult [-Skipped] [-Because ] [] +``` + +## DESCRIPTION + +Sometimes a test shouldn't be executed, sometimes the condition cannot be evaluated. +By default such tests would typically fail and produce a big red message. +Using Set-ItResult it is possible to set the result from the inside of the It script +block to either inconclusive, pending or skipped. + +As of Pester 5, there is no "Inconclusive" or "Pending" test state, so all tests will now go to state skipped, +however the test result notes will include information about being inconclusive or testing to keep this command +backwards compatible + +## EXAMPLES + +### EXAMPLE 1 + +```powershell +Describe "Example" { + It "Inconclusive test" { + Set-ItResult -Inconclusive -Because "we want it to be inconclusive" + } + It "Skipped test" { + Set-ItResult -Skipped -Because "we want it to be skipped" + } +} +``` + +the output should be + +``` +Describing Example + [?] Inconclusive test is inconclusive, because we want it to be inconclusive 35ms (32ms|3ms) + [!] Skipped test is skipped, because we want it to be skipped 3ms (2ms|1ms) +Tests completed in 78ms +Tests Passed: 0, Failed: 0, Skipped: 1, Inconclusive: 1, NotRun: 0 +``` + +## PARAMETERS + +### -Inconclusive + +Sets the test result to inconclusive. +Cannot be used at the same time as -Pending or -Skipped + +```yaml +Type: SwitchParameter +Parameter Sets: Inconclusive +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Pending + +**DEPRECATED** Sets the test result to pending. +Cannot be used at the same time as -Inconclusive or -Skipped + +```yaml +Type: SwitchParameter +Parameter Sets: Pending +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Skipped + +Sets the test result to skipped. +Cannot be used at the same time as -Inconclusive or -Pending + +```yaml +Type: SwitchParameter +Parameter Sets: Skipped +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Because + +Similarly to failing tests, skipped and inconclusive tests should have reason. +It allows +to provide information to the user why the test is neither successful nor failed. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS + +[https://pester.dev/docs/commands/Set-ItResult](https://pester.dev/docs/commands/Set-ItResult) + +## VERSION + +*This page was generated using comment-based help in [Pester 5.6.0](https://github.com/pester/pester).* diff --git a/versioned_docs/version-v5/commands/Should.mdx b/versioned_docs/version-v5/commands/Should.mdx new file mode 100644 index 00000000..2f5fef43 --- /dev/null +++ b/versioned_docs/version-v5/commands/Should.mdx @@ -0,0 +1,1184 @@ +--- +id: Should +title: Should +description: Help page for the PowerShell Pester "Should" command +keywords: + - PowerShell + - Pester + - Help + - Documentation +hide_title: false +hide_table_of_contents: false +custom_edit_url: null +--- + +:::info This page was generated +Contributions are welcome in [Pester-repo](https://github.com/pester/pester). +::: + +## SYNOPSIS + +Should is a keyword that is used to define an assertion inside an It block. + +## SYNTAX + +### Be + +```powershell +Should [[-ActualValue] ] [-Be] [-Not] [-ExpectedValue ] [-Because ] + [] +``` + +### BeExactly + +```powershell +Should [[-ActualValue] ] [-Not] [-ExpectedValue ] [-Because ] [-BeExactly] + [] +``` + +### BeGreaterThan + +```powershell +Should [[-ActualValue] ] [-Not] [-ExpectedValue ] [-Because ] [-BeGreaterThan] + [] +``` + +### BeLessOrEqual + +```powershell +Should [[-ActualValue] ] [-Not] [-ExpectedValue ] [-Because ] [-BeLessOrEqual] + [] +``` + +### BeIn + +```powershell +Should [[-ActualValue] ] [-Not] [-ExpectedValue ] [-Because ] [-BeIn] + [] +``` + +### BeLessThan + +```powershell +Should [[-ActualValue] ] [-Not] [-ExpectedValue ] [-Because ] [-BeLessThan] + [] +``` + +### BeGreaterOrEqual + +```powershell +Should [[-ActualValue] ] [-Not] [-ExpectedValue ] [-Because ] [-BeGreaterOrEqual] + [] +``` + +### BeLike + +```powershell +Should [[-ActualValue] ] [-Not] [-ExpectedValue ] [-Because ] [-BeLike] + [] +``` + +### BeLikeExactly + +```powershell +Should [[-ActualValue] ] [-Not] [-ExpectedValue ] [-Because ] [-BeLikeExactly] + [] +``` + +### BeNullOrEmpty + +```powershell +Should [[-ActualValue] ] [-Not] [-Because ] [-BeNullOrEmpty] [] +``` + +### BeOfType + +```powershell +Should [[-ActualValue] ] [-Not] [-Because ] [-BeOfType] [-ExpectedType ] + [] +``` + +### BeTrue + +```powershell +Should [[-ActualValue] ] [-Not] [-Because ] [-BeTrue] [] +``` + +### BeFalse + +```powershell +Should [[-ActualValue] ] [-Not] [-Because ] [-BeFalse] [] +``` + +### Contain + +```powershell +Should [[-ActualValue] ] [-Not] [-ExpectedValue ] [-Because ] [-Contain] + [] +``` + +### Exist + +```powershell +Should [[-ActualValue] ] [-Not] [-Because ] [-Exist] [] +``` + +### FileContentMatch + +```powershell +Should [[-ActualValue] ] [-Not] [-Because ] [-FileContentMatch] [-ExpectedContent ] + [] +``` + +### FileContentMatchExactly + +```powershell +Should [[-ActualValue] ] [-Not] [-Because ] [-ExpectedContent ] + [-FileContentMatchExactly] [] +``` + +### FileContentMatchMultiline + +```powershell +Should [[-ActualValue] ] [-Not] [-Because ] [-ExpectedContent ] + [-FileContentMatchMultiline] [] +``` + +### FileContentMatchMultilineExactly + +```powershell +Should [[-ActualValue] ] [-Not] [-Because ] [-ExpectedContent ] + [-FileContentMatchMultilineExactly] [] +``` + +### HaveCount + +```powershell +Should [[-ActualValue] ] [-Not] [-ExpectedValue ] [-Because ] [-HaveCount] + [] +``` + +### HaveParameter + +```powershell +Should [[-ActualValue] ] [-Not] [-Because ] [-HaveParameter] [-ParameterName ] + [-Type ] [-DefaultValue ] [-Mandatory] [-InParameterSet ] [-HasArgumentCompleter] + [-Alias ] [] +``` + +### Match + +```powershell +Should [[-ActualValue] ] [-Not] [-Because ] [-Match] [-RegularExpression ] + [] +``` + +### MatchExactly + +```powershell +Should [[-ActualValue] ] [-Not] [-Because ] [-RegularExpression ] [-MatchExactly] + [] +``` + +### Throw + +```powershell +Should [[-ActualValue] ] [-Not] [-Because ] [-Throw] [-ExpectedMessage ] + [-ErrorId ] [-ExceptionType ] [-PassThru] [] +``` + +### InvokeVerifiable + +```powershell +Should [[-ActualValue] ] [-Not] [-Because ] [-InvokeVerifiable] [] +``` + +### Invoke + +```powershell +Should [[-ActualValue] ] [-Not] [-Because ] [-Invoke] [-CommandName ] [-Times ] + [-ParameterFilter ] [-ExclusiveFilter ] [-ModuleName ] [-Scope ] [-Exactly] + [-CallerSessionState ] [] +``` + +## DESCRIPTION + +Should is a keyword that is used to define an assertion inside an It block. +Should provides assertion methods to verify assertions e.g. +comparing objects. +If assertion is not met the test fails and an exception is thrown. + +Should can be used more than once in the It block if more than one assertion +need to be verified. +Each Should keyword needs to be on a separate line. +Test will be passed only when all assertion will be met (logical conjunction). + +## EXAMPLES + +### EXAMPLE 1 + +```powershell +Describe "d1" { + It "i1" { + Mock Get-Command { } + Get-Command -CommandName abc + Should -Invoke Get-Command -Times 1 -Exactly + } +} +``` + +Example of creating a mock for `Get-Command` and asserting that it was called exactly one time. + +### EXAMPLE 2 + +```powershell +$true | Should -BeFalse +``` + +Asserting that the input value is false. +This would fail the test by throwing an error. + +### EXAMPLE 3 + +```powershell +$a | Should -Be 10 +``` + +Asserting that the input value defined in $a is equal to 10. + +### EXAMPLE 4 + +```powershell +Should -Invoke Get-Command -Times 1 -Exactly +``` + +Asserting that the mocked `Get-Command` was called exactly one time. + +### EXAMPLE 5 + +```powershell +$user | Should -Not -BeNullOrEmpty +``` + +Asserting that the input value from $user is not null or empty. + +### EXAMPLE 6 + +```powershell +$planets.Name | Should -Be $Expected +``` + +Asserting that the value of `$planets.Name` is equal to the value defined in `$Expected`. + +### EXAMPLE 7 + +```powershell +Context "We want to ensure an exception is thrown when expected" { + It "Throws the exception" { + { Get-Application -Name Blarg } | Should -Throw -ExpectedMessage "Application 'Blarg' not found" + } +} +``` + +Asserting that `Get-Application -Name Blarg` will throw an exception with a specific message. + +## PARAMETERS + +### -ActualValue + +The actual value that was obtained in the test which should be verified against +a expected value. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Alias + +Depends on operator being used. +See `Get-ShouldOperator -Name ` or https://pester.dev/docs/assertions/ for help. + +```yaml +Type: Object +Parameter Sets: HaveParameter +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Be + +Compares one object with another for equality and throws if the two objects are not the same. + +```yaml +Type: SwitchParameter +Parameter Sets: Be +Aliases: EQ + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Because + +Depends on operator being used. +See `Get-ShouldOperator -Name ` or https://pester.dev/docs/assertions/ for help. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -BeExactly + +Compares one object with another for equality and throws if the two objects are not the same. +This comparison is case sensitive. + +```yaml +Type: SwitchParameter +Parameter Sets: BeExactly +Aliases: CEQ + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -BeFalse + +Asserts that the value is false, or falsy. + +```yaml +Type: SwitchParameter +Parameter Sets: BeFalse +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -BeGreaterOrEqual + +Asserts that a number (or other comparable value) is greater than or equal to an expected value. +Uses PowerShell's -ge operator to compare the two values. + +```yaml +Type: SwitchParameter +Parameter Sets: BeGreaterOrEqual +Aliases: GE + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -BeGreaterThan + +Asserts that a number (or other comparable value) is greater than an expected value. +Uses PowerShell's -gt operator to compare the two values. + +```yaml +Type: SwitchParameter +Parameter Sets: BeGreaterThan +Aliases: GT + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -BeIn + +Asserts that a collection of values contain a specific value. +Uses PowerShell's -contains operator to confirm. + +```yaml +Type: SwitchParameter +Parameter Sets: BeIn +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -BeLessOrEqual + +Asserts that a number (or other comparable value) is lower than, or equal to an expected value. +Uses PowerShell's -le operator to compare the two values. + +```yaml +Type: SwitchParameter +Parameter Sets: BeLessOrEqual +Aliases: LE + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -BeLessThan + +Asserts that a number (or other comparable value) is lower than an expected value. +Uses PowerShell's -lt operator to compare the two values. + +```yaml +Type: SwitchParameter +Parameter Sets: BeLessThan +Aliases: LT + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -BeLike + +Asserts that the actual value matches a wildcard pattern using PowerShell's -like operator. +This comparison is not case-sensitive. + +```yaml +Type: SwitchParameter +Parameter Sets: BeLike +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -BeLikeExactly + +Asserts that the actual value matches a wildcard pattern using PowerShell's -like operator. +This comparison is case-sensitive. + +```yaml +Type: SwitchParameter +Parameter Sets: BeLikeExactly +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -BeNullOrEmpty + +Checks values for null or empty (strings). +The static [String]::IsNullOrEmpty() method is used to do the comparison. + +```yaml +Type: SwitchParameter +Parameter Sets: BeNullOrEmpty +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -BeOfType + +Asserts that the actual value should be an object of a specified type (or a subclass of the specified type) using PowerShell's -is operator. + +```yaml +Type: SwitchParameter +Parameter Sets: BeOfType +Aliases: HaveType + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -BeTrue + +Asserts that the value is true, or truthy. + +```yaml +Type: SwitchParameter +Parameter Sets: BeTrue +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -CallerSessionState + +Depends on operator being used. +See `Get-ShouldOperator -Name ` or https://pester.dev/docs/assertions/ for help. + +```yaml +Type: Object +Parameter Sets: Invoke +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -CommandName + +Depends on operator being used. +See `Get-ShouldOperator -Name ` or https://pester.dev/docs/assertions/ for help. + +```yaml +Type: Object +Parameter Sets: Invoke +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Contain + +Asserts that collection contains a specific value. +Uses PowerShell's -contains operator to confirm. + +```yaml +Type: SwitchParameter +Parameter Sets: Contain +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -DefaultValue + +Depends on operator being used. +See `Get-ShouldOperator -Name ` or https://pester.dev/docs/assertions/ for help. + +```yaml +Type: Object +Parameter Sets: HaveParameter +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ErrorId + +Depends on operator being used. +See `Get-ShouldOperator -Name ` or https://pester.dev/docs/assertions/ for help. + +```yaml +Type: Object +Parameter Sets: Throw +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Exactly + +Depends on operator being used. +See `Get-ShouldOperator -Name ` or https://pester.dev/docs/assertions/ for help. + +```yaml +Type: SwitchParameter +Parameter Sets: Invoke +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ExceptionType + +Depends on operator being used. +See `Get-ShouldOperator -Name ` or https://pester.dev/docs/assertions/ for help. + +```yaml +Type: Object +Parameter Sets: Throw +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ExclusiveFilter + +Depends on operator being used. +See `Get-ShouldOperator -Name ` or https://pester.dev/docs/assertions/ for help. + +```yaml +Type: Object +Parameter Sets: Invoke +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Exist + +Does not perform any comparison, but checks if the object calling Exist is present in a PS Provider. +The object must have valid path syntax. +It essentially must pass a Test-Path call. + +```yaml +Type: SwitchParameter +Parameter Sets: Exist +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ExpectedContent + +Depends on operator being used. +See `Get-ShouldOperator -Name ` or https://pester.dev/docs/assertions/ for help. + +```yaml +Type: Object +Parameter Sets: FileContentMatch, FileContentMatchExactly, FileContentMatchMultiline, FileContentMatchMultilineExactly +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ExpectedMessage + +Depends on operator being used. +See `Get-ShouldOperator -Name ` or https://pester.dev/docs/assertions/ for help. + +```yaml +Type: Object +Parameter Sets: Throw +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ExpectedType + +Depends on operator being used. +See `Get-ShouldOperator -Name ` or https://pester.dev/docs/assertions/ for help. + +```yaml +Type: Object +Parameter Sets: BeOfType +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ExpectedValue + +Depends on operator being used. +See `Get-ShouldOperator -Name ` or https://pester.dev/docs/assertions/ for help. + +```yaml +Type: Object +Parameter Sets: Be, BeExactly, BeGreaterThan, BeLessOrEqual, BeIn, BeLessThan, BeGreaterOrEqual, BeLike, BeLikeExactly, Contain, HaveCount +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -FileContentMatch + +Checks to see if a file contains the specified text. +This search is not case sensitive and uses regular expressions. + +```yaml +Type: SwitchParameter +Parameter Sets: FileContentMatch +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -FileContentMatchExactly + +Checks to see if a file contains the specified text. +This search is case sensitive and uses regular expressions to match the text. + +```yaml +Type: SwitchParameter +Parameter Sets: FileContentMatchExactly +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -FileContentMatchMultiline + +As opposed to FileContentMatch and FileContentMatchExactly operators, FileContentMatchMultiline presents content of the file being tested as one string object, so that the expression you are comparing it to can consist of several lines. + +When using FileContentMatchMultiline operator, '^' and '$' represent the beginning and end of the whole file, instead of the beginning and end of a line + +```yaml +Type: SwitchParameter +Parameter Sets: FileContentMatchMultiline +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -FileContentMatchMultilineExactly + +As opposed to FileContentMatch and FileContentMatchExactly operators, FileContentMatchMultilineExactly presents content of the file being tested as one string object, so that the case sensitive expression you are comparing it to can consist of several lines. + +When using FileContentMatchMultilineExactly operator, '^' and '$' represent the beginning and end of the whole file, instead of the beginning and end of a line. + +```yaml +Type: SwitchParameter +Parameter Sets: FileContentMatchMultilineExactly +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -HasArgumentCompleter + +Depends on operator being used. +See `Get-ShouldOperator -Name ` or https://pester.dev/docs/assertions/ for help. + +```yaml +Type: SwitchParameter +Parameter Sets: HaveParameter +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -HaveCount + +Asserts that a collection has the expected amount of items. + +```yaml +Type: SwitchParameter +Parameter Sets: HaveCount +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -HaveParameter + +Asserts that a command has the expected parameter. + +```yaml +Type: SwitchParameter +Parameter Sets: HaveParameter +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -InParameterSet + +Depends on operator being used. +See `Get-ShouldOperator -Name ` or https://pester.dev/docs/assertions/ for help. + +```yaml +Type: Object +Parameter Sets: HaveParameter +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Invoke + +Checks if a Mocked command has been called a certain number of times and throws an exception if it has not. + +```yaml +Type: SwitchParameter +Parameter Sets: Invoke +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -InvokeVerifiable + +Checks if any Verifiable Mock has not been invoked. +If so, this will throw an exception. + +```yaml +Type: SwitchParameter +Parameter Sets: InvokeVerifiable +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Mandatory + +Depends on operator being used. +See `Get-ShouldOperator -Name ` or https://pester.dev/docs/assertions/ for help. + +```yaml +Type: SwitchParameter +Parameter Sets: HaveParameter +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Match + +Uses a regular expression to compare two objects. +This comparison is not case sensitive. + +```yaml +Type: SwitchParameter +Parameter Sets: Match +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -MatchExactly + +Uses a regular expression to compare two objects. +This comparison is case sensitive. + +```yaml +Type: SwitchParameter +Parameter Sets: MatchExactly +Aliases: CMATCH + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ModuleName + +Depends on operator being used. +See `Get-ShouldOperator -Name ` or https://pester.dev/docs/assertions/ for help. + +```yaml +Type: Object +Parameter Sets: Invoke +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Not + +Reverse the assertion + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ParameterFilter + +Depends on operator being used. +See `Get-ShouldOperator -Name ` or https://pester.dev/docs/assertions/ for help. + +```yaml +Type: Object +Parameter Sets: Invoke +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ParameterName + +Depends on operator being used. +See `Get-ShouldOperator -Name ` or https://pester.dev/docs/assertions/ for help. + +```yaml +Type: Object +Parameter Sets: HaveParameter +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PassThru + +Depends on operator being used. +See `Get-ShouldOperator -Name ` or https://pester.dev/docs/assertions/ for help. + +```yaml +Type: SwitchParameter +Parameter Sets: Throw +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -RegularExpression + +Depends on operator being used. +See `Get-ShouldOperator -Name ` or https://pester.dev/docs/assertions/ for help. + +```yaml +Type: Object +Parameter Sets: Match, MatchExactly +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Scope + +Depends on operator being used. +See `Get-ShouldOperator -Name ` or https://pester.dev/docs/assertions/ for help. + +```yaml +Type: Object +Parameter Sets: Invoke +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Throw + +Checks if an exception was thrown. +Enclose input in a scriptblock. + +```yaml +Type: SwitchParameter +Parameter Sets: Throw +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Times + +Depends on operator being used. +See `Get-ShouldOperator -Name ` or https://pester.dev/docs/assertions/ for help. + +```yaml +Type: Object +Parameter Sets: Invoke +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Type + +Depends on operator being used. +See `Get-ShouldOperator -Name ` or https://pester.dev/docs/assertions/ for help. + +```yaml +Type: Object +Parameter Sets: HaveParameter +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS + +[https://pester.dev/docs/commands/Should](https://pester.dev/docs/commands/Should) + +[https://pester.dev/docs/assertions](https://pester.dev/docs/assertions) + +## VERSION + +*This page was generated using comment-based help in [Pester 5.6.0](https://github.com/pester/pester).* diff --git a/versioned_docs/version-v5/commands/docusaurus.sidebar.js b/versioned_docs/version-v5/commands/docusaurus.sidebar.js new file mode 100644 index 00000000..9e69da4f --- /dev/null +++ b/versioned_docs/version-v5/commands/docusaurus.sidebar.js @@ -0,0 +1,38 @@ +/** + * Import this file in your Docusaurus `sidebars.js` file. + * + * Auto-generated by Alt3.Docusaurus.Powershell 1.0.36. + * + * Copyright (c) 2019-present, ALT3 B.V. + * + * Licensed under the MIT license. + */ + +module.exports = [ + 'commands/Add-ShouldOperator', + 'commands/AfterAll', + 'commands/AfterEach', + 'commands/Assert-MockCalled', + 'commands/Assert-VerifiableMock', + 'commands/BeforeAll', + 'commands/BeforeDiscovery', + 'commands/BeforeEach', + 'commands/Context', + 'commands/ConvertTo-JUnitReport', + 'commands/ConvertTo-NUnitReport', + 'commands/ConvertTo-Pester4Result', + 'commands/Describe', + 'commands/Export-JUnitReport', + 'commands/Export-NUnitReport', + 'commands/Get-ShouldOperator', + 'commands/InModuleScope', + 'commands/Invoke-Pester', + 'commands/It', + 'commands/Mock', + 'commands/New-Fixture', + 'commands/New-MockObject', + 'commands/New-PesterConfiguration', + 'commands/New-PesterContainer', + 'commands/Set-ItResult', + 'commands/Should' +]; diff --git a/versioned_docs/version-v5/contributing/feature-requests.mdx b/versioned_docs/version-v5/contributing/feature-requests.mdx new file mode 100644 index 00000000..fbdabb06 --- /dev/null +++ b/versioned_docs/version-v5/contributing/feature-requests.mdx @@ -0,0 +1,10 @@ +--- +id: feature-requests +title: Feature Requests +sidebar_label: Feature Requests +description: How to suggest a new feature or improvement to the Pester PowerShell-module +--- + +To propose a new feature, please [create a new issue](https://github.com/pester/Pester/issues/new/choose) and share as much information as you see fit. Especially what the proposed feature is, why it is useful, and what dependencies (if any) it has. It would also be great if you added one or two examples of real world usage, if you have any. + +When we discuss new features we look at how useful it is to the majority of users, how difficult it would be to implement, if breaking changes to the API must be introduced to have it, and if it's too specialized or too general to put in the codebase. But again, don't let that scare you away. diff --git a/versioned_docs/version-v5/contributing/introduction.mdx b/versioned_docs/version-v5/contributing/introduction.mdx new file mode 100644 index 00000000..6a09fb58 --- /dev/null +++ b/versioned_docs/version-v5/contributing/introduction.mdx @@ -0,0 +1,63 @@ +--- +id: introduction +title: Introduction for contributors +sidebar_label: Introduction +description: There are many ways to contribute to the Pester project and community. Check out this short introduction for how to get started +--- + +To propose a new feature to Pester or report a bug, we encourage you to first share your findings +with us by creating a new issue. The feature or bug will be discussed, and if it's something we would +like (or even love!) to see in our codebase we will ask you to create a pull request (PR) for it. We +have a (more or less) standardized process for accepting PRs, but don't let that scare you away. We +understand that you spent your free time to contribute, so we will take our time to help you +successfully add your code to Pester. + +## Community + +Open source doesn’t always have the best reputation for being friendly and welcoming, and that makes +us sad. **Everyone belongs in open source, and Pester is dedicated to making you feel welcome.** + +We will never judge, condescend, or exclude anyone. Instead, we will go above and beyond to support +the community, through helping you contribute to the Pester ecosystem, an open and inclusive code +of conduct, and other means that empower and embrace the incredible community that makes Pester possible. + +One of our community's values is that "you belong here". + +## Covenant Code of Conduct + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, gender identity and expression, level of +experience, nationality, personal appearance, race, religion, or sexual identity +and orientation. + +[Read the full code of conduct](https://github.com/pester/Pester/blob/main/CODE_OF_CONDUCT.md) + +## Ways to Contribute + +The Pester community welcomes contributions. Please refer to the guides below on how to make sure your contributions get accepted: + +- [How to File an Issue](./reporting-issues) +- [How to make a Feature Request](./feature-requests) +- [How to Open a Pull Request](./pull-requests) + +## Where to get support + +- [GitHub Discussions](https://github.com/pester/Pester/discussions) +- [Gitter](https://gitter.im/pester/Pester) +- [Powershell.org](https://forums.powershell.org/c/pester) +- [Slack](https://powershell.slack.com/messages/C03QKTUCS) +- [Discord (#testing)](https://discord.gg/powershell) + +### Stack Overflow + +Many members of the community use Stack Overflow to ask questions. Read through +the [existing questions](http://stackoverflow.com/questions/tagged/pester) +tagged with `pester` or +[ask your own](http://stackoverflow.com/questions/ask?tags=pester)! + +### Twitter + +For the latest news about Pester, +[follow **@pspester** on Twitter](https://twitter.com/pspester). diff --git a/versioned_docs/version-v5/contributing/pull-requests.mdx b/versioned_docs/version-v5/contributing/pull-requests.mdx new file mode 100644 index 00000000..8787c803 --- /dev/null +++ b/versioned_docs/version-v5/contributing/pull-requests.mdx @@ -0,0 +1,148 @@ +--- +id: pull-requests +title: Submitting Pull Requests +sidebar_label: Pull Requests +description: Introduction on how to start contributing to the Pester project either by filing a bug, feature requests, support or submitting a pull request +--- + +So now we talked about your proposed change in the issue and it's time for you to implement the change and make it into a pull request (PR). + +### Step 1 - Forking the Main Repository + +You cannot add code directly to our repository, you need to first get your own copy "a fork". GitHub makes this really simple, all you need to do is log in with your GitHub account, navigate to [Pester repository](https://github.com/pester/Pester) and click the "Fork" button on the upper right. There is a helpful wizard to walk you through the process of forking and cloning the repository. At the end you should have a local copy of Pester on your computer. + +If you don't have much experience with git, I suggest you download the [GitHub desktop client](https://desktop.github.com/) that will make reviewing your changes really simple. I will be describing all the steps in commands that you need to put in command line. You can get to it by clicking the cog wheel in the application and selecting "Open in Git shell". + +### Step 2 - Syncing Your Clone with the Main Repository + +__If you just forked and cloned as described in the Step 1 you can skip directly to step 3. Your code is already up-to-date.__ + +Otherwise you should make sure that your fork and your local copy (clone) is up to date. We will be updating the main branch, because that is where you should always start when creating a new PR. + +First you need to tell your repository where to find the official Pester repository by setting an upstream remote, you can find how to do that [in this official guide.](https://help.github.com/articles/configuring-a-remote-for-a-fork/) + +Then you need to get the latest code from the main Pester repository (upstream) and merge it to your repository, [here is another official guide on how to do that.](https://help.github.com/articles/syncing-a-fork/). Finally you push the changes to your fork on the server (origin), by running `git push` in the command line. You should repeat these steps every time you are starting a new PR, to make sure your code is up-to-date. + +Here is the whole process from cloning the repository from an out-dated fork, till pushing the changes to the server: + +```powershell +# cloning my fork of Pester from the server, +# (notice the /nohwnd/pester.git in the URL, unlike /pester/pester.git of the official repository) +C:\Users\nohwnd\Documents\GitHub> git clone https://github.com/nohwnd/pester.git +Cloning into 'pester'... +remote: Enumerating objects: 10888, done. +remote: Counting objects: 100% (789/789), done. +remote: Compressing objects: 100% (371/371), done. +remote: Total 10888 (delta 441), reused 689 (delta 405), pack-reused 10099 +Receiving objects: 100% (10888/10888), 20.92 MiB | 8.37 MiB/s, done. +Resolving deltas: 100% (7528/7528), done. + +# navigating to the repository folder +C:\Users\nohwnd\Documents\GitHub> cd .\Pester\ + +# listing the remotes to see what is there +# (notice that the URL is the same as the cloning URL and that it's called origin) +C:\Users\nohwnd\Documents\GitHub\Pester [main ≡]> git remote -v +origin https://github.com/nohwnd/Pester.git (fetch) +origin https://github.com/nohwnd/Pester.git (push) + +# adding one more remote to tell git where the official Pester repository is +# (notice this one is called upstream, and has /pester/pester.git in the URL, unlike the fork) +C:\Users\nohwnd\Documents\GitHub\Pester [main ≡]> git remote add upstream https://github.com/pester/Pester.git + +# listing the remotes again to confirm the configuration is correct +C:\Users\nohwnd\Documents\GitHub\Pester [main ≡]> git remote -v +origin https://github.com/nohwnd/Pester.git (fetch) +origin https://github.com/nohwnd/Pester.git (push) +upstream https://github.com/pester/Pester.git (fetch) +upstream https://github.com/pester/Pester.git (push) + +### --- The previous steps are one-time. You can start from here on successive updates. --- + +# downloading (fetching) data from the official repository +# (you can see there are some new branches and tags) +C:\Users\nohwnd\Documents\GitHub\Pester [main ≡]> git fetch upstream +remote: Enumerating objects: 502, done. +remote: Counting objects: 100% (502/502), done. +remote: Compressing objects: 100% (257/257), done. +remote: Total 502 (delta 335), reused 373 (delta 244), pack-reused 0 +Receiving objects: 100% (502/502), 333.22 KiB | 4.56 MiB/s, done. +Resolving deltas: 100% (335/335), completed with 47 local objects. +From https://github.com/pester/Pester +... + * [new branch] main -> upstream/main + * [new branch] profiler-cc -> upstream/profiler-cc + * [new branch] readme -> upstream/readme + * [new branch] rel/3.x.x -> upstream/rel/3.x.x + * [new branch] rel/4.x.x -> upstream/rel/4.x.x + * [new branch] rel/5.2.x -> upstream/rel/5.2.x + * [new branch] rel/5.3.x -> upstream/rel/5.3.x +... + * [new tag] 5.3.2 -> 5.3.2 + * [new tag] 5.3.3 -> 5.3.3 + +# moving to the main branch (I already was there so this step was not necessary.) +# the message says I am up to date with origin/main - the main branch in my fork on the server. +# you can call "git pull" to make sure everything is up to date +C:\Users\nohwnd\Documents\GitHub\Pester [main ≡]> git checkout main +Already on 'main' +Your branch is up to date with 'origin/main'. + +# here I am merging the offical repository main branch to my fork main branch +# you can see there were some changes to merge +C:\Users\nohwnd\Documents\GitHub\Pester [main ≡]> git merge upstream/main +Updating 3c1b0e4..8869115 +Fast-forward + azure-pipelines.yml | 9 --------- + src/functions/Output.ps1 | 17 +++++++++++++---- + src/functions/assertions/Should.ps1 | 9 +++++++++ + 3 files changed, 22 insertions(+), 13 deletions(-) + +# pushing the merged changes to my fork on the server (origin) +C:\Users\nohwnd\Documents\GitHub\Pester [main ↑]> git push +... +To https://github.com/nohwnd/Pester.git + 3c1b0e4..8869115 main -> main +``` + +### Step 3 - Create a Feature Branch + +Switch to your main branch and create a new so-called feature branch from it ("FixHelpForShould" in examples below). This branch will hold all changes for the PR you are implementing. You could put your changes directly into the main branch, but that's not recommended. + +```bash +git checkout -b "FixHelpForShould" +``` + +This command will create a new branch based on the current branch (main) and will switch directly to it. + +```powershell +C:\Users\nohwnd\Documents\GitHub\Pester [main ≡]> git checkout main +Already on 'main' +Your branch is up-to-date with 'origin/main'. +C:\Users\nohwnd\Documents\GitHub\Pester [main ≡]> git checkout -b "FixHelpForShould" +Switched to a new branch 'FixHelpForShould' +C:\Users\nohwnd\Documents\GitHub\Pester [FixHelpForShould]> +``` + +### Step 4 - Implement Your Changes + +Now you can start implementing your changes. Make sure that your changes are relevant to the feature that you are implementing/the bug you are fixing. +Avoid changing formatting and style of code that is not relevant to your changes. + +Remember to build the module and run tests to make sure everything still works. See [CONTRIBUTING](https://github.com/pester/Pester/blob/main/CONTRIBUTING.md) for more details. + +### Step 5 - Commit Your Changes + +Once you are done with you changes you need to commit them to your branch. +When all commits are ready and tests pass, push the new feature branch to your fork. + +```bash +git push origin FixHelpForShould +``` + +### Step 6 - Submit Your Pull Request + +Open your fork on https://github.com and click the "Compare & pull request" button in the banner at the top. +This will take you to the pull request form. Read and fill out the template text and submit your pull request. + +Thanks for contributing! diff --git a/versioned_docs/version-v5/contributing/reporting-issues.mdx b/versioned_docs/version-v5/contributing/reporting-issues.mdx new file mode 100644 index 00000000..607d30d6 --- /dev/null +++ b/versioned_docs/version-v5/contributing/reporting-issues.mdx @@ -0,0 +1,25 @@ +--- +id: reporting-issues +title: Reporting Issues +sidebar_label: Reporting Issues +description: Found an issue with Pester? Check out this guide for how to create an issue and provide us feedback so we can help you +--- + +To report a bug, please [create a new issue](https://github.com/pester/Pester/issues/new/choose), and fill out the details. Your bug report should include the description of what is wrong, the version of Pester, PowerShell and the operating system. To make your bug report perfect you should also include a simple way to reproduce the bug. + +Here is a piece of code that collects the required system information for you and puts it in your clipboard: + +```powershell +# You can open the URL in a browser to view the code before running it. +(Invoke-WebRequest -Uri "https://git.io/JTinj" -UseBasicParsing).Content | Invoke-Expression +``` + +Example output: + +``` +Pester version : 5.3.3 C:\Users\nohwnd\Documents\PowerShell\Modules\Pester\5.3.3\Pester.psm1 +PowerShell version : 7.2.3 +OS version : Microsoft Windows NT 10.0.22000.0 +``` + +The best way to report the reproduction steps is in a form of a Pester test. But it's not always easy to do, especially if you are reporting a bug in some internal part of the framework. So feel free to provide just a list of steps that need to be taken to reproduce the bug. diff --git a/versioned_docs/version-v5/index.html b/versioned_docs/version-v5/index.html new file mode 100644 index 00000000..7585a851 --- /dev/null +++ b/versioned_docs/version-v5/index.html @@ -0,0 +1,18 @@ + + + + + + + Pester Documentation + + + If you are not redirected automatically, follow this + link. + + diff --git a/versioned_docs/version-v5/introduction/installation.mdx b/versioned_docs/version-v5/introduction/installation.mdx new file mode 100644 index 00000000..af1bb73d --- /dev/null +++ b/versioned_docs/version-v5/introduction/installation.mdx @@ -0,0 +1,132 @@ +--- +id: installation +title: Installation and Update +sidebar_label: Installation +description: Pester is a cross-platform PowerShell module for testing your PowerShell code. Follow these steps to install or update your Pester-module to get started today +--- + +## Compatibility + +Pester is a cross-platform module that runs on Windows, Linux, MacOS and anywhere else supported by PowerShell. It is tested and compatible with: +- Windows PowerShell 3.0 - 5.1 +- PowerShell 6.0.4 and above + +## Installing from PowerShell Gallery + +You can install Pester using the built-in `Install-Module` command. The examples below will install Pester in your [default installation scope](https://learn.microsoft.com/en-us/powershell/module/powershellget/install-module?view=powershellget-3.x#-scope) depending on your PowerShell-version. You can control this using the `-Scope ` parameter. + +### Linux & MacOS + +From a PowerShell session run: + +```powershell +Install-Module -Name Pester +``` + +To update: + +```powershell +Update-Module -Name Pester +``` + +### Windows + +Windows 10 / Windows Server 2016 and later ships with Pester version 3.4.0. This built-in version cannot be updated using the simple `Update-Module` cmdlet. +Instead you need to perform a side-by-side installation to get started with the latest version of Pester. + +The built-in version is signed by Microsoft while newer versions are community-maintained and signed with a different certificate, +causing `Install-Module` to sometimes throw a error requiring us to accept the new publisher certificate. + +Run the command below to install the latest version: +```powershell +# -Force to install side-by-side +# -SkipPublisherCheck to accept the newer certificate + +Install-Module -Name Pester -Force -SkipPublisherCheck +``` + +For any subsequent updates it is enough to run: + +```powershell +Update-Module -Name Pester +``` + +:::note Removing the built-in version +If you'd like to remove the built-in version of Pester, you can do so using the following code *as administrator*: + +```powershell +$module = "C:\Program Files\WindowsPowerShell\Modules\Pester" +& takeown.exe /F $module /A /R +& icacls.exe $module /reset +& icacls.exe $module /grant "*S-1-5-32-544:F" /inheritance:d /T +Remove-Item -Path $module -Recurse -Force -Confirm:$false + +# Install latest Pester +Install-Module -Name Pester +``` +::: + +### Common errors + +#### TLS error while connecting to PowerShell Gallery +If you receive the following warning when trying to install the module, you may need to explicitly enable TLS 1.2. + +```powershell +WARNING: Unable to resolve package source 'https://www.powershellgallery.com/api/v2'. + +# Enable TLS 1.2 for the current PowerShell instance using the line below and try again +[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor [System.Net.SecurityProtocolType]::Tls12 +``` + +#### Command `Install-Module` is not found + +Older versions of Windows running Windows PowerShell 3.0 or 4.0 do not have a built-in package manager. You can install `PowerShellGet` using the [instructions here](https://docs.microsoft.com/en-us/powershell/scripting/gallery/installing-psget#for-computers-running-powershell-30-or-powershell-40). After completing the steps, start a new PowerShell session and retry [the module installation](#installing-from-powershell-gallery). + +Alternatively, you can install the module manually using the instructions below. + +## Installing manually + +You don't have to use a package manager to install Pester. Another option is to download and installing it manually which can be useful in e.g. offline environments. + +1. Download the module on a machine with internet using either: + - `Save-Module -Name Pester -Path C:\Temp`. It will save it in a versioned folder, ex *C:\Temp\Pester\5.5.0* + - Or download the NuGet package from PowerShell Gallery and extract it, see [Manual Package Download](https://docs.microsoft.com/en-us/powershell/scripting/gallery/how-to/working-with-packages/manual-download) +2. Copy the Pester-folder (ex. *C:\Temp\Pester*) to your destination computer and place it in one of your module directories defined by [$env:PSModulePath](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_psmodulepath). On a Windows-system the default locations include: + - **Current user:** *$HOME\Documents\WindowsPowerShell\Modules* + - **All users:** *$env:ProgramFiles\WindowsPowerShell\Modules* +3. Start PowerShell and start testing. + +:::note +Step 2 is an optional step to enable simple import by name and module auto-loading. You could also import Pester using an absolute path like `Import-Module C:\Temp\Pester\5.5.0`. +::: + +## Alternative package sources + +PSGallery is the easiest way to get Pester installed to your computer, but there are alternatives. +On a build server you might prefer using [Chocolatey](https://chocolatey.org/), or if you're adding Pester to your .NET project that already uses [NuGet](https://www.nuget.org/) you might prefer that. + +These options may not support pre-release versions and it may need to be initialized on first use. + +### Chocolatey + +[Chocolatey](https://chocolatey.org/) (or _choco_) is a commonly used package manager for Windows. You can install Pester using: + +```powershell +choco install Pester +``` + +Or to update: + +```powershell +choco upgrade Pester +``` + +You may also pass the `--prerelease` option to install or update to a prerelease version of Pester. + +### Nuget + +[Nuget](https://www.nuget.org/) is the package manager for .NET projects. +Getting Pester from Nuget is useful when you are integrating PowerShell code with your .NET project, and want to have that code tested. + +To install use Package Manager of Visual Studio, or Package Manager Console in Visual Studio. +Once you need this we are pretty sure you know what you are doing. :slightly_smiling_face: diff --git a/versioned_docs/version-v5/migrations/breaking-changes-in-v5.mdx b/versioned_docs/version-v5/migrations/breaking-changes-in-v5.mdx new file mode 100644 index 00000000..ebf3d5d0 --- /dev/null +++ b/versioned_docs/version-v5/migrations/breaking-changes-in-v5.mdx @@ -0,0 +1,39 @@ +--- +id: breaking-changes-in-v5 +title: Breaking changes in v5 +description: Pester v5 included an all-new runtime which lead to some breaking changes in syntax and features for existing users. See this list of breaking changes when upgrading to Pester v5 +--- + +## Actual breaking changes + +- (❗ new in 5.0.1) The Parameters of `Invoke-Pester` changed significantly, but in 5.0.1, a compatibility parameter set was added. To allow all the v4 parameters to be used, e.g. like this `Invoke-Pester -Script $testFile -PassThru -Verbose -OutputFile $tr -OutputFormat NUnitXml -CodeCoverage "$tmp/*-*.ps1" -CodeCoverageOutputFile $cc -Show All`. The compatibility is not 100%, neither -Script not -CodeCoverage take hashtables, they just take a collection of paths. The `-Strict` parameter and `-PesterOption` are ignored. The `-Output` \ `-Show` parameter takes all the values, but translates only the most used options to Pester 5 compatible options, otherwise it uses `Detailed` output. It also allows all the Pester 5 output options, to allow you to use `Diagnostic` during migration. **This whole Legacy-parameter set is deprecated** and prints a warning when used. For more options and the Advanced interface see [simple and advanced interface](./v4-to-v5#simple-and-advanced-interface) above on how to invoke Pester. +- PowerShell 2 is no longer supported +- Legacy syntax `Should Be` (without `-`) is removed, see [Migrating from Pester v3 to v4](./v3-to-v4) +- Mocks are scoped based on their placement, not in whole `Describe` / `Context`. The count also depends on their placement. See [mock scoping](../usage/mocking#mocks-are-scoped-based-on-their-placement) +- `Assert-VerifiableMocks` was removed, see [Should -Invoke](../usage/mocking#should--invoke) +- All code placed in the body of `Describe` outside of `It`, `BeforeAll`, `BeforeEach`, `AfterAll`, `AfterEach` will run during discovery and it's state might or might not be available to the test code, see [Discovery and Run](../usage/discovery-and-run) + +- `-Output` parameter has reduced options to `None`, `Normal`, `Detailed` and `Diagnostic`, `-Show` alias is removed +- `-PesterOption` switch is removed +- `-TestName` switch is replaced with `-FullNameFilter` switch +- `-Script` option was renamed to `-Path` and takes paths only, it does not take hashtables. For parametrized scripts, see [Providing external data to tests](../usage/data-driven-tests#providing-external-data-to-tests) +- Using `$MyInvocation.MyCommand.Path` to locate your script in `BeforeAll` does not work. This does not break it for your scripts and modules. Use `$PSScriptRoot` or `$PSCommandPath`. See [Migrating from Pester v4](../usage/importing-tested-functions#migrating-from-pester-v4) or the [importing ps files](https://jakubjares.com/2020/04/11/pester5-importing-ps-files/) article for detailed information. +- Should `-Throw` is using `-like` to match the exception message instead of .Contains. Use `*` or any of the other `-like` wildcard to match only part of the message. +- Variables defined during Discovery, are not available in Before*, After* and It. When generating tests via foreach blocks, make sure you pass all variables into the test using -TestCases / -ForEach. +- Gherkin is removed, and will later move to it's own module, please keep using Pester version 4. +- `TestDrive` is defined during Run only, it cannot be used in -TestCases / -ForEach. + +### Deprecated features + +- `Assert-MockCalled` is deprecated, it is recommended to use [Should -Invoke](../usage/mocking) +- `Assert-VerifiableMock` is deprecated, it is recommended to use [Should -InvokeVerifiable](../usage/mocking) + +### Additional issues to be solved future releases + +- `-Strict` switch is not available +- Inconclusive and Pending states are currently no longer available, `-Pending` and `-Inconclusive` are translated to `-Skip` both on test blocks and when using `Set-ItResult` +- Automatic Code coverage via -CI switch currently disabled as it's slow. Can still be enabled using configuration, but is largely untested. +- Generating tests using foreach during discovery time works mostly, generating them from BeforeAll, to postpone expensive work till it is needed in case the test is filtered out also works, but is hacky. Get in touch if you need it and help me refine it. +- Running on huge codebases is largely untested + +**Noticed more of them? Share please!** diff --git a/versioned_docs/version-v5/migrations/v3-to-v4.mdx b/versioned_docs/version-v5/migrations/v3-to-v4.mdx new file mode 100644 index 00000000..949f69fa --- /dev/null +++ b/versioned_docs/version-v5/migrations/v3-to-v4.mdx @@ -0,0 +1,236 @@ +--- +id: v3-to-v4 +title: Migrating from Pester v3 to v4 +sidebar_label: Pester v3 to v4 +description: Migration from Pester v3 to v4 may require minor changes to your test code. See this guide to get help understanding and making the necessary changes to be compatible with Pester v4 +--- + +Migration from Pester 3 to 4 typically involves minor changes to test code. Sometimes the migration requires no changes at all. This guide is meant to help you understand and make the necessary changes to your existing test code to accommodate Pester 4. + +## Update to New Names + +We recommend performing string replacement on tests written for Pester 3 and earlier as follows: + +1. replace all occurrences of any `Contain` assertion with `FileContentMatch`. +2. rename all occurrences of `Assert-VerifiableMocks` to `Assert-VerifiableMock` + +You can use this simple script that can migrate test files in UTF8 and ASCII encoding. + +:warning: +Please verify manually results generated by the script - it can generate false positive replaces! + +```powershell +param ($Path = '.') + +# version 2017-12-13 + +$testFiles = $(Get-ChildItem -Path $Path -Recurse *.Tests.ps1).FullName + +foreach ($file in $testFiles) +{ + "Migrating '$file'" + $encoding = Get-FileEncoding -Path $file + $content = Get-Content -Path $file -Encoding $encoding + $content = $content -replace 'Should\s+\-?Contain', 'Should -FileContentMatch' + $content = $content -replace 'Should\s+\-?Not\s*-?Contain', 'Should -Not -FileContentMatch' + $content = $content -replace 'Assert-VerifiableMocks', 'Assert-VerifiableMock' + $content | Set-Content -Path $file -Encoding $encoding +} + +function Get-FileEncoding { + # source https://gist.github.com/jpoehls/2406504 + # simplified. + + [CmdletBinding()] + Param ( + [Parameter(Mandatory = $True, ValueFromPipelineByPropertyName = $True)] + [string]$Path + ) + + [byte[]]$byte = get-content -Encoding byte -ReadCount 4 -TotalCount 4 -Path $Path + + if ( $byte[0] -eq 0xef -and $byte[1] -eq 0xbb -and $byte[2] -eq 0xbf ) + { Write-Output 'UTF8' } + + else + { Write-Output 'ASCII' } +} +``` + +## Update to the new assertions syntax + +In Pester 4.0 the new assertion syntax was introduced. \ +Now assertions can be provided as parameters to Should, that allows richer assertion vocabulary. + +### Old syntax + +```powershell +It 'Check something' { + 10 | Should Be 10 +} +``` + +### New syntax + +``` powershell +It 'Check something' { + 10 | Should -Be 10 +} +``` + +For most cases tests can be updated using the function provided below. + +:warning: +Please verify manually results generated by the script specially if your scripts are not UTF-8 or ASCII encoded! + +```powershell +function Update-PesterTest { +<# + .SYNOPSIS + The function intended to update Pester tests notation from version 3.x to 4.x. + + .DESCRIPTION + Notation for the Should assertion changed between Pester version 3.x and 4.x. + The function helps to update existing Pester 3.x tests to the new notation. + + Please be aware that if your original Pester test files are encoded differently than UTF-8 + than the final files encoding will be Unicode (UTF-7) / ASCSI. + + .PARAMETER Path + Path to the file that contain Pester tests to update. + + .PARAMETER Destination + Path to the file for which updated tests will be saved. + + If the Destination parameter is ommitted tests will be updated in place. + The content of an original file will be replaced. + + .EXAMPLE + + Update-PesterTest -Path .\Pester3-Tests\Dumy.Tests.ps1 .\Pester4-Tests\Dumy.Tests.ps1 + + .NOTES + Original author + Chris Dent, @indented-automation + + Updates + Wojciech Sciesinski, @it-praktyk + + LICENSE + Copyright 2017 Chris Dent + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + .LINK + https://github.com/pester/Pester/issues/892 + https://gist.github.com/indented-automation/aeb14825e39dd8849beee44f681fbab3 + https://gist.github.com/jpoehls/2406504 +#> + + [CmdletBinding()] + param ( + [Parameter(Mandatory=$true, ValueFromPipeline, ValueFromPipelineByPropertyName)] + [Alias('FullName')] + [System.IO.FileInfo]$Path, + [Parameter(Mandatory=$false)] + [String]$Destination + ) + + begin { + $shouldParams = [String[]](Get-Command Should).Parameters.Keys + $destIsEmpty = [String]::IsNullOrEmpty($Destination) + } + + process { + $Path = $pscmdlet.GetUnresolvedProviderPathFromPSPath($Path) + + $encoding = Get-FileEncoding -Path $Path + + [String]$MessageText = "The file {0} will be {1} encoded." -f $Path, $encoding + + Write-Verbose -Message $MessageText + + $errors = $tokens = @() + $ast = [System.Management.Automation.Language.Parser]::ParseFile( + $Path, + [Ref]$tokens, + [Ref]$errors + ) + + $script = Get-Content $Path -Raw -Encoding $encoding + $ast.FindAll( + { + param ( $ast ) + + $ast -is [System.Management.Automation.Language.CommandAst] -and + $ast.GetCommandName() -eq 'Should' + }, + $true + ) | + ForEach-Object { + $_.CommandElements | Where-Object { + $_.StringConstantType -eq 'BareWord' -and + $_.Value -in $shouldParams -or + $_.Value -eq 'Contain' + } + } | + Sort-Object { $_.Extent.StartOffset } -Descending | + ForEach-Object { + if ($_.Value -eq 'Contain') { + $script = $script.Remove($_.Extent.StartOffset, 7).Insert($_.Extent.StartOffset, '-FileContentMatch') + } else { + $script = $script.Insert($_.Extent.Startoffset, '-') + } + } + + if ( $destIsEmpty) { $Destination = $Path } + + Set-Content -Path $Destination -Value $script -NoNewline -Encoding $encoding + } + +} + +function Get-FileEncoding { + # source https://gist.github.com/jpoehls/2406504 + # simplified. + + [CmdletBinding()] + Param ( + [Parameter(Mandatory = $True, ValueFromPipelineByPropertyName = $True)] + [string]$Path + ) + + [byte[]]$byte = get-content -Encoding byte -ReadCount 4 -TotalCount 4 -Path $Path + + if ( $byte[0] -eq 0xef -and $byte[1] -eq 0xbb -and $byte[2] -eq 0xbf ) + { Write-Output 'UTF8' } + + else + { Write-Output 'ASCII' } +} +``` + +## Mock-Related Changes + +We are not 100% sure what implications changing from functions to aliases had on mocking. There are no immediate changes that you need to do, but here are two articles that should help you start figuring out issues if you have any: + +- [Get-Command of mocked function is less complete](https://github.com/pester/Pester/issues/810) +- [Summary of mock scope changes](https://github.com/pester/Pester/issues/812) + +## Array-Related Changes + +The `Should` command now performs array assertions. For the most part this change is transparent to existing tests. There are some edge cases, however, where a test involving an array passes in Pester 3 but fails in Pester 4. [This article](https://github.com/pester/Pester/issues/873) contains such an example. + +## Related (Github) Issues + +Visit this link for all [Migration Related Issues](https://github.com/Pester/Pester/issues?utf8=%E2%9C%93&q=is%3Aissue%20label%3A%22Pester%20migration%20v3-%3Ev4%22%20). diff --git a/versioned_docs/version-v5/migrations/v4-to-v5.mdx b/versioned_docs/version-v5/migrations/v4-to-v5.mdx new file mode 100644 index 00000000..96c07810 --- /dev/null +++ b/versioned_docs/version-v5/migrations/v4-to-v5.mdx @@ -0,0 +1,177 @@ +--- +id: v4-to-v5 +title: Migrating from Pester v4 to v5 +sidebar_label: Pester v4 to v5 +description: Pester v5 introduced some fundamental changes compared with Pester v4. See this guide to get help understanding and making the necessary changes to be compatible with Pester v5 +--- + +The fundamental change in this release is that Pester now runs in two phases: Discovery and Run. During discovery, it quickly scans your test files and discovers all the Describes, Contexts, Its and other Pester blocks. + +**Put all your test-code into `It`, `BeforeAll`, `BeforeEach`, `AfterAll` or `AfterEach`. Put no test-code directly into `Describe`, `Context` or on the top of your file, without wrapping it in one of these blocks, unless you have a good reason to do so.** + +**All misplaced code will run during Discovery, and its results won't be available during Run. Code meant to run in Discovery should be explicitly placed into `BeforeDiscovery`, see [Data driven tests](../usage/data-driven-tests#beforediscovery).** + +This will allow Pester to control when all of your code is executed, and scope it correctly. This will also keep the amount of code executed during discovery to a minimum. Keeping it fast and responsive. See [Discovery and Run](../usage/discovery-and-run) for details. + + +### Put setup in BeforeAll +If your test suite already puts its setups and teardowns into `Before*` and `After*`. All you need to do is move the file setup into a `BeforeAll` block: + +```powershell +BeforeAll { + # DON'T use $MyInvocation.MyCommand.Path + . $PSCommandPath.Replace('.Tests.ps1','.ps1') +} + +Describe "Get-Cactus" { + It "Returns 🌵" { + Get-Cactus | Should -Be '🌵' + } +} +``` + +See [migration script](https://gist.github.com/nohwnd/d488bd14ab4572f92ae77e208f476ada) for a script that does it for you. Improvements are welcome, e.g. putting code between `Describe` and `It` into `BeforeAll`. + +### Review your usage of Skip + +Discovery also impacts `-Skip` when you use it with `-Skip:$SomeCondition`. All the code in the describe block, including your skip conditions and TestCases will be evaluated during Discovery. Prefer static global variables, or code that is cheap to executed. It is not forbidden to put code to figure out the skip outside of `BeforeAll`, but be aware that it will run on every discovery. + +This won't work. `BeforeAll` runs after Discovery, and so `$isSkipped` is not defined and ends up being `$null -> $false`, so the test will run. + +```powershell +Describe "d" { + BeforeAll { + function Get-IsSkipped { + Start-Sleep -Second 1 + $true + } + $isSkipped = Get-IsSkipped + } + + It "i" -Skip:$isSkipped { + + } +} +``` + +Changing the code like this will skip the test correctly, but be aware that the code will run every time Discovery is performed on that file. Depending on how you run your tests this might be every time. + +```powershell +function Get-IsSkipped { + Start-Sleep -Second 1 + $true +} +$isSkipped = Get-IsSkipped + +Describe "d" { + It "i" -Skip:$isSkipped { + + } +} +``` + +Consider settings the check statically into a global read-only variable (much like `$IsWindows`), or caching the response for a while. Are you in this situation? Get in touch via the channels mentioned in [Got questions?](https://github.com/pester/pester#got-questions). + +### Review your usage of TestCases + +`-TestCases`, much like `-Skip` are evaluated during discovery and saved for later use when the test runs. This means that doing expensive setup for them will be happening every Discovery. On the other hand, you will now find their complete content for each TestCase in `Data` on the result test object. + + +# New result object + +The new result object is extremely rich, and used by Pester internally to make all of its decisions. Most of the information in the tree is unprocessed to allow you to to work with the raw data. You are welcome to inspect the object, and write your code based on it. + +To use your current CI pipeline with the new object use `ConvertTo-Pester4Result` to convert it. To convert the new object to NUnit report use `ConvertTo-NUnitReport` or specify the `-CI` switch to enable NUnit output, code coverage and exit code on failure. + + +## Simple and advanced interface + +`Invoke-Pester` is extremely bloated in Pester4. Some of the parameters consume hashtables that I always have to google, and some of the names don't make sense anymore. In Pester5 I aimed to simplify this interface and get rid of the hashtables. Right now I landed on two vastly different apis. With a big hole in the middle that still remains to be defined. There is the Simple interface that looks like this: + +```powershell +Invoke-Pester -Path + -ExcludePath + -Tag + -ExcludeTag + -FullNameFilter + -Output + -CI + -PassThru +``` + +And the Advanced interface that takes just Pester configuration object and nothing else: + +```powershell +Invoke-Pester -Configuration +``` + +A mapping of the parameters of the simple interface to the configuration object properties on the advanced interface is: + +| Parameter | Configuration Object Property | +| -------------- | ---------------------------------------------------- | +| Path | Run.Path | +| ExcludePath | Run.ExcludePath | +| Tag | Filter.Tag | +| ExcludeTag | Filter.ExcludeTag | +| FullNameFilter | Filter.FullName | +| Output | Output.Verbosity | +| CI | TestResult.Enabled and Run.Exit (all set to `$true`) | +| PassThru | Run.PassThru | + + +## Legacy interface + +The following table shows a mapping of v4 Legacy parameters (those which have not been documented under the Simple/Advanced interfaces) to the configuration object + +
+ +| Parameter | Configuration Object Property | +| ------------------------------ | ----------------------------------------- | +| EnableExit | Run.Exit | +| CodeCoverage | CodeCoverage.Path | +| CodeCoverageOutputFile | CodeCoverage.OutputPath | +| CodeCoverageOutputFileEncoding | CodeCoverage.OutputEncoding | +| CodeCoverageOutputFileFormat | CodeCoverage.OutputFormat | +| OutputFile | TestResult.OutputPath | +| OutputFormat | TestResult.OutputFormat | +| Show | Output.Verbosity (via mapping; see below) | + +
+ +The following table shows the mapping for v4 *Show* property values to the configuration property *Output.Verbosity*: + +| *Show* value | Configuration Object *Output Verbosity* Property | +| ------------ | ------------------------------------------------ | +| All | Detailed | +| Default | Detailed | +| Detailed | Detailed | +| Fails | Normal | +| Diagnostic | Diagnostic | +| Normal | Normal | +| Minimal | Minimal | +| None | None | + + +### Implicit parameters for TestCases + +Test cases are super useful, but I find it a bit annoying, and error prone to define the `param` block all the time, so when invoking `It` I am defining the variables in parent scope, and also splatting them. As a result you don't have to define the `param` block: + +```powershell +Describe "a" { + It "b" -TestCases @( + @{ Name = "Jakub"; Age = 30 } + ) { + $Name | Should -Be "Jakub" + } +} +``` + +This also works for Mock. + +#### Mocks can be debugged + +Mocks don't rewrite the scriptblock you provide anymore. You can now set breakpoints into them as well as any of the ParameterFilter or Should -Invoke Parameter filter. + +#### Avoid putting in InModuleScope around your Describe and It blocks + +`InModuleScope` is a simple way to expose your internal module functions to be tested, but it prevents you from properly testing your published functions, does not ensure that your functions are actually published, and slows down Discovery by loading the module. Aim to avoid it altogether by using `-ModuleName` on `Mock`. Or at least avoid placing `InModuleScope` outside of `It`. diff --git a/versioned_docs/version-v5/quick-start.mdx b/versioned_docs/version-v5/quick-start.mdx new file mode 100644 index 00000000..731c3e2f --- /dev/null +++ b/versioned_docs/version-v5/quick-start.mdx @@ -0,0 +1,338 @@ +--- +id: quick-start +title: Quick Start +sidebar_label: Quick Start +description: Get started using Pester to test your PowerShell scripts, functions and modules +--- + +> **tl;dr:** Here is a [summary.](#summary) + +## What is Pester? + +Pester is a testing and mocking framework for PowerShell. + +Pester provides a framework for writing and running tests. Pester is most commonly +used for writing unit and integration tests, but it is not limited to just that. +It is also a base for tools that validate whole environments, computer deployments, database configurations and so on. + +Pester follows a file naming convention `*.Tests.ps1`, and uses a simple set of functions: +`Describe`, `Context`, `It`, `Should` and `Mock` to create a mini-DSL for writing your tests. + +Pester tests can execute any command or script that is accessible to a Pester test file. This +includes functions, Cmdlets, Modules and scripts. Pester can be run locally, where it integrates well +with Visual Studio Code, and it can of course be integrated into a build script in a CI pipeline. + +Pester contains a powerful set of Mocking capabilities that allow tests to replace the behavior of any +command inside of a piece of PowerShell code being tested. See [Mocking with Pester](./usage/mocking). + +Pester can produce artifacts such as Test Results file and can be used for generating +[Code Coverage](./usage/code-coverage) and [Test Result](./usage/test-results) files for reporting +results in CI pipeline. + +## Installing Pester + +To install Pester it is usually enough to just do `Install-Module Pester -Force`. And then follow it by +`Import-Module Pester -PassThru`. This is the output you should see in the console: + +```powershell +Import-Module Pester -PassThru + +ModuleType Version PreRelease Name +---------- ------- ---------- ---- +Script 5.5.0 Pester +``` + +Full installation guide is available in [installation](introduction/installation). + +## Creating a Pester Test + +To start using Pester, create a new file called `Get-Planet.Tests.ps1`. `Get-Planet` is the name of the function +we will be testing. Feel free to replace that with your own function name. The file name is important because Pester +uses a naming convention, all `*.Tests.ps1` files will be inspected for tests. + +Inside of the file paste this code: + +```powershell +BeforeAll { + function Get-Planet ([string]$Name = '*') { + $planets = @( + @{ Name = 'Mercury' } + @{ Name = 'Venus' } + @{ Name = 'Earth' } + @{ Name = 'Mars' } + @{ Name = 'Jupiter' } + @{ Name = 'Saturn' } + @{ Name = 'Uranus' } + @{ Name = 'Neptune' } + ) | ForEach-Object { [PSCustomObject] $_ } + + $planets | Where-Object { $_.Name -like $Name } + } +} + +Describe 'Get-Planet' { + It 'Given no parameters, it lists all 8 planets' { + $allPlanets = Get-Planet + $allPlanets.Count | Should -Be 8 + } +} +``` + +This code uses multiple Pester keywords, and we will go over them in detail soon, but for now let's just run it. + +In your console run `Invoke-Pester -Output Detailed C:\t\Planets\Get-Planet.Tests.ps1`: + +``` +Starting discovery in 1 files. +Discovering in C:\t\Planets\Get-Planet.Tests.ps1. +Found 1 tests. 41ms +Discovery finished in 77ms. + +Running tests from 'C:\t\Planets\Get-Planet.Tests.ps1' +Describing Get-Planet + [+] Given no parameters, it lists all 8 planets 20ms (18ms|2ms) +Tests completed in 179ms +Tests Passed: 1, Failed: 0, Skipped: 0 NotRun: 0 +``` + +Looking at the last line of output you can see that we ran 1 test and it Passed. Good job, you just ran your first Pester test! 🥳🥳🥳 + +### Understanding our test + +In the previous run, our test passed, and if you'd run it again it would pass again. That is the beauty of automated testing. This is because using the `Should` keyword we are saying: + +> 👉 "There should be 8 items in `$allPlanets`." + +And there are. + +But how did we know that we want to test for exactly that? Well, we didn't. It was just one example of how we could describe our Solar System. You can try remembering some facts about it and try writing them as tests. + +Here are few examples: + +- Earth is the third planet in our Solar System. +- Pluto is not part of our Solar System. +- The planets go in this order: Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune. + + +```powershell +It 'Earth is the third planet in our Solar System' { + $allPlanets = Get-Planet + $allPlanets[2].Name | Should -Be 'Earth' +} +``` + +```powershell +It 'Pluto is not part of our Solar System' { + $allPlanets = Get-Planet + $plutos = $allPlanets | Where-Object Name -EQ 'Pluto' + $plutos.Count | Should -Be 0 +} +``` + +```powershell +It 'Planets have this order: Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune' { + $allPlanets = Get-Planet + $planetsInOrder = $allPlanets.Name -join ', ' + $planetsInOrder | Should -Be 'Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune' +} +``` + +Try adding those tests into your `Get-Planet.Tests.ps1` file. Put them under the other `It` block, but make sure they are placed within the curly braces associated with `Describe`. + +### Breaking our test, by breaking the tested function + +There are few ways to break the test, one of them is adding Pluto back into our Solar System. + +```powershell +$planets = @( + @{ Name = 'Mercury' } + @{ Name = 'Venus' } + @{ Name = 'Earth' } + @{ Name = 'Mars' } + @{ Name = 'Jupiter' } + @{ Name = 'Saturn' } + @{ Name = 'Uranus' } + @{ Name = 'Neptune' } + @{ Name = 'Pluto' } +) | ForEach-Object { [PSCustomObject] $_ } +``` + +This will break the assertion that we have in our test, because we no longer return 8 items from the tested function. Instead we now return 9. Running the test, it will no longer pass: + +``` +Invoke-Pester -Output Detailed C:\t\Planets\Get-Planet.Tests.ps1 + +Starting discovery in 1 files. +Discovering in C:\t\Planets\Get-Planet.Tests.ps1. +Found 1 tests. 9ms +Discovery finished in 21ms. + +Running tests from 'C:\t\Planets\Get-Planet.Tests.ps1' +Describing Get-Planet + [-] Given no parameters, it lists all 8 planets 19ms (12ms|7ms) + Expected 8, but got 9. + at $allPlanets.Count | Should -Be 8, C:\t\Planets\Get-Planet.Tests.ps1:22 + at , C:\t\Planets\Get-Planet.Tests.ps1:22 +Tests completed in 183ms +Tests Passed: 0, Failed: 1, Skipped: 0 NotRun: 0 +``` + +The error is: `Expected 8, but got 9.`, this exactly reflects the change that we made to the tested function. We added one more item to the collection of planets, and the test confirms that the function is now broken. + +### Breaking our test, by breaking the test expectation + +The change that we just did is not the only change that we can make to break the test. There are other ways to do it. We can change the expected count to be 1, saying that there is just one planet orbiting the Sun, by changing the `Should` to `$allPlanets.Count | Should -Be 1`. This will also break the test: + +``` +Describing Get-Planet + [-] Given no parameters, it lists all 8 planets 25ms (21ms|4ms) + Expected 1, but got 8. + at $allPlanets.Count | Should -Be 1, C:\t\Planets\Get-Planet.Tests.ps1:21 + at , C:\t\Planets\Get-Planet.Tests.ps1:21 +Tests completed in 195ms +``` + +The error is: `Expected 1, but got 8.`, this again reflects exactly what we did in the test, but it no longer reflects the real world. + +### How tests break + +If you look closer on how we broke the test, you can see that there are two distinct ways to break it. +- The first was that the tested function did not work correctly, this is a good way to break the test. +- The second one is when the function works correctly, but the test is incorrect. This is a bad way to break the test. + +Being able to distinguish between those two is important, when your test breaks keep in mind that either the function, or the tests might be broken. What you usually do is that you look at what changed more recently. If the test is new, and the function existed for a while, you first blame the test. When the test was passing before, but it is not anymore, you first blame the tested function. + +## Other keywords + +Now that we know about `It`, and `Should`. We can quickly look at the rest of the Pester keywords that we used. + +### Describe + +This keyword allows you to group tests (represented by `It` blocks) into groups. You can have one or more `Describe`s per file. You can also nest `Describe`s into each other to give your test suite more structure. + +A similar keyword to `Describe` is `Context`. In almost all cases `Context` can be used interchangeably with `Describe`. Typically the top-level block is a `Describe` that is named after the function that is being tested. And then, if needed, `Context` blocks are used inside of the `Describe` to group tests based on what aspect of the function you are testing. + +Like this: + +```powershell +Describe 'Get-Planet' { + Context 'no parameters' { + It 'lists all 8 planets' { + # .. + } + + It 'lists them in the correct order' { + # ... + } + } + + Context "with -Filter" { + It 'filters based on planet Name' { + # ... + } + } +} +``` +### BeforeAll + +Now that we split the tests into groups we might want to share some common code among those tests. To do this we `BeforeAll` block that will run at the start of the block that contains it, or at the start of the file if not contained in any block. In our example we used it to define the tested function. + +There is also `AfterAll` block that will run at the end of the block, and `BeforeEach / AfterEach` that will run before every test in the given block. + + +## Splitting to tests and function + +Until now we had just a single file that contained both our tests and the function that's being tested. In real life you want the tested function to be separated from its tests. This way you can run the function, without running the tests with it. + +To move the function out of the test we will move it to a separate file, and will [dot-source](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_scripts?view=powershell-7#script-scope-and-dot-sourcing) it back into the `BeforeAll`. To do this create a new file in the same directory as `Get-Planet.Tests.ps1` and call it `Get-Planet.ps1`. Then cut the function from the test file and paste it into the other file: + +```powershell title="Get-Planet.ps1" +function Get-Planet ([string]$Name = '*') { + $planets = @( + @{ Name = 'Mercury' } + @{ Name = 'Venus' } + @{ Name = 'Earth' } + @{ Name = 'Mars' } + @{ Name = 'Jupiter' } + @{ Name = 'Saturn' } + @{ Name = 'Uranus' } + @{ Name = 'Neptune' } + ) | ForEach-Object { [PSCustomObject] $_ } + + $planets | Where-Object { $_.Name -like $Name } +} +``` + +```powershell title="Get-Planet.Tests.ps1" +BeforeAll { + +} + +Describe 'Get-Planet' { + It 'Given no parameters, it lists all 8 planets' { + $allPlanets = Get-Planet + $allPlanets.Count | Should -Be 8 + } +} +``` + +If we now run the test, we will see that it breaks, because the function is no longer reachable from the test: + +``` +Starting discovery in 1 files. +Discovering in C:\t\Planets\Get-Planet.Tests.ps1. +Found 1 tests. 14ms +Discovery finished in 36ms. + +Running tests from 'C:\t\Planets\Get-Planet.Tests.ps1' +Describing Get-Planet + [-] Given no parameters, it lists all 8 planets 40ms (37ms|3ms) + CommandNotFoundException: The term 'Get-Planet' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. + at , C:\t\Planets\Get-Planet.Tests.ps1:7 +Tests completed in 214ms +Tests Passed: 0, Failed: 1, Skipped: 0 NotRun: 0 +``` + +The error is `CommandNotFoundException: The term 'Get-Planet' is not recognized as the name of a cmdlet, function, script file, or operable program.`. This is because the function is not defined, and we need to make it available to the test. + +> 🤷‍♀ If your test still works, try starting a clean PowerShell session, chances are, you played around with the code, and the tested function is still defined in your scope. Starting a new PowerShell window will clean that up. + +To get the function back to scope we will dot-source (import) the file inside of `BeforeAll`: + +```powershell +BeforeAll { + . $PSScriptRoot/Get-Planet.ps1 +} + +Describe 'Get-Planet' { + It 'Given no parameters, it lists all 8 planets' { + $allPlanets = Get-Planet + $allPlanets.Count | Should -Be 8 + } +} +``` + +``` +Invoke-Pester -Output Detailed C:\t\Planets\Get-Planet.Tests.ps1 + +Starting discovery in 1 files. +Discovering in C:\t\Planets\Get-Planet.Tests.ps1. +Found 1 tests. 19ms +Discovery finished in 31ms. + +Running tests from 'C:\t\Planets\Get-Planet.Tests.ps1' +Describing Get-Planet + [+] Given no parameters, it lists all 8 planets 10ms (5ms|5ms) +Tests completed in 189ms +Tests Passed: 1, Failed: 0, Skipped: 0 NotRun: 0 +``` + +## Summary + +Pester uses a file naming convention `*.Tests.ps1` for test files. Those files are typically named after the tested function, and are placed next to a file that contains the function. The function file is imported via dot-sourcing in the `BeforeAll` on top of the file. And `$PSScriptRoot` is typically used to provide a relative path to the function file. + +Tests are written into `It` blocks and grouped by `Describe` or `Context` into groups. `Should` is used to express what is being tested, and it will fail the test if the condition is not true. + +`Invoke-Pester` can then be used to run the tests in a given test file, and `-Output Detailed` can be used to show every test in the output, no matter if it passed or failed. Otherwise only failed tests, or whole files (when everything passed) are shown. + +To learn more, for example how to run multiple test files in one run, continue to the [Usage](usage/file-placement-and-naming) section. diff --git a/versioned_docs/version-v5/usage/_GetEmoji.mdx b/versioned_docs/version-v5/usage/_GetEmoji.mdx new file mode 100644 index 00000000..de5c749b --- /dev/null +++ b/versioned_docs/version-v5/usage/_GetEmoji.mdx @@ -0,0 +1,24 @@ +
+ Required code for samples (PowerShell 6 or later) +
+ To run the sample below, place this file in the same folder as Get-Emoji.Tests.ps1. + + ```powershell title="Get-Emoji.ps1" + $emojis = @( + @{ Name = 'apple'; Symbol = '🍎'; Kind = 'Fruit' } + @{ Name = 'beaming face with smiling eyes'; Symbol = '😁'; Kind = 'Face' } + @{ Name = 'cactus'; Symbol = '🌵'; Kind = 'Plant' } + @{ Name = 'giraffe'; Symbol = '🦒'; Kind = 'Animal' } + @{ Name = 'pencil'; Symbol = '✏️'; Kind = 'Item' } + @{ Name = 'penguin'; Symbol = '🐧'; Kind = 'Animal' } + @{ Name = 'pensive'; Symbol = '😔'; Kind = 'Face' } + @{ Name = 'slightly smiling face'; Symbol = '🙂'; Kind = 'Face' } + @{ Name = 'smiling face with smiling eyes'; Symbol = '😊'; Kind = 'Face' } + ) | ForEach-Object { [PSCustomObject]$_ } + + function Get-Emoji ([string]$Name = '*') { + $emojis | Where-Object Name -like $Name | ForEach-Object Symbol + } + ``` +
+
diff --git a/versioned_docs/version-v5/usage/_PesterDemoFunctions.mdx b/versioned_docs/version-v5/usage/_PesterDemoFunctions.mdx new file mode 100644 index 00000000..8dab4bfe --- /dev/null +++ b/versioned_docs/version-v5/usage/_PesterDemoFunctions.mdx @@ -0,0 +1,55 @@ +
+ Required code for samples (PowerShell 6 or later) +
+ This module is required for the Emoji and Fruit tests below. Copy and paste this in your console before running the tests. + + ```powershell + Get-Module PesterDemoFunctions | Remove-Module + New-Module PesterDemoFunctions -ScriptBlock { + $emojis = @( + @{ Name = 'apple'; Symbol = '🍎'; Kind = 'Fruit' } + @{ Name = 'beaming face with smiling eyes'; Symbol = '😁'; Kind = 'Face' } + @{ Name = 'cactus'; Symbol = '🌵'; Kind = 'Plant' } + @{ Name = 'giraffe'; Symbol = '🦒'; Kind = 'Animal' } + @{ Name = 'pencil'; Symbol = '✏️'; Kind = 'Item' } + @{ Name = 'penguin'; Symbol = '🐧'; Kind = 'Animal' } + @{ Name = 'pensive'; Symbol = '😔'; Kind = 'Face' } + @{ Name = 'slightly smiling face'; Symbol = '🙂'; Kind = 'Face' } + @{ Name = 'smiling face with smiling eyes'; Symbol = '😊'; Kind = 'Face' } + ) | ForEach-Object { [PSCustomObject]$_ } + + function Get-Emoji ([string]$Name = '*') { + $script:emojis | Where-Object Name -like $Name | ForEach-Object Symbol + } + + function Get-EmojiKind { + param( + [Parameter(Mandatory = $true, ValueFromPipeline = $true)] + [string]$Emoji + ) + process { + $script:emojis | Where-Object Symbol -eq $Emoji | Foreach-Object Kind + } + } + + $fruitBasket = [System.Collections.ArrayList]@('🍎','🍌','🥝','🥑','🍇','🍐') + + function Get-FruitBasket { + $script:fruitBasket + } + + function Remove-FruitBasket { + param( + [Parameter(Mandatory = $true)] + [string]$Item + ) + $script:fruitBasket.Remove($Item) + } + + function Reset-FruitBasket { + $script:fruitBasket = [System.Collections.ArrayList]@('🍎','🍌','🥝','🥑','🍇','🍐') + } + } | Import-Module + ``` +
+
diff --git a/versioned_docs/version-v5/usage/code-coverage.mdx b/versioned_docs/version-v5/usage/code-coverage.mdx new file mode 100644 index 00000000..d56e8d3c --- /dev/null +++ b/versioned_docs/version-v5/usage/code-coverage.mdx @@ -0,0 +1,217 @@ +--- +id: code-coverage +title: Generating Code Coverage Metrics +sidebar_label: Code Coverage +description: Pester can generate code coverage metrics to help you understand how many lines of your PowerShell code that is actually covered by your Pester-tests. Use this to increase confidence in your tests +--- + +Code Coverage refers to the percentage of lines of code that are tested +by a suite of unit tests. It's a good general indicator of how thoroughly +your code has been tested, that all branches and edge cases are working +properly, etc. Pester calculates this coverage during +test execution and generates a report. + +In practice, Pester's Code Coverage analysis provides valuable insights +into the coverage of your code and helps identify untested branches and edge cases. + +## Quickstart + +To generate Code Coverage metrics we no longer rely in the `-CodeCoverage` parameter of the `Invoke-Pester` command. +Pester, offers a new way to configure Code Coverage using `New-PesterConfiguration`, as explained in the following snippet: + + ```powershell + # Create a Pester configuration object using `New-PesterConfiguration` + $config = New-PesterConfiguration + + # Set the test path to specify where your tests are located. In this example, we set the path to the current directory. Pester will look into all subdirectories. + $config.Run.Path = "." + + # Enable Code Coverage + $config.CodeCoverage.Enabled = $true + + # Run Pester tests using the configuration you've created + Invoke-Pester -Configuration $config + + # Example output... + # Tests completed in 8.26s + # Tests Passed: 8, Failed: 0, Skipped: 0 NotRun: 0 + # Processing code coverage result. + # Covered 11.7% / 75%. 735 analyzed Commands in 22 Files. + ``` + +The final line displays both the current code coverage and the desired target coverage. You can customize the target coverage by configuring the CodeCoverage.CoveragePercentTarget option. + +## Examples + +Here are some examples of the various ways the Code Coverage configuration can be used, +and their corresponding output when used with the following files. + +```powershell title="CoverageTest.ps1" +function FunctionOne ([switch] $SwitchParam) +{ + if ($SwitchParam) + { + return 'SwitchParam was set' + } + else + { + return 'SwitchParam was not set' + } +} + +function FunctionTwo +{ + return 'I get executed' + return 'I do not' +} +``` + +```powershell title="CoverageTest.Tests.ps1" +BeforeAll { + . $PSCommandPath.Replace('.Tests.ps1','.ps1') +} + +Describe 'Demonstrating Code Coverage' { + It 'Calls FunctionOne with no switch parameter set' { + FunctionOne | Should -Be 'SwitchParam was not set' + } + + It 'Calls FunctionTwo' { + FunctionTwo | Should -Be 'I get executed' + } +} +``` + +Let's see what is the coverage once executed: + +```powershell +$config = New-PesterConfiguration +$config.Run.Path = ".\CoverageTest.Tests.ps1" +$config.CodeCoverage.Enabled = $true + +# Optional to scope the coverage to the list of files or directories in this path +$config.CodeCoverage.Path = ".\CoverageTest.ps1" + +Invoke-Pester -Configuration $config + +<# +... +Tests completed in 109ms +Tests Passed: 2, Failed: 0, Skipped: 0 NotRun: 0 +Processing code coverage result. +Covered 60% / 75%. 5 analyzed Commands in 1 File. +#> +``` + +When Pester is executed with detailed verbosity enabled, +it provides a comprehensive output that includes detailed information about the covered lines. For example: + + +```powershell +$config = New-PesterConfiguration +$config.Run.Path = ".\CoverageTest.Tests.ps1" +$config.CodeCoverage.Enabled = $true +$config.Output.Verbosity = "Detailed" + +Invoke-Pester -Configuration $config + +<# +... +Tests Passed: 2, Failed: 0, Skipped: 0 NotRun: 0 +Processing code coverage result. +Code Coverage result processed in 22 ms. +Covered 60% / 75%. 5 analyzed Commands in 1 File. +Missed commands: + +File Class Function Line Command +---- ----- -------- ---- ------- +CoverageTest.ps1 FunctionOne 5 return 'SwitchParam was set' +CoverageTest.ps1 FunctionTwo 16 return 'I do not' +#> +``` + +As you can see, the test script fails to run `FunctionOne` with its switch parameter set, +and there is an unreachable line of code in `FunctionTwo`. + +## Coverage Format + +By default, Pester generates a `coverage.xml` file in [JaCoCo](https://www.jacoco.org/) format. You have the flexibility to modify the output format, path, and encoding by using the following options: + +```powershell +$config = New-PesterConfiguration +$config.CodeCoverage.OutputFormat = 'CoverageGutters' +$config.CodeCoverage.OutputPath = 'cov.xml' +$config.CodeCoverage.OutputEncoding = 'UTF8' + +$config.CodeCoverage.Enabled = $true + +Invoke-Pester -Configuration $config +``` + +For additional `CodeCoverage` configuration options, please refer to the [New-PesterConfiguration](https://pester.dev/docs/commands/New-PesterConfiguration) documentation. + +:::tip Pester does not traverse directories. +If you encounter an **empty `coverage.xml` file**, it's likely because you're running the tests from a directory that doesn't +include the relevant code to be covered. +To resolve this, you can either follow the recommended [Test file structure](https://pester.dev/docs/usage/test-file-structure), +which involves placing the tests alongside the code you want to cover, +or set the config `CodeCoverage.Path` option to the directory +that contains the code to be covered. +::: + +## Integrating with GitHub Actions + +To integrate Pester tests with Code Coverage into your GitHub Actions workflow, follow these steps: + +1. Create or update your GitHub Actions workflow file (e.g., `.github/workflows/pester-tests.yml`). Use the following example as a template: + + ```yaml + name: Run Pester Tests + + on: + push: + branches: [ "dev", "main" ] + pull_request: + branches: [ "dev" ] + + jobs: + pester: + runs-on: windows-latest + + steps: + - name: Checkout code + uses: actions/checkout@v2 + + - name: Install Pester + shell: pwsh + run: Install-Module -Name Pester -Force -Scope CurrentUser + + - name: Run Pester Tests + working-directory: ./solution + run: | + # Run Pester tests with Code Coverage + $config = New-PesterConfiguration + $config.Run.Path = "." + $config.CodeCoverage.Enabled = $true + $config.TestResult.Enabled = $true + Invoke-Pester -Configuration $config + + - name: Upload code coverage report + if: ${{ success() }} + uses: actions/upload-artifact@v2 + with: + name: code-coverage-report + path: solution\coverage.xml + ``` + +2. The workflow defined above triggers on pushes to the "dev" and "main" branches and on pull requests targeting the "dev" branch. Make sure to adjust the branch names as needed. + +3. This workflow runs on a Windows environment and does the following: + - Checks out the code. + - Installs the Pester module. + - Runs Pester tests with Code Coverage. + - Uploads the code coverage report as an artifact. + +4. Adjust the paths and configurations in the workflow according to your project structure and requirements. + +With this configuration, Pester tests will be executed with Code Coverage, and the coverage report will be available as an artifact in your GitHub Actions workflow. \ No newline at end of file diff --git a/versioned_docs/version-v5/usage/configuration.mdx b/versioned_docs/version-v5/usage/configuration.mdx new file mode 100644 index 00000000..c51f1f61 --- /dev/null +++ b/versioned_docs/version-v5/usage/configuration.mdx @@ -0,0 +1,256 @@ +--- +title: Configuration +description: Documentation about how to configure the behavior, options and features in Pester +--- + +### Advanced interface + +Advanced interface uses `PesterConfiguration` object which contains all options that you can provide to Pester and contains descriptions for all the configuration sections and as well as default values. Here is what you see when you look at the default Debug section of the object: + +```powershell +[PesterConfiguration]::Default.Debug | Format-List + +ShowFullErrors : Show full errors including Pester internal stack. (False, default: False) +WriteDebugMessages : Write Debug messages to screen. (False, default: False) +WriteDebugMessagesFrom : Write Debug messages from a given source, WriteDebugMessages must be set to true for this to work. You can use like wildcards to get messages from multiple sources, as well as * to get everything. (*, default: *) +ShowNavigationMarkers : Write paths after every block and test, for easy navigation in VSCode. (False, default: False) +``` + +:::tip New in Pester 5.2.0! +[New-PesterConfiguration](../commands/New-PesterConfiguration) is now available and the recommended way to create the PesterConfiguration-object. It has the added benefit of auto-loading the Pester-module if needed and up-to-date help of available options in the configuration object. +::: + +The configuration object can be constructed either via the Default static property or by casting a hashtable to it. You can also cast a hashtable to any of its sections. Here are three different ways to the same goal: + +```powershell +# import module before creating the object +Import-Module Pester +# get default from static property +$configuration = [PesterConfiguration]::Default +# adding properties & discover via intellisense +$configuration.Run.Path = 'C:\projects\tst' +$configuration.Filter.Tag = 'Acceptance' +$configuration.Filter.ExcludeTag = 'WindowsOnly' +$configuration.Should.ErrorAction = 'Continue' +$configuration.CodeCoverage.Enabled = $true +``` + +```powershell +# cast whole hashtable to configuration +$configuration = [PesterConfiguration]@{ + Run = @{ + Path = 'C:\projects\tst' + } + Filter = @{ + Tag = 'Acceptance' + ExcludeTag = 'WindowsOnly' + } + Should = @{ + ErrorAction = 'Continue' + } + CodeCoverage = @{ + Enabled = $true + } +} +``` + +```powershell +# cast from empty hashtable to get default +$configuration = [PesterConfiguration]@{} +$configuration.Run.Path = 'C:\projects\tst' +# cast hashtable to section +$configuration.Filter = @{ + Tag = 'Acceptance' + ExcludeTag = 'WindowsOnly' + } +$configuration.Should.ErrorAction = 'Continue' +$configuration.CodeCoverage.Enabled = $true +``` + +This configuration object contains all the options that are currently supported and the Simple interface is internally translates to this object internally. It is the source of truth for the defaults and configuration. The Intermediate api will be figured out later, as well as all the other details. + +### PesterPreference + +There is one more way to provide the configuration object which is `$PesterPreference`. On `Invoke-Pester` (in case of interactive execution `Invoke-Pester` is called inside of the first `Describe`) the preference is collected and merged with the configuration object if provided. This allows you to configure everything that you would via Invoke-Pester also when you are running interactively (via `F5`). You can also use this to define the defaults for your session by putting $PesterPreference into your PowerShell profile. + +Here is a simple example of enabling Mock logging output while running interactively : + +```powershell +$PesterPreference = [PesterConfiguration]::Default +$PesterPreference.Debug.WriteDebugMessages = $true +$PesterPreference.Debug.WriteDebugMessagesFrom = "Mock" + +BeforeAll { + function a { "hello" } +} +Describe "pester preference" { + It "mocks" { + Mock a { "mock" } + a | Should -Be "mock" + } +} +``` + +``` +Starting test discovery in 1 files. +Discovering tests in C:\Users\jajares\Desktop\mck.tests.ps1. +Found 1 tests. 44ms +Test discovery finished. 80ms + + +Running tests from 'C:\Users\jajares\Desktop\mck.tests.ps1' +Describing pester preference +Mock: Setting up mock for a. +Mock: We are in a test. Returning mock table from test scope. +Mock: Resolving command a. +Mock: Searching for command in the caller scope. +Mock: Found the command a in the caller scope. +Mock: Mock does not have a hook yet, creating a new one. +Mock: Defined new hook with bootstrap function PesterMock_b0bde5ee-1b4f-4b8f-b1dd-aef38b3bc13d and aliases a. +Mock: Adding a new default behavior to a. +Mock: Mock bootstrap function a called from block Begin. +Mock: Capturing arguments of the mocked command. +Mock: Mock for a was invoked from block Begin. +Mock: Getting all defined mock behaviors in this and parent scopes for command a. +Mock: We are in a test. Finding all behaviors in this test. +Mock: Found behaviors for 'a' in the test. +Mock: Finding all behaviors in this block and parents. +... shortened Mock does a lot of stuff +Verifiable: False +Mock: We are in a test. Returning mock table from test scope. +Mock: Removing function PesterMock_b0bde5ee-1b4f-4b8f-b1dd-aef38b3bc13d and aliases a for . + [+] mocks 857ms (840ms|16ms) +Tests completed in 1.12s +Tests Passed: 1, Failed: 0, Skipped: 0, Total: 1, NotRun: 0 +``` + +## PesterConfiguration Options + + + +*This section was generated using Pester 5.6.0.* + +### Run + +Run configuration. + +
+| Option | Description | Type | Default | +|--------|-------------|-----:|--------:| +| Run.Path | Directories to be searched for tests, paths directly to test files, or combination of both. | `string[]` | `@('.')` | +| Run.ExcludePath | Directories or files to be excluded from the run. | `string[]` | `@()` | +| Run.ScriptBlock | ScriptBlocks containing tests to be executed. | `scriptblock[]` | `@()` | +| Run.Container | ContainerInfo objects containing tests to be executed. | `ContainerInfo[]` | `@()` | +| Run.TestExtension | Filter used to identify test files. | `string` | `'.Tests.ps1'` | +| Run.Exit | Exit with non-zero exit code when the test run fails. Exit code is always set to `$LASTEXITCODE` even when this option is `$false`. When used together with Throw, throwing an exception is preferred. | `bool` | `$false` | +| Run.Throw | Throw an exception when test run fails. When used together with Exit, throwing an exception is preferred. | `bool` | `$false` | +| Run.PassThru | Return result object to the pipeline after finishing the test run. | `bool` | `$false` | +| Run.SkipRun | Runs the discovery phase but skips run. Use it with PassThru to get object populated with all tests. | `bool` | `$false` | +| Run.SkipRemainingOnFailure | Skips remaining tests after failure for selected scope, options are None, Run, Container and Block. | `string` | `'None'` | +
+ +### Filter + +Filter configuration + +
+| Option | Description | Type | Default | +|--------|-------------|-----:|--------:| +| Filter.Tag | Tags of Describe, Context or It to be run. | `string[]` | `@()` | +| Filter.ExcludeTag | Tags of Describe, Context or It to be excluded from the run. | `string[]` | `@()` | +| Filter.Line | Filter by file and scriptblock start line, useful to run parsed tests programmatically to avoid problems with expanded names. Example: 'C:\tests\file1.Tests.ps1:37' | `string[]` | `@()` | +| Filter.ExcludeLine | Exclude by file and scriptblock start line, takes precedence over Line. | `string[]` | `@()` | +| Filter.FullName | Full name of test with -like wildcards, joined by dot. Example: '*.describe Get-Item.test1' | `string[]` | `@()` | +
+ +### CodeCoverage + +CodeCoverage configuration. + +
+| Option | Description | Type | Default | +|--------|-------------|-----:|--------:| +| CodeCoverage.Enabled | Enable CodeCoverage. | `bool` | `$false` | +| CodeCoverage.OutputFormat | Format to use for code coverage report. Possible values: JaCoCo, CoverageGutters | `string` | `'JaCoCo'` | +| CodeCoverage.OutputPath | Path relative to the current directory where code coverage report is saved. | `string` | `'coverage.xml'` | +| CodeCoverage.OutputEncoding | Encoding of the output file. | `string` | `'UTF8'` | +| CodeCoverage.Path | Directories or files to be used for code coverage, by default the Path(s) from general settings are used, unless overridden here. | `string[]` | `@()` | +| CodeCoverage.ExcludeTests | Exclude tests from code coverage. This uses the TestFilter from general configuration. | `bool` | `$true` | +| CodeCoverage.RecursePaths | Will recurse through directories in the Path option. | `bool` | `$true` | +| CodeCoverage.CoveragePercentTarget | Target percent of code coverage that you want to achieve, default 75%. | `decimal` | `75` | +| CodeCoverage.UseBreakpoints | EXPERIMENTAL: When false, use Profiler based tracer to do CodeCoverage instead of using breakpoints. | `bool` | `$true` | +| CodeCoverage.SingleHitBreakpoints | Remove breakpoint when it is hit. | `bool` | `$true` | +
+ +### TestResult + +TestResult configuration. + +
+| Option | Description | Type | Default | +|--------|-------------|-----:|--------:| +| TestResult.Enabled | Enable TestResult. | `bool` | `$false` | +| TestResult.OutputFormat | Format to use for test result report. Possible values: NUnitXml, NUnit2.5, NUnit3 or JUnitXml | `string` | `'NUnitXml'` | +| TestResult.OutputPath | Path relative to the current directory where test result report is saved. | `string` | `'testResults.xml'` | +| TestResult.OutputEncoding | Encoding of the output file. | `string` | `'UTF8'` | +| TestResult.TestSuiteName | Set the name assigned to the root 'test-suite' element. | `string` | `'Pester'` | +
+ +### Should + +Should configuration. + +
+| Option | Description | Type | Default | +|--------|-------------|-----:|--------:| +| Should.ErrorAction | Controls if Should throws on error. Use 'Stop' to throw on error, or 'Continue' to fail at the end of the test. | `string` | `'Stop'` | +
+ +### Debug + +Debug configuration for Pester. ⚠ Use at your own risk! + +
+| Option | Description | Type | Default | +|--------|-------------|-----:|--------:| +| Debug.ShowFullErrors | Show full errors including Pester internal stack. This property is deprecated, and if set to true it will override Output.StackTraceVerbosity to 'Full'. | `bool` | `$false` | +| Debug.WriteDebugMessages | Write Debug messages to screen. | `bool` | `$false` | +| Debug.WriteDebugMessagesFrom | Write Debug messages from a given source, WriteDebugMessages must be set to true for this to work. You can use like wildcards to get messages from multiple sources, as well as * to get everything. | `string[]` | `@('Discovery', 'Skip', 'Mock', 'CodeCoverage')` | +| Debug.ShowNavigationMarkers | Write paths after every block and test, for easy navigation in VSCode. | `bool` | `$false` | +| Debug.ReturnRawResultObject | Returns unfiltered result object, this is for development only. Do not rely on this object for additional properties, non-public properties will be renamed without previous notice. | `bool` | `$false` | +
+ +### Output + +Output configuration + +
+| Option | Description | Type | Default | +|--------|-------------|-----:|--------:| +| Output.Verbosity | The verbosity of output, options are None, Normal, Detailed and Diagnostic. | `string` | `'Normal'` | +| Output.StackTraceVerbosity | The verbosity of stacktrace output, options are None, FirstLine, Filtered and Full. | `string` | `'Filtered'` | +| Output.CIFormat | The CI format of error output in build logs, options are None, Auto, AzureDevops and GithubActions. | `string` | `'Auto'` | +| Output.CILogLevel | The CI log level in build logs, options are Error and Warning. | `string` | `'Error'` | +| Output.RenderMode | The mode used to render console output, options are Auto, Ansi, ConsoleColor and Plaintext. | `string` | `'Auto'` | +
+ +### TestDrive + +TestDrive configuration. + +
+| Option | Description | Type | Default | +|--------|-------------|-----:|--------:| +| TestDrive.Enabled | Enable TestDrive. | `bool` | `$true` | +
+ +### TestRegistry + +TestRegistry configuration. + +
+| Option | Description | Type | Default | +|--------|-------------|-----:|--------:| +| TestRegistry.Enabled | Enable TestRegistry. | `bool` | `$true` | +
+ diff --git a/versioned_docs/version-v5/usage/data-driven-tests.mdx b/versioned_docs/version-v5/usage/data-driven-tests.mdx new file mode 100644 index 00000000..51868f13 --- /dev/null +++ b/versioned_docs/version-v5/usage/data-driven-tests.mdx @@ -0,0 +1,691 @@ +--- +title: Data driven tests +description: Pester can generate tests based on data. This can range from providing multiple examples on a single `It`, to generating whole set of tests based on an external configuration file +--- + +> Migrating from Pester v4? Jump to [Migrating from Pester v4](#migrating-from-pester-v4). + +Pester can generate tests based on data. This can range from providing multiple examples on a single `It`, to generating whole set of tests based on an external configuration file. + +## Using `-ForEach` & `-TestCases` with hashtable + +The most common usage of data driven tests is providing multiple examples to a single `It`. This way we reuse the body of the test. And decorate the test with examples of its usage. This is superior to copy-pasting tests for each example, because the amount of code to maintain is reduced, the amount of typos is reduced, and it is very easy to add more examples. + +To define examples for a test, use `-ForEach` on an `It` block. On `It` block the parameter is also aliased `-TestCases` for backwards compatibility. + +The data are provided as an array of hashtables: + +import PesterDemoFunctions from './_PesterDemoFunctions.mdx'; + + + +```powershell +Describe "Get-Emoji" { + It "Returns ()" -ForEach @( + @{ Name = "cactus"; Expected = '🌵'} + @{ Name = "giraffe"; Expected = '🦒'} + ) { + Get-Emoji -Name $name | Should -Be $expected + } +} +``` + +`@()` is an array. One test will be generated for each item in the array. + +Inside of the `@()` array, a hashtable is provided `@{}`. This hashtable can have multiple keys, here it is `Name` and `Expected`, and each one of those keys will be defined as a variable in the test. These variables can be used in the test, and also in the `<>` templates, described below. + +The code above will generate tests that are equivalent to this: + +```powershell +Describe "Get-Emoji" { + It "Returns 🌵 (cactus)" { + Get-Emoji -Name cactus | Should -Be '🌵' + } + + It "Returns 🦒 (giraffe)" { + Get-Emoji -Name giraffe | Should -Be '🦒' + } +} +``` + +Using `-ForEach` (or `-TestCases`) we can now very easily provide more examples just by adding more data: + +```powershell +Describe "Get-Emoji" { + It "Returns ()" -ForEach @( + @{ Name = "cactus"; Expected = '🌵'} + @{ Name = "giraffe"; Expected = '🦒'} + @{ Name = "apple"; Expected = '🍎'} + @{ Name = "pencil"; Expected = '✏️'} + @{ Name = "penguin"; Expected = '🐧'} + @{ Name = "smiling face with smiling eyes"; Expected = '😊'} + ) { + Get-Emoji -Name $name | Should -Be $expected + } +} +``` + +#### `-ForEach` on `Describe` and `Context` + +The same `-ForEach` syntax is used on `Describe` (or `Context`) to generate those blocks from the provided data: + +```powershell +Describe "Get-Emoji " -ForEach @( + @{ Name = "cactus"; Symbol = '🌵'; Kind = 'Plant' } + @{ Name = "giraffe"; Symbol = '🦒'; Kind = 'Animal' } +) { + It "Returns " { + Get-Emoji -Name $name | Should -Be $symbol + } + + It "Has kind " { + Get-Emoji -Name $name | Get-EmojiKind | Should -Be $kind + } +} +``` + +Which is equivalent to writing: + +```powershell +Describe "Get-Emoji cactus" { + It "Returns 🌵" { + Get-Emoji -Name cactus | Should -Be '🌵' + } + + It "Has kind Plant" { + Get-Emoji -Name cactus | Get-EmojiKind | Should -Be 'Plant' + } +} + +Describe "Get-Emoji giraffe" { + It "Returns 🦒" { + Get-Emoji -Name giraffe | Should -Be '🦒' + } + + It "Has kind Animal" { + Get-Emoji -Name giraffe | Get-EmojiKind | Should -Be 'Animal' + } +} +``` + +#### Choosing a subset of data + +The provided data will be available in both `Discovery` and `Run`, which allows us to generate tests based on the current data. Here for example we generate tests in a `Context`, based on the data provided to the `Describe`: + +```powershell +Describe "Get-Emoji " -ForEach @( + @{ + Name = "cactus"; + Symbol = '🌵'; + Kind = 'Plant' + Runes = @( + @{ Index = 0; Rune = 127797 } + ) + } + @{ + Name = "pencil" + Symbol = '✏️' + Kind = 'Item' + Runes = @( + @{ Index = 0; Rune = 9999 } + @{ Index = 1; Rune = 65039 } + ) + } +) { + It "Returns " { + Get-Emoji -Name $name | Should -Be $symbol + } + + It "Has kind " { + Get-Emoji -Name $name | Get-EmojiKind | Should -Be $kind + } + + Context "Runes (each character in multibyte emoji)" -ForEach $runes { + It "Has rune on index " { + $actual = @((Get-Emoji -Name $name).EnumerateRunes()) + $actual[$index].Value | Should -Be $rune + } + } +} +``` + + + +## Using `-ForEach` & `-TestCases` with an array + +`-ForEach` is most powerful when used with an array of hashtables, but it can take any array. In that case it will define `$_` variable, representing the current item. This approach can be used on `Describe`, `Context` and `It`: + +```powershell +Describe "Get-FruitBasket" { + It "Contains <_>" -ForEach '🍎','🍌','🥝','🥑','🍇','🍐' { + Get-FruitBasket | Should -Contain $_ + } +} + +Describe "Get-FruitBasket" { + Context "Fruit <_>" -ForEach '🍎','🍌','🥝','🥑','🍇','🍐' { + It "Contains <_> by default" { + Get-FruitBasket | Should -Contain $_ + } + + It "Can remove <_> from the basket" { + Remove-FruitBasket -Item $_ + Get-FruitBasket | Should -Not -Contain $_ + } + } + AfterAll { + Reset-FruitBasket + } +} +``` + +:::tip +`-ForEach` defines the `$_` variable even when used with an array of hashtables. In that case `$_` will be set to the current hashtable. +::: + +## Using `<>` templates + +Test and block names can contain values surrounded by `<>` in their name. Those will be considered a template, and will be expanded. Any variable available in scope can be expanded using this syntax, not just the data from `-ForEach`: + +```powershell +BeforeAll { + $apple = '🍎' +} + +Describe "" { + It " " -ForEach @( + @{ Animal = "🐛" } + @{ Animal = "🐶" } + ) { + # ... + } +} +``` +``` +Describing 🍎 + [+] 🍎 🐛 5ms (3ms|2ms) + [+] 🍎 🐶 2ms (1ms|1ms) +``` + +Additionally, the expansion of the string is postponed after the setup for the current block or test. This enables you to expand variables defined in `BeforeAll`, and `BeforeEach` of the current block, even though the code is visually below the name of the block: + +```powershell +Describe "" { + BeforeAll { + $banana = '🍌' + } + + BeforeEach { + $giraffe = '🦒' + } + + It " " { + # ... + } +} +``` + +``` +Describing 🍌 + [+] 🍌 🦒 7ms (5ms|3ms) +``` + +#### `<_>` in template + +The current item in the provided array is represented by `$_` and can be expanded by using `<_>` template. + +```powershell +Describe "Animals " { + It "<_>" -ForEach @("🐛", "🐶") { + # ... + } +} +``` +``` +Describing Animals + [+] 🐛 7ms (2ms|5ms) + [+] 🐶 2ms (1ms|1ms) +``` + +### Using dot-navigation in `<>` template + +The `<>` templates allow to navigate through the provided object by using dot-notation. This is useful when the data are not just a flat structure: + +```powershell +Describe "Animals" { + It "A () goes " -ForEach @( + @{ + Name = "cow" + Animal = @{ + Sound = "Mooo" + Emoji = "🐄" + } + } + + @{ + Name = "fox" + Animal = @{ + Sound = "Ring-ding-ding-ding-dingeringeding!" + Emoji = "🦊" + } + } + ) { + # ... + } +} +``` +``` +Describing Animals + [+] A 🐄 (cow) goes Mooo 12ms (1ms|11ms) + [+] A 🦊 (fox) goes Ring-ding-ding-ding-dingeringeding! 2ms (1ms|1ms) +``` + + +### Escaping + +Before the template string is expanded every `$` and `` ` `` in the text is escaped. This allows you to put literals, such as `$null` in your test names, and still use the template to expand the value: + +```powershell +Describe "Fruit" -ForEach "🍎", "🍐" { + # with single quoted string + It 'Getting <_> returns $null' { + # ... + } + + # with double quoted string + It "Getting <_> returns `$null" { + # ... + } +} +``` +``` +Describing Fruit + [+] Getting 🍎 returns $null 3ms (1ms|2ms) + [+] Getting 🍎 returns $null 2ms (1ms|1ms) + +Describing Fruit + [+] Getting 🍐 returns $null 3ms (1ms|3ms) + [+] Getting 🍐 returns $null 1ms (1ms|1ms) +``` + +To avoid a `<` from being considered a template use `` `< `` to escape it. This allows you to put greater than and less than in your test names. Or to wrap values in `<>`: + +```powershell +# with single quoted string +Describe 'When x `< 4, x: <_>' -ForEach @(1..4) { + It 'x: `<<_>`>' { + # ... + } +} + +# with double quoted string +Describe "When x ``< 4, x: <_>" -ForEach @(1..4) { + It "x: ``<<_>``>" { + # ... + } +} +``` +``` +Describing When x < 4, x: 1 + [+] x: <1> 3ms (1ms|3ms) + +Describing When x < 4, x: 2 + [+] x: <2> 6ms (0ms|6ms) + +Describing When x < 4, x: 3 + [+] x: <3> 5ms (1ms|5ms) + +Describing When x < 4, x: 4 + [+] x: <4> 4ms (0ms|4ms) +``` + +#### Internals + +The value in the string is escaped by adding `` ` `` before every `$` and `` ` ``. Every template is prefixed by `$`, and then the string is expanded: + +``` +" should not be `$null" + +# because this is double quoted string it will be +# expanded by powershell to + + should not be $null + +# then escaped by us to + should not be `$null + +# template is replaced +$x should not be `$null + +# and then it is evaluated in the appropriate script scope +$x = 1 +& { "$x should not be `$null" } + +# giving the final text +1 should not be $null +``` + +#### + +## Providing external data to tests + +`.Tests.ps1` script is a PowerShell script as any other and you can use the `param` block in it. Script parameters are available in both `Discovery` and `Run`. This is very useful when reusing a single test file with multiple data sets. For example when writing a generic test suite that ensures that correct style is used in a given script file: + +```powershell title="CodingStyle.Tests.ps1" +param ( + [Parameter(Mandatory)] + [string] $File +) + +BeforeAll { + $content = Get-Content $File +} + +Describe "File - " { + Context "Whitespace" { + It "There is no extra whitespace following a line" { + # ... + } + + It "File ends with an empty line" { + # ... + } + } +} +``` + +The external data are then provided to the test by `-Data` parameter on `New-PesterContainer`, in the same manner `-ForEach` would be used on `Describe` or `It`: + +```powershell +$container = New-PesterContainer -Path 'CodingStyle.Tests.ps1' -Data @{ File = "Get-Emoji.ps1" } +Invoke-Pester -Container $container -Output Detailed +``` + +``` +Running tests from 'C:\p\style\CodingStyle.Tests.ps1' +Describing File - Get-Emoji.ps1 + Context Whitespace + [+] There is no extra whitespace following a line 30ms (1ms|30ms) + [+] File ends with an empty line 2ms (1ms|1ms) +Tests completed in 445ms +Tests Passed: 2, Failed: 0, Skipped: 0 NotRun: 0 +``` + +:::note +`$PSBoundParameters` is not available in Pester tests. Reference parameters by their variables like `$File` in the example above. +::: + +#### Re-using the same test file + +In the scenario above we tested just a single file, but chances are we want to run those style tests for every file in the repository. This can be achieved by generating one data item for each file: + +```powershell +$files = 'Get-Emoji.ps1', 'Get-Planet.ps1' +$containers = $files | ForEach-Object { + New-PesterContainer -Path 'CodingStyle.Tests.ps1' -Data @{ File = $_ } +} + +Invoke-Pester -Container $containers -Output Detailed +``` + +This will run the test file twice, once for each file. You could even grab all `.ps1` files in the current Path and test them, just by using `$files = Get-ChildItem -Filter '*.ps1' -Recurse`. + +The `-Data` parameter takes an array of hashtables. As an alternative to the code above, you also attach all the test data to a single container: + +```powershell +$files = 'Get-Emoji.ps1', 'Get-Planet.ps1' +$data = $files | ForEach-Object { + @{ File = $_ } +} + +$container = New-PesterContainer -Path 'CodingStyle.Tests.ps1' -Data $data +Invoke-Pester -Container $container -Output Detailed +``` + +There is no advantage in using one over the other, choose the one that suits your needs better. + +#### Re-using the same data set + +In the example above we had a single test file, and multiple different data sets. We can also have the opposite. A single data set used by multiple test files: + +```powershell +$data = @{ File = "Get-Emoji.ps1" } +$containers = @( + (New-PesterContainer -Path 'CodingStyle.Tests.ps1' -Data $data) + (New-PesterContainer -Path 'BadWords.Tests.ps1' -Data $data) +) +Invoke-Pester -Container $containers -Output Detailed + +# or simply + +$data = @{ File = "Get-Emoji.ps1" } +$container = New-PesterContainer -Path 'CodingStyle.Tests.ps1', 'BadWords.Tests.ps1' -Data $data +Invoke-Pester -Container $container -Output Detailed +``` + +#### Wildcards + +`New-PesterContainer` resolves the `-Path` parameter the same way `Invoke-Pester` does. You can use it to provide a wildcard path to run all files matching the pattern. For example to run all *Style tests against all files in the current directory: + +```powershell +$files = Get-ChildItem -Filter '*.ps1' -Recurse +$data = $files | ForEach-Object { + @{ File = $_.FullName } +} + + +$containers = New-PesterContainer -Path '*Style.Tests.ps1' -Data $data +Invoke-Pester -Container $containers -Output Detailed +``` + +## `BeforeDiscovery` + +In Pester v4 it was normal to place code directly on top of the script file, or directly into the body of `Describe` and `Context`. Pester v5 discourages this, because all code directly in script or in `Describe / Context` body will run during `Discovery`. This leads to unexpected results. + +BUT in some cases, especially when generating tests, putting code directly in script body is okay. `BeforeDiscovery` was introduced to show that the code is like this intentionally, and not by accident. Wrapping code into `BeforeDiscovery` has no impact on its execution. It should be used everywhere where code is intentionally placed outside of a Pester controlled leaf-block (see [Discovery and Run](discovery-and-run)). That is on top of files, or directly in body of `Describe / Context`. + +Here for example I generate one `Describe` for each script file, instead of passing the list of files externally. I need this code to run during `Discovery` to generate those blocks. `BeforeDiscovery` is used there to show that this code placement is intentional: + +```powershell +BeforeDiscovery { + $files = Get-ChildItem -Path $PSScriptRoot -Filter '*.ps1' -Recurse +} + +Describe "File - <_>" -ForEach $files { + Context "Whitespace" { + It "There is no extra whitespace following a line" { + # ... + } + + It "File ends with an empty line" { + # ... + } + } +} +``` + + +## Migrating from Pester v4 + +There are two main things to take into account when Data driven tests in Pester v5: The [execution is not top down](#execution-is-not-top-down) like in V4 but done in two phases `Discovery` and `Run`. Variables from `Discovery` are not available in `Run`, unless you explicitly attach them to a `Describe`, `Context` or `It` using `Foreach` or `TestCases` + +This has big impact the classic pattern of using `foreach` to generate tests. + +### Execution is not top down + +Pester v5 introduces a new two phase execution. In the first phase called `Discovery`, it will run your whole test script from top to bottom. It will also run all ScriptBlocks that you provided to any `Describe`, `Context` and `BeforeDiscovery`. It will collect the ScriptBlocks you provided to `It`, `BeforeAll`, `BeforeEach`, `AfterEach` and `AfterAll`, but won't run them until later. + +| Phase | V4 | V5 Discovery | V5 Run | +| :---------------- | :--- | :----------- | :----- | +| `BeforeAll` | ✔️ | ❌ | ✔️ | +| `BeforeEach` | ✔️ | ❌ | ✔️ | +| `It` | ✔️ | ❌ | ✔️ | +| `AfterEach` | ✔️ | ❌ | ✔️ | +| `AfterAll` | ✔️ | ❌ | ✔️ | +| `BeforeDiscovery` | N/A | ✔️ | ❌ | +| `Describe` | ✔️ | ✔️ | ❌ | +| `Context` | ✔️ | ✔️ | ❌ | +| Other | ✔️ | ✔️ | ❌ | + +Other, is any script outside of `It`, `BeforeAll`, `BeforeEach`, `AfterEach` and `AfterAll`. You see that this code behaves like the new `BeforeDiscovery` block and thus for clarity on when script will be run its advised to use the `BeforeDiscovery`. + +In simple terms this means that the script below will run until the last line during `Discovery`. But no test will be executed: + +```powershell +Write-Host "We are starting with discovery." +Describe "d" { + Write-Host "We are finding tests in this describe." + It "i" { + Write-Host "I am running!" + } + + Write-Host "We are leaving this describe." +} + +Write-Host "We are done with discovery!" +``` + +``` +Starting discovery in 1 files. +Discovering in C:\p\g.Tests.ps1. +We are starting with discovery. +We are finding tests in this describe. +We are leaving this describe. +We are done with discovery! +Found 1 tests. 35ms +Discovery finished in 43ms. + +Running tests from 'C:\p\g.Tests.ps1' +Describing d +I am running! + [+] i 5ms (2ms|3ms) +Tests completed in 256ms +``` + +Notice that "We are done with discovery!" is placed at the end of the script, but is printed before "I am running!". This is because we postpone the execution of `It` until the `Run` phase. + +### Variables defined during `Discovery` are not available in `Run` + +Defining a variable directly in the body of the script, will make it available during `Discovery`, but it won't be available during `Run`. You can see that the test failed because `$name` is not defined. + +```powershell +$name = "Jakub" + +Describe "d" { + It "My name is: $name" { + $name | Should -be "Jakub" + } +} +``` +``` +Starting discovery in 1 files. +Discovering in C:\p\g.Tests.ps1. +Found 1 tests. 21ms +Discovery finished in 65ms. + +Running tests from 'C:\p\g.Tests.ps1' +Describing d + [-] My name is: Jakub 106ms (103ms|3ms) + Expected 'Jakub', but got $null. + at $name | Should -be "Jakub", C:\p\g.Tests.ps1:5 + at , C:\p\g.Tests.ps1:5 +Tests completed in 436ms +Tests Passed: 0, Failed: 1, Skipped: 0 NotRun: 0 +``` + +This is especially confusing because `$name` was correctly expanded in the name of the test. But if you think about it, it is logical. The script is running till the end, so the string `"My name is: $name"` is expanded during `Discovery` where the `$name` variable *is* available. + +### Moving away from `foreach` + +Those two limitations mean that this pattern, is difficult to use: + +```powershell +$files = Get-ChildItem "../src/*.ps1" -Recurse +foreach ($file in $files) { + Describe "$file" { + It "$file - has help" { + $content = Get-Content $file + # ... + } + } +} +``` + +The `$file` variable won't be defined in the `It` and the test will fail. You can work around this problem by specifying a single item `-ForEach` to attach the value to the block. `-ForEach` (and `-TestCases`) will inspect the provided value, and if it is a hashtable, it will define a variable for each key in that hashtable. + +```powershell +$files = Get-ChildItem "../src/*.ps1" -Recurse +foreach ($file in $files) { + Describe "$file" -ForEach { File = $file } { + It "$file - has help" { + $content = Get-Content $file + # ... + } + } +} +``` + +This will take the value of `$file` during `Discovery` and attach it to that `Describe` block, and then during `Run` it will define a new variable `$file` with the same value. + +Next step is to move to `-ForEach` functionality entirely: + +```powershell +BeforeDiscovery { + $files = Get-ChildItem "../src/*.ps1" -Recurse +} + +Describe "" -ForEach $files { + BeforeAll { + # Renaming the automatic $_ variable to $file + # to make it easier to work with + $file = $_ + } + It " - has help" { + $content = Get-Content $file + # ... + } +} +``` + +There are three notable changes: + +- `$files` are defined inside of `BeforeDiscovery` block, to show that this code is running in `Discovery` intentionally, and not by accident +- `$files` is provided directly to `-ForEach`. This will generate one `Describe` for each item in `$file`, and will define the current item as `$_` which is available in both `Discovery` and `Run`. + +- The names of tests are using the `<>` template to expand the variable `$file` during `Run`. Any variable in scope can be used for that expansion, including the variables defined in the `BeforeAll` that is contained directly inside of the current `Describe`. + +### Another variation on `foreach` + +One more common approach is to put common test setup directly in the `Describe` block to ensure that the file will be loaded only once: + +```powershell +$files = Get-ChildItem "../src/*.ps1" -Recurse +foreach ($file in $files) { + Describe "$file" { + $content = Get-Content $file + It "$file - has help" { + # ... + } + } +} +``` + +This approach can still be easily converted to Pester v5: + +```powershell +BeforeDiscovery { + $files = Get-ChildItem "../src/*.ps1" -Recurse +} + +Describe "" -ForEach $files { + BeforeAll { + # Renaming the automatic $_ variable to $file + # to make it easier to work with + $file = $_ + $content = Get-Content $file + } + It " - has help" { + # ... + } +} +``` diff --git a/versioned_docs/version-v5/usage/discovery-and-run.mdx b/versioned_docs/version-v5/usage/discovery-and-run.mdx new file mode 100644 index 00000000..200963a6 --- /dev/null +++ b/versioned_docs/version-v5/usage/discovery-and-run.mdx @@ -0,0 +1,168 @@ +--- +title: Discovery and Run +description: Pester runs your test files in two phases, Discovery and Run. This introduction explains how they work and how it affects they way your structure and write your tests +--- + +Pester runs your test files in two phases: Discovery and Run. During discovery, it quickly scans your test files and discovers all the Describes, Contexts, Its and other Pester blocks. + +This powers many of the features in Pester 5 and enables many others to be implemented in the future. + +To reap the benefits, there are two rules to follow: + +**Put all your test-code into `It`, `BeforeAll`, `BeforeEach`, `AfterAll` or `AfterEach`.** + +**Put no test-code directly into `Describe`, `Context` or on the top of your file, without wrapping it in one of these blocks.** + +All misplaced code will run during Discovery, and its results won't be available during Run. This will lead to confusing results. + +Running code in Discovery is used for dynamically creating tests. That code should be placed into `BeforeDiscovery`, see [Data driven tests](data-driven-tests#beforediscovery). + +## Execution order + +In Pester v4 the execution of your test code was mostly top-down, with the exception of all the `Before*` and `After*` blocks. Those blocks were picked up by Pester using AST and "moved" to the place where they needed to run. + +For example placing an `AfterAll` at the top of a `Describe` would not run it at the top, but instead it would correctly run it as the last thing in that `Describe` wrapped in a `try finally`. + +Pester v5 takes this to the next level and manipulates the execution of your test file in a more complex way. This has good reason, but makes understanding how your code executes quite complex, especially when you don't follow the two rules listed above. + + +### Discovery + +Take for example this test file. When executed it will discover two tests inside of this file, and run them: + +import GetEmoji from './_GetEmoji.mdx'; + + + +```powershell title="Get-Emoji.Tests.ps1" +BeforeAll { + . $PSCommandPath.Replace('.Tests.ps1','.ps1') +} + +Describe "Get-Emoji" { + It "Returns ()" -TestCases @( + @{ Name = "cactus"; Expected = '🌵'} + @{ Name = "giraffe"; Expected = '🦒'} + ) { + Get-Emoji -Name $name | Should -Be $expected + } +} + +Write-Host "Discovery done." +``` + +This is what happens step by step when you run `Get-Emoji.Tests.ps1`: + +- The script file `Get-Emoji.Tests.ps1` is invoked +- `BeforeAll` function runs. It saves the ScriptBlock provided to it, but does not execute it yet. +- `Describe` function runs. It **invokes** the ScriptBlock provided to it, to be able to collect information about the tests contained inside of that scriptblock. `Describe` and `Context` scriptblocks are the only scriptblocks that are invoked during `Discovery`. +- All parameters provided to `It` are evaluated by PowerShell: + - `-Name` is evaluated: + - if double quoted string is used (`""`) all variables and sub-expressions in the string are expanded + - if single quotes string is used (`''`) it is taken as it is + - `-TestCases` are evaluated: + - all `""` strings are expanded + - all commands are executed, if any are used +- `It` function runs. The ScriptBlock provided (the body of the test) is saved but not executed yet. Two tests are generated. One for each item in `-TestCases` array. +- `Write-Host` runs and prints "Discovery done." + +At this point we are done with `Discovery`. As you can see discovery is just a "trick". We run the whole script to the end, but don't invoke any ScriptBlock, except for the one associated with `Describe`. + +At the end of `Discovery` we have collected all the tests and setups that are contained in the file, and stored them in the internal data of Pester module. The internal representation looks something like this: + +``` +Container: Get-Emoji.Tests.ps1 + BeforeAll: `{ . $PSCommandPath.Replace('.Tests.ps1','.ps1') } + AfterAll: + Blocks: + Block: Get-Emoji + BeforeAll: + BeforeEach: + AfterEach: + AfterAll: + Tests: + Test: Returns () + Data: @{ Name = "cactus"; Expected = '🌵'} + ScriptBlock: { Get-Emoji -Name $name | Should -Be $expected } + + Test: Returns () + Data: @{ Name = "giraffe"; Expected = '🦒'} + ScriptBlock: { Get-Emoji -Name $name | Should -Be $expected } +``` + +Now we would go through all the objects, check filters and propagate them down and back up. This gives us the final overview of what needs to run. In this case there are no filters, so nothing changes and all tests will be invoked. + +At this point we are done with the Discovery phase. We invoked the script to the end, and evaluated all the `-TestCases` and `-Name` strings if they have variables in them and use double quotes. + +### Run + +In the run phase we take the internal tree of containers, blocks and tests and run them. We need to do quite a lot of work to reconstruct the correct scoping and to ensure that everything runs safely. At a high level this is what happens: + +- Run the `BeforeAll` ScriptBlock, this imports the tested function +- Create new scope to isolate the test from other tests + - Invoke the `It ScriptBlock`, this runs the first test + - Return to the previous scope +- Create new scope to isolate the test from other tests + - Invoke the `It ScriptBlock`, this runs the second test + - Return to the previous scope +- Return to the previous scope + +We are done. All tests in this container are executed. + + +## Common gotchas + +### `BeforeAll` and `-TestCases` + +`-TestCases` are evaluated during `Discovery`, but `BeforeAll` won't run until the `Run` phase. Using variables set in `BeforeAll` in `-TestCases` (or `-ForEach`) won't work. The variable from `BeforeAll` simply won't be defined until much after `-TestCases` and `-ForEach` are evaluated. + +### Generating test and blocks via `foreach` keyword + +A common pattern in Pester v4 is to use `foreach` to generated tests and blocks based on external data, for example like this: + +```powershell +BeforeAll { + # check all script files + $files = Get-ChildItem *.ps1 +} + +foreach ($file in $files) { + Describe "$file is correct" { + It "has empty line at end" { + # ... + } + + It "has UTF-8 encoding" { + # ... + } + } +} +``` + +In this case the `foreach` is evaluated during `Discovery` because we simply run the whole script file. But `BeforeAll` won't be invoked until `Run`, so the `$files` variable is not defined during `Discovery` and the tests are not generated. This can be solved by defining the code that is used to generate tests into `BeforeDiscovery` block. See [Data driven tests](data-driven-tests#beforediscovery). + + +### Variables are not available in test + +The example above has one more problem, if we move the setup to `BeforeDiscovery`, we will generate the tests correctly, and the `foreach` will define `$file` variable. But we won't be able to use the `$file` variable in the `It`. We need to attach it to the `It` using `-TestCases` with a single test case: + +```powershell +BeforeDiscovery { # <- this will run during Discovery + # check all script files + $files = Get-ChildItem *.ps1 +} + +foreach ($file in $files) { + Describe "$file is correct" { + It "has empty line at end" -TestCases @{ File = $file } { # <- we pass $file data to the test + # ... + } + + It "has UTF-8 encoding" { + # ... + } + } +} +``` + +Both of the problems above are avoidable by using `-ForEach`, see [Data driven tests](data-driven-tests). diff --git a/versioned_docs/version-v5/usage/file-placement-and-naming.mdx b/versioned_docs/version-v5/usage/file-placement-and-naming.mdx new file mode 100644 index 00000000..f705ec59 --- /dev/null +++ b/versioned_docs/version-v5/usage/file-placement-and-naming.mdx @@ -0,0 +1,34 @@ +--- +title: File placement and naming +description: Tips on how to name and structure your Pester test files and categorize your tests +--- + +## Common convention + +Pester considers all files named `.Tests.ps1` to be test files. This is the default naming convention that is used by almost all projects. + +Each file is called as the function it tests. This means that for a function `Get-Emoji` we would have `Get-Emoji.Tests.ps1` and `Get-Emoji.ps1`. + +Test files are placed in the same directory as the code that they test, or in a separate `tests` directory that follows the same directory structure as the main src directory. + +``` +Get-Emoji.ps1 +Get-Emoji.Tests.ps1 + +# or + +src/public/Get-Emoji.ps1 +tests/public/Get-Emoji.Tests.ps1 +``` + +## Custom conventions + +The convention above is the default that most projects use, but Pester is not prescriptive about how you should name or place your files. The default extension can be customized by setting the `Run.TestExtension` configuration option. The relative position of files can be then adjusted by changing the code you use to code files into tests. See [Importing tested functions](importing-tested-functions). + +However the convention above is the default and is recommended to be used, especially when you are starting with Pester. + +## Categorizing tests + +There can be many tests in one file, but in bigger projects you might want to distinguish, Unit, and Acceptance tests (or whatever are the categories of tests you have). This is typically approached by using tags. But another way is to split the tests in separate files and name them accordingly `Get-Emoji.Unit.Tests.ps1`, `Get-Emoji.Acceptance.Tests.ps1`. This keeps your Acceptance test and Unit test code separate, which might be a good idea as Acceptance tests are usually more complex, and require more dependencies. + +You can then use the `Run.TestExtension` configuration option to customize the file extension convention to run only `*.Unit.Tests.ps1`, only `*.Acceptance.Tests.ps1` or keep the default to run all `*.Tests.ps1`. Even more fine-grained control is possible by using the `-ExcludePath` parameter, or by using `Get-ChildItem` to filter all paths and then provide them to `-Path` parameter. diff --git a/versioned_docs/version-v5/usage/images/azuredevops-log.png b/versioned_docs/version-v5/usage/images/azuredevops-log.png new file mode 100644 index 00000000..3ce787eb Binary files /dev/null and b/versioned_docs/version-v5/usage/images/azuredevops-log.png differ diff --git a/versioned_docs/version-v5/usage/images/azuredevops-report.png b/versioned_docs/version-v5/usage/images/azuredevops-report.png new file mode 100644 index 00000000..f2bbd5f2 Binary files /dev/null and b/versioned_docs/version-v5/usage/images/azuredevops-report.png differ diff --git a/versioned_docs/version-v5/usage/images/github-log.png b/versioned_docs/version-v5/usage/images/github-log.png new file mode 100644 index 00000000..fc8599d9 Binary files /dev/null and b/versioned_docs/version-v5/usage/images/github-log.png differ diff --git a/versioned_docs/version-v5/usage/images/github-report.png b/versioned_docs/version-v5/usage/images/github-report.png new file mode 100644 index 00000000..b86d521a Binary files /dev/null and b/versioned_docs/version-v5/usage/images/github-report.png differ diff --git a/versioned_docs/version-v5/usage/images/minimal-output.gif b/versioned_docs/version-v5/usage/images/minimal-output.gif new file mode 100644 index 00000000..adcc50a0 Binary files /dev/null and b/versioned_docs/version-v5/usage/images/minimal-output.gif differ diff --git a/versioned_docs/version-v5/usage/images/output-detailed.png b/versioned_docs/version-v5/usage/images/output-detailed.png new file mode 100644 index 00000000..7f2aa53c Binary files /dev/null and b/versioned_docs/version-v5/usage/images/output-detailed.png differ diff --git a/versioned_docs/version-v5/usage/images/output-diagnostic.png b/versioned_docs/version-v5/usage/images/output-diagnostic.png new file mode 100644 index 00000000..33d01bd2 Binary files /dev/null and b/versioned_docs/version-v5/usage/images/output-diagnostic.png differ diff --git a/versioned_docs/version-v5/usage/images/output-normal.png b/versioned_docs/version-v5/usage/images/output-normal.png new file mode 100644 index 00000000..ce58573b Binary files /dev/null and b/versioned_docs/version-v5/usage/images/output-normal.png differ diff --git a/versioned_docs/version-v5/usage/images/single-test.gif b/versioned_docs/version-v5/usage/images/single-test.gif new file mode 100644 index 00000000..faeeea21 Binary files /dev/null and b/versioned_docs/version-v5/usage/images/single-test.gif differ diff --git a/versioned_docs/version-v5/usage/images/stacktrace-filtered.png b/versioned_docs/version-v5/usage/images/stacktrace-filtered.png new file mode 100644 index 00000000..ef291865 Binary files /dev/null and b/versioned_docs/version-v5/usage/images/stacktrace-filtered.png differ diff --git a/versioned_docs/version-v5/usage/images/stacktrace-firstline.png b/versioned_docs/version-v5/usage/images/stacktrace-firstline.png new file mode 100644 index 00000000..cf1fce4f Binary files /dev/null and b/versioned_docs/version-v5/usage/images/stacktrace-firstline.png differ diff --git a/versioned_docs/version-v5/usage/images/stacktrace-full.png b/versioned_docs/version-v5/usage/images/stacktrace-full.png new file mode 100644 index 00000000..2d73f67e Binary files /dev/null and b/versioned_docs/version-v5/usage/images/stacktrace-full.png differ diff --git a/versioned_docs/version-v5/usage/images/stacktrace-none.png b/versioned_docs/version-v5/usage/images/stacktrace-none.png new file mode 100644 index 00000000..45138992 Binary files /dev/null and b/versioned_docs/version-v5/usage/images/stacktrace-none.png differ diff --git a/versioned_docs/version-v5/usage/importing-tested-functions.mdx b/versioned_docs/version-v5/usage/importing-tested-functions.mdx new file mode 100644 index 00000000..412cb6a5 --- /dev/null +++ b/versioned_docs/version-v5/usage/importing-tested-functions.mdx @@ -0,0 +1,91 @@ +--- +title: Importing tested functions +description: Importing your PowerShell-code is essential to being able to test it. See how to import functions from your code to make them available for your tests +--- + +> Migrating from Pester v4? Jump to [Migrating from Pester v4](#migrating-from-pester-v4). + + +### Importing the tested functions + +Pester tests are placed in `.Tests.ps1` file, for example `Get-Emoji.Tests.ps1`. The code is placed in `Get-Emoji.ps1`. + +To make the tested code available to the test we need to import the code file. This is done by dot-sourcing the file into the current scope like this: + +```powershell title="Get-Emoji.Tests.ps1" +# at the top of the file +BeforeAll { + . $PSScriptRoot/Get-Emoji.ps1 +} +``` + +This code will locate the `Get-Emoji.ps1` file, which is placed in the same directory as `Get-Emoji.Tests.ps1` and import it into the test by dot-sourcing it. + +Alternatively `$PSCommandPath` can be used to get the name of the code file by convention: + +```powershell title="Get-Emoji.Tests.ps1" +BeforeAll { + # Get-Emoji.Tests.ps1 - .Tests.ps1 + .ps1 = Get-Emoji.ps1 + . $PSCommandPath.Replace('.Tests.ps1','.ps1') +} +``` + +This avoids spelling out the name of the referenced file every time. + +:::warning +The code above is using `string.Replace()` method which is case sensitive. Make sure you say `Tests` and that the test file is named `.Tests.ps1`. +::: + +:::warning +Pester v4 users might be inclined not to use the `BeforeAll` block or to use `$MyInvocation.MyCommand.Path` in `BeforeAll`. Neither will work. See [Migrating from Pester v4](#migrating-from-pester-v4). +::: + + +## Migrating from Pester v4 +### Put setup in BeforeAll + +In Pester v5 the setup code should be put into a `BeforeAll` block, and `$MyInvocation.MyCommand.Path` should *NOT* be used: + +```powershell +# BEFORE (Pester v4): + +$here = Split-Path -Parent $MyInvocation.MyCommand.Path +$sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path).Replace(".Tests.", ".") +. "$here\$sut" + +Describe "Get-Cactus" { + It "Returns 🌵" { + Get-Cactus | Should -Be '🌵' + } +} +``` + +```powershell +# AFTER (Pester v5): + +BeforeAll { + # DON'T use $MyInvocation.MyCommand.Path + . $PSCommandPath.Replace('.Tests.ps1','.ps1') +} + +Describe "Get-Cactus" { + It "Returns 🌵" { + Get-Cactus | Should -Be '🌵' + } +} +``` + +### Using `$MyInvocation.MyCommand.Path` in other code + +`$MyInvocation.MyCommand.Path` can be used in other parts of your code, just not in `BeforeAll`. If your module uses it, then it will continue to work even when used with Pester 5. The breaking change in Pester is because the `$here\$sut` snippet relies on the fact that it runs directly in the script, which is no longer true when placed in `BeforeAll`. This problem is not specific to `BeforeAll`, running `$MyInvocation.MyCommand.Path` in any function will make the Path property undefined: + +```powershell +"in script: -$($MyInvocation.MyCommand.Path)-" + +function f () { "in function: -$($MyInvocation.MyCommand.Path)-" } +f + +# output: +in script: -C:\temp\script.ps1- +in function: -- +``` diff --git a/versioned_docs/version-v5/usage/mocking.mdx b/versioned_docs/version-v5/usage/mocking.mdx new file mode 100644 index 00000000..f064b37c --- /dev/null +++ b/versioned_docs/version-v5/usage/mocking.mdx @@ -0,0 +1,275 @@ +--- +id: mocking +title: Mocking with Pester +sidebar_label: Mocking +description: Pester provides a set of Mocking functions making it easy to fake dependencies and also to verify behavior. Using these mocking functions can allow you to "shim" a data layer or mock other complex functions that already have their own tests +--- + +Pester provides a set of Mocking functions making it easy to fake dependencies and also to verify behavior. Using these mocking functions can allow you to "shim" a data layer or mock other complex functions that already have their own tests. + +## Description + +With the set of Mocking functions that Pester exposes, one can: + +* Mock the behavior of ANY powershell command. +* Verify that specific commands were (or were not) called. +* Verify the number of times a command was called with a set of specified parameters. + +## Mocking Functions + +### Mock + +Mocks the behavior of an existing command with an alternate implementation. + +### Should -Invoke + +Checks if a mocked command has been called a certain number of times and throws an exception if it has not. + +### Should -InvokeVerifiable + +Checks if any verifiable Mock has not been invoked. If so, this will throw an exception. + +## Example + +```powershell +BeforeAll{ + function Build ($version) { + Write-Host "a build was run for version: $version" + } + + function Get-Version{ + return 'Version' + } + + function Get-NextVersion { + return 'NextVersion' + } + + function BuildIfChanged { + $thisVersion = Get-Version + $nextVersion = Get-NextVersion + if ($thisVersion -ne $nextVersion) { Build $nextVersion } + return $nextVersion + } +} + +Describe "BuildIfChanged" { + Context "When there are Changes" { + BeforeEach{ + Mock Get-Version {return 1.1} + Mock Get-NextVersion {return 1.2} + Mock Build {} -Verifiable -ParameterFilter {$version -eq 1.2} + + $result = BuildIfChanged + } + + It "Builds the next version" { + Should -InvokeVerifiable + } + + It "returns the next version number" { + $result | Should -Be 1.2 + } + } + Context "When there are no Changes" { + BeforeEach{ + Mock Get-Version { return 1.1 } + Mock Get-NextVersion { return 1.1 } + Mock Build {} + + $result = BuildIfChanged + } + + It "Should not build the next version" { + Should -Invoke -CommandName Build -Times 0 -ParameterFilter {$version -eq 1.1} + } + } +} +``` + +--- +If you need to mock calls to commands which are made from inside a Script Module, additional code is required. For details, refer to [Unit Testing within Modules](./modules) + +--- + +### Mocking a function that is called by a method in a PowerShell class + +In PowerShell 6 and later functions called by classes can be mocked as above with no known problems. + +However previous versions of PowerShell, including **all** versions of Windows PowerShell up to 5.1 cache class definitions in such a way that they are never redefined, even if you remove the module and re-import, or modify the class. This breaks Pester's Mock command, as the scope where the mock must be injected cannot be found. + +Dave Wyatt has provided this workaround ([original source](https://github.com/pester/Pester/issues/797#issuecomment-314495326)): + +> Simply run your Pester tests in a fresh session every time; this is simple to do with Start-Job. I have this proxy function in my PowerShell profile to help with that: + +```powershell +# Updated example based on https://github.com/pester/Pester/issues/797#issuecomment-314495326 +function Invoke-PesterJob { + [CmdletBinding()] + param( + [Parameter(Position=0)] + [string[]] $Path = '.', + [string[]] $ExcludePath = @() + [string[]] $TagFilter, + [string[]] $ExcludeTagFilter, + [string[]] $FullNameFilter, + [switch] $EnableExit, + [switch] $PassThru + ) + + $params = $PSBoundParameters + + Start-Job -ScriptBlock { Set-Location $using:pwd; Invoke-Pester @using:params } | + Receive-Job -Wait -AutoRemoveJob +} +Set-Alias ipj Invoke-PesterJob +``` + +### Mocking a native application + +Mocking native commands can be done in a similar way as Powershell functions/cmdlets. The major difference is that native commands don't provide named parameters for us to use inside the mock scriptblock or in a ParameterFilter, so you'd have to rely on arguments made available using `$args`. + +```powershell +# For Windows-users: curl used in sample requires Windows 10 1803 / Windows Server 2019 or later +Describe 'Mocking native commands' { + It 'Mock bash' { + # Windows PowerShell has curl -> Invoke-WebRequest alias. Removing to make sample cross-platform + while (Test-Path Alias:curl) { Remove-Item Alias:curl } + + function GetHTTPHeader ($url) { + & curl --url $url ` + -I + } + + Mock curl { Write-Warning "$args" } + + GetHTTPHeader -url 'https://google.com' + + Should -Invoke -CommandName 'curl' -Exactly -Times 1 -ParameterFilter { $args[0] -eq '--url' -and $args[1] -eq 'https://google.com' } + + # By converting args to string (will concat using space by default) you can match a pattern if order might change. remember linebreaks + Should -Invoke -CommandName 'curl' -Exactly -Times 1 -ParameterFilter { "$args" -match '--url https://google.com -I' } + } +} +``` + +## $PesterBoundParameters + +Calling a mocked command will execute a proxy-function (hook) which evaluates and chooses the correct behavior/mock to invoke in that scenario. Because of this proxy `$PSBoundParameters` will be overwritten and are not available inside your mock's scriptblock. + +Starting in Pester 5.2.0, a new `$PesterBoundParameters` variable has been introduced as a replacement. Using this you can evaluate bound parameters and/or forward them to other functions inside your mock's code. + +```powershell +Describe 'PesterBoundParameters' { + It 'Demo' { + Mock -CommandName Write-Host -MockWith { + # Do something else + Write-Warning -Message "MOCKED - $Object" + + # Call real Write-Host with bound parameters + & (Get-Command -CommandType Cmdlet -Name Write-Host) @PesterBoundParameters + } + + Write-Host -Object "This should be red" -ForegroundColor Red + } +} +``` + +## Changes from Pester v4 + +### Mocks are scoped based on their placement + +Mocks are no longer effective in the whole `Describe` / `Context` in which they were placed. Instead they will default to the block in which they were placed. Both of these work: + +```powershell +Describe "d" { + BeforeAll { + function f () { "real" } + } + + It "i" { + Mock f { "mock" } + f | Should -Be "mock" + } + + It "j" { + f | Should -Be "real" + } +} + +Describe "d" { + BeforeAll { + function f () { "real" } + Mock f { "mock" } + } + + It "i" { + f | Should -Be "mock" + } + + It "j" { + f | Should -Be "mock" + } +} +``` + +### Counting mocks depends on placement + +Counting mocks depends on where the assertion is placed. In `It`, `BeforeEach` and `AfterEach` it defaults to `It` scope. In `Describe`, `Context`, `BeforeAll` and `AfterAll`, it default to `Describe` or `Context` based on the command that contains them. The default can still be overriden by specifying `-Scope` parameter. + +```powershell +Describe "d" { + + BeforeAll { + function f () { "real" } + Mock f { "mock" } + } + + It "i" { + f + Should -Invoke f -Exactly 1 + } + + It "j" { + f + Should -Invoke f -Exactly 1 + } + + It "k" { + f + Should -Invoke f -Exactly 3 -Scope Describe + } + + AfterEach { + Should -Invoke f -Exactly 1 + } + + AfterAll { + Should -Invoke f -Exactly 3 + } +} +``` + +### Default parameters for ParameterFilter + +Parameter filters no longer require you to use `param()`. + +```powershell +Describe "d" { + + BeforeAll { + function f ($a) { "real" } + Mock f { "mock" } -ParameterFilter { $a -eq 10 } + } + + It "i" { + f 10 + Should -Invoke f -Exactly 1 + } + + It "j" { + f 20 + Should -Invoke f -Exactly 0 + } +} +``` diff --git a/versioned_docs/version-v5/usage/modules.mdx b/versioned_docs/version-v5/usage/modules.mdx new file mode 100644 index 00000000..7547d91b --- /dev/null +++ b/versioned_docs/version-v5/usage/modules.mdx @@ -0,0 +1,293 @@ +--- +id: modules +title: Unit Testing within Modules +sidebar_label: Modules +description: PowerShell code in modules run in their own module state. This requires special attention when writing tests for internal functions or when mocking dependencies used by code in a module +--- + +## Introduction + +Let's say you have code like this inside a script module (.psm1 file): + +```powershell title="MyModule.psm1" +function BuildIfChanged { + $thisVersion = Get-Version + $nextVersion = Get-NextVersion + if ($thisVersion -ne $nextVersion) { Build $nextVersion } + return $nextVersion +} + +function Build ($version) { + Write-Host "a build was run for version: $version" +} + +# Actual definitions of Get-Version and Get-NextVersion are not shown here, +# since we'll just be mocking them anyway. However, the commands do need to +# exist in order to be mocked, so we'll stick dummy functions here + +function Get-Version { return 0 } +function Get-NextVersion { return 0 } + +Export-ModuleMember -Function BuildIfChanged +``` + +## Testing public functions +You wish to write a unit test for this module which mocks the calls to `Get-Version` and `Get-NextVersion` from the module's `BuildIfChanged` command. In older versions of Pester, this was not possible. As of version 3.0, there are two ways you can perform unit tests of PowerShell script modules. The first is to inject mocks into a module: + +For these example, we'll assume the module above is installed in a path defined in [`$env:PSModulePath`](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_psmodulepath). + +```powershell +BeforeAll { + Import-Module MyModule +} + +Describe "BuildIfChanged" { + Context "When there are Changes" { + BeforeAll { + Mock -ModuleName MyModule Get-Version { return 1.1 } + Mock -ModuleName MyModule Get-NextVersion { return 1.2 } + + # Just for giggles, we'll also mock Write-Host here, to demonstrate that you can + # mock calls to commands other than functions defined within the same module. + Mock -ModuleName MyModule Write-Host {} -Verifiable -ParameterFilter { + $Object -eq 'a build was run for version: 1.2' + } + + $result = BuildIfChanged + } + + It "Builds the next version and calls Write-Host" { + Should -InvokeVerifiable + } + + It "returns the next version number" { + $result | Should -Be 1.2 + } + } + + Context "When there are no Changes" { + BeforeAll { + Mock -ModuleName MyModule Get-Version { return 1.1 } + Mock -ModuleName MyModule Get-NextVersion { return 1.1 } + Mock -ModuleName MyModule Build { } + + $result = BuildIfChanged + } + + It "Should not build the next version" { + # -Scope Context is used below since BuildIfChanged is called in BeforeAll + # It's not required when the mock is called inside It + Should -Invoke Build -ModuleName MyModule -Times 0 -Scope Context -ParameterFilter { + $version -eq 1.1 + } + } + } +} +``` + +### -ModuleName + +Notice that in this example test script, all calls to [Mock](../commands/Mock) and [Should -Invoke](../commands/Should) have had the `-ModuleName MyModule` parameter added. This tells Pester to inject the mock into the module's scope, which causes any calls to those commands from inside the module to execute the mock instead. + +When you write your test script this way, you can mock commands that are called by the module's internal functions. However, your test script is still limited to accessing the public, exported members of the module. If you wanted to write a unit test that calls `Build` directly, for example, it wouldn't work using the above technique. That's where the second approach to script module testing comes into play. + +## Testing private functions + +With Pester's [InModuleScope](../commands/InModuleScope) command, you can cause entire sections of your test script to execute inside the targeted script module. This gives you access to non-exported members of the module. For example: + +```powershell +BeforeAll { + Import-Module MyModule +} + +Describe "Unit testing the module's internal Build function:" { + It 'Outputs the correct message' { + InModuleScope MyModule { + $testVersion = 5.0 + Mock Write-Host { } + + Build $testVersion + + Should -Invoke Write-Host -ParameterFilter { + $Object -eq "a build was run for version: $testVersion" + } + } + } +} +``` + +Notice that when using `InModuleScope`, you no longer need to specify a `-ModuleName` parameter when calling `Mock` or `Should -Invoke` for commands within that module. You are also able to directly call the `Build` function, which the module does not export. + +:::warning Avoid putting in InModuleScope around your Describe and It blocks. + +`InModuleScope` is a simple way to expose your internal module functions to be tested, but it prevents you from properly testing your published functions, does not ensure that your functions are actually published and slows down test discovery by loading the module. Aim to avoid it altogether by using `-ModuleName` on `Mock` when possible or at least limit it to inside the It block like the sample above. +::: + +:::tip Variables and functions created inside InModuleScope won't persist by default + +The scriptblock provided to `InModuleScope` is executed in a local scope inside the module session state. If you're creating variables, functions etc. intended to be reused in later outside of this scriptblock, use the `script:` scope-modifier to make them available to all future scopes inside the module. +::: + +## Working with different module types + +Pester supports most module types in PowerShell, but there are some limitations with `Mock` and `InModuleScope` features for some module types. + +### Types of Modules +PowerShell modules are a way of grouping related scripts and resources together to make it easier to use them. There are a number of different types of modules, each of which have slightly different characteristics: + +- Script modules +- Binary modules +- Manifest modules +- Dynamic modules *(will also return Script as ModuleType)* + +To determine the type of a module you can use the Get-Module cmdlet. + +```powershell +ModuleType Version Name +---------- ------- ---- +Script 0.0 __DynamicModule_11b8a091-bd9b-49... +Binary 1.0.0.0 CimCmdlets +Manifest 3.1.0.0 Microsoft.PowerShell.Management +Manifest 3.1.0.0 Microsoft.PowerShell.Utility +Script 5.3.3 Pester +Script 2.0.0 PSReadline +``` + +To inspect your modules you might need to use `-ListAvailable` or load the module first using `Import-Module` and then inspect it. + +:::tip +Read more about the different module types at Microsoft Docs, see [Understanding a Windows PowerShell Module](https://docs.microsoft.com/en-us/powershell/scripting/developer/module/understanding-a-windows-powershell-module). +::: + +### Usage and workarounds + +Pester can be used to both test and mock the behavior commands that are exported from all types of modules. For example the following tests will call the real `Invoke-PublicMethod` command and call a mocked implementation of it regardless of whether it is defined in a Script, Binary, Manifest or Dynamic module: + +```powershell +Describe "Invoke-PublicMethod" { + It "returns a value" { + $result = Invoke-PublicMethod + $result | Should Be 'Invoke-PublicMethod called!' + } + + It "mocking exported command" { + Mock Invoke-PublicMethod { 'mocked' } + $result = Invoke-PublicMethod + $result | Should Be 'mocked' + } +} +``` + +However injecting mocks into or executing code inside a **Binary** module is not possible due to how they are implemented in PowerShell. As a result, you may see an error message when trying to use `Mock -ModuleName` or `InModuleScope`: + +```powershell +Module 'MyBinaryModule' is not a Script or Manifest module. Detected modules of the following types: 'Binary' +``` + +The following sections describe Pester's support for the `Mock` and `InModuleScope` features for each type of module and workarounds if available. + +### Script Modules + +Pester fully supports Script modules, so both `Mock` and `InModuleScope` can be used without any workarounds. + +### Dynamic Modules + +The `Mock` and `InModuleScope` features can be used with Dynamic modules if the module is first imported using `Import-Module`. Example: + +```powershell +BeforeAll { + # create a dynamic module + $myDynamicModule = New-Module -Name MyDynamicModule { + function Invoke-PrivateFunction { 'I am the internal function' } + function Invoke-PublicFunction { Invoke-PrivateFunction } + Export-ModuleMember -Function Invoke-PublicFunction + } + + # remove previously imported (to enable rerunning the tests) + Get-Module MyDynamicModule -ErrorAction SilentlyContinue | Remove-Module + + # import the dynamic module + $myDynamicModule | Import-Module -Force +} + +# use InModuleScope and Mock for commands inside the dynamic module +Describe 'Executing test code inside a dynamic module' { + Context 'Using the Mock command' { + It 'Can mock functions inside the module when using Mock -ModuleName' { + Mock Invoke-PrivateFunction -ModuleName MyDynamicModule -MockWith { 'I am the mock function.' } + Invoke-PublicFunction | Should -Be 'I am the mock function.' + Should -Invoke Invoke-PrivateFunction -ModuleName MyDynamicModule + } + } + + It 'Can call module internal functions using InModuleScope' { + InModuleScope MyDynamicModule { + Invoke-PrivateFunction | Should -Be 'I am the internal function' + } + } + It 'Can mock functions inside the module without using Mock -ModuleName when inside InModuleScope' { + InModuleScope MyDynamicModule { + Mock Invoke-PrivateFunction -MockWith { 'I am the mock function.' } + Invoke-PrivateFunction | Should -Be 'I am the mock function.' + Should -Invoke Invoke-PrivateFunction + } + } +} +``` + +### Manifest Modules + +Pester 5.4 and later fully supports Manifest modules, so both `Mock` and `InModuleScope` can be used without any workarounds. For earlier versions, see workaround below. + +Be aware that only code in nested scripts (`*.ps1`) execute directly from the manifest module. Nested script modules (`*.psm1`) or binary modules (`*.dll`) are executed in their own module state. In the example below, mocking calls made inside `Get-HelloWorld` would require `-ModuleName MyNestedModule` because it's was defined in `MyNestedModule.psm1`. + +```powershell +Get-Command Get-HelloWorld + +CommandType Name Version Source +----------- ---- ------- ------ +Function Get-HelloWorld 0.0.1 MyManifestModule + +(Get-Module MyManifestModule).NestedModules + +ModuleType Version PreRelease Name ExportedCommands +---------- ------- ---------- ---- ---------------- +Script 0.0 MyNestedModule Get-HelloWorld + +Get-HelloWorld +Hello World from module: MyNestedModule +``` + +:::tip Workaround for older versions of Pester +Prior to Pester 5.4, only exported members from a manifest module could be tested with Pester and the `Mock` and `InModuleScope` features were unavailable. However, by creating a empty script module with `*.psm1` extension and adding it into the `RootModule` (or `ModuleToProcess`) attribute of the manifest `*.psd1` file, the module is converted to a Script module. + +For example, save the manifest below to create a PowerShell **Manifest** module. + +```powershell title="MyModule.psd1" +@{ + ModuleVersion = '1.0' + NestedModules = @( "Invoke-PrivateManifestMethod.ps1", "Invoke-PublicManifestMethod.ps1" ) + FunctionsToExport = @( "Invoke-PublicManifestMethod" ) +} +``` + +To convert it into a **Script** module, create a new blank file called `MyModule.psm1` and modify the manifest created above as follows: + +```powershell title="MyModule.psd1" +@{ + ModuleVersion = '1.0' + # highlight-next-line + RootModule = "MyModule.psm1" + NestedModules = @( "Invoke-PrivateManifestMethod.ps1", "Invoke-PublicManifestMethod.ps1" ) + FunctionsToExport = @( "Invoke-PublicManifestMethod" ) +} +``` + +PowerShell will then load the module as a Script module and Pester's `Mock` and `InModuleScope` features will work as expected. +::: + +### Binary Modules + +Exported commands from a Binary module can be tested and mocked using with `Mock` for calls made in script or other modules. + +Use of `InModuleScope` and injecting mocks inside module (using `-ModuleName MyBinaryModule`) are not possible and there are no workarounds. diff --git a/versioned_docs/version-v5/usage/output.mdx b/versioned_docs/version-v5/usage/output.mdx new file mode 100644 index 00000000..72b36bea --- /dev/null +++ b/versioned_docs/version-v5/usage/output.mdx @@ -0,0 +1,94 @@ +--- +title: Output +description: Pester uses customizable console output to show tests results, errors and summary. See how you can customize this output to fit your preference +--- + +Pester offers multiple options to customize the console output to your preference. These settings are available in the Output-section of PesterConfiguration. + +```powershell +$conf = New-PesterConfiguration +$conf.Output + +Verbosity : The verbosity of output, options are None, Normal, Detailed and Diagnostic. (Normal, default: Normal) +StackTraceVerbosity : The verbosity of stacktrace output, options are None, FirstLine, Filtered and Full. (Filtered, default: Filtered) +CIFormat : The CI format of error output in build logs, options are None, Auto, AzureDevops and GithubActions. (Auto, default: Auto) +RenderMode : The mode used to render console output, options are Auto, Ansi, ConsoleColor and Plaintext. (Auto, default: Auto) +``` + +This page focuses on the general options available for all users. See [VSCode](./vscode) for settings and features specific to using Pester with VSCode. + +### Verbosity + +This option controls the general level of console output. Pester v5 supports the following levels: + +- **None**: No console output is shown. Typically used in combination with `Run.PassThru / -PassThru` to do custom post-processing of the results. +- **Normal (default)**: Focus on successful containers and failed tests/blocks. Shows basic discovery information and the summary of all tests.
+![Normal verbosity](./images/output-normal.png) +- **Detailed**: Similar to Normal, but this level shows all blocks and tests, including successful.
+![Detailed verbosity](./images/output-detailed.png) +- **Diagnostic**: Very verbose, but useful when troubleshooting tests. This level behaves like Detailed, but also enables debug-messages. It enforces common debug message categories as a minimum, but additional levels can be enabled by appending to the list in `Debug.WriteDebugMessagesFrom`.
+![Diagnostic verbosity](./images/output-diagnostic.png) + +### StackTraceVerbosity + +**New in Pester 5.3!** +When an error is shown due to a failed setup or test, a stacktrace is included to help you identify where the problem occured. Users might not care much about this while developers need it to identify and fix any issues. +This option lets you control how much of the stacktrace that will be printed using one of the following levels: + +- **None**: No stacktrace is shown, only the error message.
+![No stacktrace](./images/stacktrace-none.png) +- **FirstLine**: Only show the first line of the stacktrace. This is typically the line in your failing tests.
+![FirstLine stacktrace](./images/stacktrace-firstline.png) +- **Filtered (default)**: Shows stacktrace related to your code. Filters out lines related to Pester-runtime.
+![Filtered stacktrace](./images/stacktrace-filtered.png) +- **Full**: Shows unfiltered stacktrace including calls made by Pester-runtime. Mostly used for troubleshooting. This is equal to the option `Debug.ShowFullErrors = $true` used prior to Pester v5.3.
+![Full stacktrace](./images/stacktrace-full.png) + +:::tip Error details are always available in the result-object +The result-object returned from `Run.PassThru / -PassThru` includes a `ErrorRecord`-property in all blocks/tests with full stacktrace and more, even if you've limited the console output using the options above. +::: + +### CIFormat + +**New in Pester 5.3!** +Pester supports CI-specific output syntaxes to highlight, log and navigate to errors in your tests for a few popular CI systems. This options lets your control how this behavior should work. The following levels are currently supported: + +- **None**: Disable all CI-specific syntax. Error messages are presented in the format you're familiar with. +- **Auto (default)**: Automatically enables CI-specific format when Pester detects that it runs in a supported CI system. Will fallback to same output as None. +- **AzureDevops**: Enables Azure Devops-specific format to log errors and display the error messages in red. +- **GithubActions**: Enables Github Actions-specific format to log errors and display the error message in red. Error message and stacktrace are grouped. + +#### Azure Devops +In Azure Devops, the following features are enabled: +- Errors are logged and shown in the run summary. Clicking on a error will send you to the related lines in the build log.
+![Azure Devops summary view](./images/azuredevops-report.png) +- Error messages are highlighted with a prefix and colorized.
+![Azure Devops log](./images/azuredevops-log.png) + +Auto-detection works by checking if `TF_BUILD` environment variable is equal to `True`. + +#### Github Actions +In Github Actions, the following features are enabled: +- Errors will be highlighted in the run summary.
+![Github Actions summary view](./images/github-report.png) +- Error title will be highlighted in red. The remaining error message and stacktrace is placed in a expandable group to clean up the logs.
+![Github Actions log](./images/github-log.png) + +Auto-detection works by checking if `GITHUB_ACTIONS` environment variable is equal to `True`. + +### RenderMode + +**New in Pester 5.4!** +Pester supports multiple render modes for console output, including ANSI escape sequences which enables colors in CI-logs. The currently supported modes are: + +- **Auto (default)**: Automatically enables the recommended mode using the following rules: + - `Plaintext` when environment variable [`NO_COLOR`](https://no-color.org/) is set. + - `ANSI` when a supported PowerShell host is being used. + - `ConsoleColor` used as fallback. +- **ANSI**: Render using ANSI escape sequences. Colors are shown in ANSI-supported console hosts, redirected output, CI-logs etc. +- **ConsoleColor**: Uses default `Write-Host` behavior. Colors are shown in console but not in CI, redirected output etc. Same mode is used prior to Pester 5.4. +- **Plaintext**: Render output without colors. + +:::note Using ANSI with PowerShell 3 and 4 +ANSI support is auto-detected using the property `$host.UI.SupportsVirtualTerminal` which was introduced in PowerShell 5. If you are running PowerShell 3 or 4 in a known supported host or CI, you need to enable it explictly using `Output.RenderMode = 'Ansi'`. +::: diff --git a/versioned_docs/version-v5/usage/setup-and-teardown.mdx b/versioned_docs/version-v5/usage/setup-and-teardown.mdx new file mode 100644 index 00000000..3b9ff62d --- /dev/null +++ b/versioned_docs/version-v5/usage/setup-and-teardown.mdx @@ -0,0 +1,273 @@ +--- +title: Setup and teardown +description: Pester offers multiple ways to run code before, and after your tests to set them up, and clean up after them +--- + +### Setup and teardown + +Pester offers multiple ways to run code before, and after your tests to set them up, and clean up after them. The setup is represented by a `BeforeAll`, and `BeforeEach` blocks. + +The teardown is used to clean up after test or a block and is guaranteed to run even if the test fails. Teardown is represented by `AfterAll` and `AfterEach` blocks. + +### BeforeAll + +`BeforeAll` is used to share setup among all the tests in a `Describe / Context` including all child blocks and tests. `BeforeAll` runs during `Run` phase and runs only once in the current block. + + +The typical usage is to setup the whole test script, most commonly to import the tested function, by dot-sourcing the script file that contains it: + +```powershell +BeforeAll { + . $PSCommandPath.Replace('.Tests.ps1','.ps1') +} + +Describe "API validation" { + # ... +} +``` + +Another typical usage is to do an expensive operation once, and then validate the result in multiple tests: + +```powershell +Describe "API validation" { + BeforeAll { + # this calls REST API and takes roughly 1 second + $response = Get-Pokemon -Name Pikachu + } + + It "response has Name = 'Pikachu'" { + $response.Name | Should -Be 'Pikachu' + } + + It "response has Type = 'electric'" { + $response.Type | Should -Be 'electric' + } +} +``` + +### BeforeEach + +`BeforeEach` runs once before every test in the current or any child blocks. Typically this is used to create all the prerequisites for the current test, such as writing content to a file. For example this is how we ensure that each test gets fresh file: + +```powershell +Describe "File parsing" { + BeforeEach { + # randomized path, to get fresh file for each test + $path = "$([IO.Path]::GetTempPath())/$([Guid]::NewGuid())_form.xml" + Copy-Item -Source $template -Destination $path -Force | Out-Null + } + + It "Writes username" { + Write-XmlForm -Path $file -Field "username" -Value "nohwnd" + $content = Get-Content $file + # ... + } + + It "Writes name" { + Write-XmlForm -Path $file -Field "name" -Value "Jakub" + $content = Get-Content $file + # ... + } +} +``` + + +### AfterEach + +`AfterEach` runs once after every test in the current or any child blocks. Typically this is used to clean up resources created by the test, or its setups. `AfterEach` runs in a finally block, and is guaranteed to run even if the test (or setup) fails. For example this is how we ensure that each test removes its test file: + +```powershell +Describe "File parsing" { + BeforeEach { + # randomized path, to get fresh file for each test + $path = "$([IO.Path]::GetTempPath())/$([Guid]::NewGuid())_form.xml" + Copy-Item -Source $template -Destination $path -Force | Out-Null + } + + It "Writes username" { + Write-XmlForm -Path $file -Field "username" -Value "nohwnd" + $content = Get-Content $file + # ... + } + + It "Writes name" { + Write-XmlForm -Path $file -Field "name" -Value "Jakub" + $content = Get-Content $file + # ... + } + + AfterEach { + if (Test-Path $file) { + Remove-Item $file -Force + } + } +} +``` + +`AfterEach` placement within the current block does not affect when it is run, you can place it on the top or on the bottom of the block, and it will still run last. + +The teardown in `AfterEach` should be prepared to run at any place of `BeforeEach` or `It`. For example when the `$file` does not exist yet, because we got `AccessDenied` when trying to write it. + +### AfterAll + +`AfterAll` runs once after every `Describe` or `Context` block. It is used to clean up common resources. It works the same as `AfterEach`, except that it just runs once. + +### Multiple setups and teardowns + +When multiple `BeforeAll` are defined, they run in the order in which they were defined. `AfterAll` run in the opposite order. + +When multiple `BeforeEach` are defined, they run in the order in which they were defined, and they run right before the test they setup. `AfterEach` run right after the test is finished, in the opposite order. + +There can be only one setup or teardown of each kind in a block. + +```powershell +BeforeAll { + Write-Host "-> Top-level BeforeAll" +} + +Describe "d" { + BeforeAll { + Write-Host "-> Describe BeforeAll" + } + + BeforeEach { + Write-Host "-> Describe BeforeEach" + } + + Context "Whitespace" { + BeforeAll { + Write-Host "-> Context BeforeAll" + } + + BeforeEach { + Write-Host "-> Context BeforeEach" + } + + It "i" { + # ... + } + + AfterEach { + Write-Host "-> Context AfterEach" + } + + AfterAll { + Write-Host "-> Context AfterAll" + } + } + + AfterEach { + Write-Host "-> Describe AfterEach" + } + + AfterAll { + Write-Host "-> Describe AfterAll" + } +} + +AfterAll { + Write-Host "-> Top-level AfterAll" +} +``` +``` +Running tests from 'xxx' +-> Top-level BeforeAll +-> Describe BeforeAll +-> Context BeforeAll +Describing d + Context Whitespace +-> Describe BeforeEach +-> Context BeforeEach +-> Context AfterEach +-> Describe AfterEach + [+] i 89ms (86ms|4ms) +-> Context AfterAll +-> Describe AfterAll +-> Top-level AfterAll +Tests completed in 543ms +Tests Passed: 1, Failed: 0, Skipped: 0 NotRun: 0 +``` + + +### Skipping setups and teardowns + +Setups and teardowns are skipped when the current tree won't result in any test being run. In the example below, running Pester with the `-ExcludeTag Acceptance` filter will exclude all tests in the Describe-block. As a result the associated setup and teardown blocks will also be skipped. + +```powershell +BeforeAll { + Start-Sleep -Seconds 3 +} + +Describe "describe 1" { + BeforeAll { + Start-Sleep -Seconds 3 + } + + It "acceptance test 1" -Tag "Acceptance" { + 1 | Should -Be 1 + } + + AfterAll { + Start-Sleep -Seconds 3 + } +} +``` + +``` +Starting test discovery in 1 files. +Found 1 tests. 64ms +Test discovery finished. 158ms +Tests completed in 139ms +Tests Passed: 0, Failed: 0, Skipped: 0, Total: 1, NotRun: 1 +``` + +### Scoping + +All variables defined in `BeforeAll` are available to all child blocks and tests. But because all child blocks and tests run in their own scopes, the variables are not writeable to them. This is needed to isolate tests from each other. + +```powershell +Describe "d" { + BeforeAll { + $a = "BeforeAll" + } + It "Write a" { + $a = "Test" + } + + It "Check a" { + $a | Should -Be "BeforeAll" + } + + AfterAll { + Write-Host "-> AfterAll" + } +} +``` +``` +Describing d + [+] Write a 7ms (1ms|6ms) + [+] Check a 4ms (3ms|1ms) +-> AfterAll +Tests completed in 347ms +``` + +`BeforeEach`, `It` and `AfterEach` run in the same scope. All variables in them are shared. This way you can move code between `BeforeEach` and `It` without changes. And you can also base your `AfterEach` on variables that were defined in `It`, for example to delete a file you created in it. + +```powershell +Describe "d" { + It "Write a" { + $a = "Test" + } + + AfterEach { + Write-Host "-> $a" + } +} +``` + +``` +Describing d +-> Test + [+] Write a 7ms (3ms|4ms) +Tests completed in 227ms +``` diff --git a/versioned_docs/version-v5/usage/skip.mdx b/versioned_docs/version-v5/usage/skip.mdx new file mode 100644 index 00000000..4be6a770 --- /dev/null +++ b/versioned_docs/version-v5/usage/skip.mdx @@ -0,0 +1,128 @@ +--- +title: Skip +description: Skipping tests can be useful in many scenarios or when certain conditions are not met like OS-compatibility. Read about how to control this in Pester tests +--- + +### Skip on everything + +`-Skip` is now available on Describe and Context. This allows you to skip all the tests in that block and every child block. + +```powershell +Describe "describe1" { + Context "with one skipped test" { + It "test 1" -Skip { + 1 | Should -Be 2 + } + + It "test 2" { + 1 | Should -Be 1 + } + } + + Describe "that is skipped" -Skip { + It "test 3" { + 1 | Should -Be 2 + } + } + + Context "that is skipped and has skipped test" -Skip { + It "test 3" -Skip { + 1 | Should -Be 2 + } + + It "test 3" { + 1 | Should -Be 2 + } + } +} +``` + +``` +Starting test discovery in 1 files. +Found 5 tests. 117ms +Test discovery finished. 418ms +Describing describe1 + Context with one skipped test + [!] test 1, is skipped 18ms (0ms|18ms) + [+] test 2 52ms (29ms|22ms) + Describing that is skipped + [!] test 3, is skipped 12ms (0ms|12ms) + Context that is skipped and has skipped test + [!] test 3, is skipped 10ms (0ms|10ms) + [!] test 3, is skipped 10ms (0ms|10ms) +Tests completed in 1.03s +Tests Passed: 1, Failed: 0, Skipped: 4, Total: 5, NotRun: 0 +``` + +:::warning +Pending is translated to skipped, Inconclusive does not exist anymore. +::: + +### Conditional skip + +Evaluation of the skip-parameter is done as part of the Discovery-phase. This means you can also dynamically skip tests based on values available in that phase. Either as logic done in BeforeDiscovery or based on values passed into a parametrized test. + +```powershell +$sb = { + param($SkipFirst) + + Describe 'My Describe Block' { + BeforeDiscovery { + $skipSecond = 1 + } + + It 'First Test' -Skip:$SkipFirst { + 1 | Should -Be 1 + } + + It 'Second Test' -Skip:($skipSecond -eq 1) { + 1 | Should -Be 1 + } + + It 'Third Test' { + 1 | Should -Be 1 + } + } +} + +$container = New-PesterContainer -ScriptBlock $sb -Data @{ SkipFirst = $true } +$configuration = New-PesterConfiguration +$configuration.Run.Container = $container +$configuration.Output.Verbosity = 'Detailed' + +Invoke-Pester -Configuration $configuration +``` + +``` +Starting discovery in 1 files. +Discovering in + param($SkipFirst) + + Describe 'My Describe Block' { + BeforeDiscovery { + $skipSecond = 1 + } + + It 'First Test' -Skip:$SkipFirst { + 1 | Should -Be 1 + } + + It 'Second Test' -Skip:($skipSecond -eq 1) { + 1 | Should -Be 1 + } + + It 'Third Test' { + 1 | Should -Be 1 + } + } +. +Found 3 tests. 37ms +Discovery finished in 97ms. +Running tests. +Describing My Describe Block + [!] First Test 3ms (0ms|3ms) + [!] Second Test 2ms (0ms|2ms) + [+] Third Test 18ms (16ms|3ms) +Tests completed in 206ms +Tests Passed: 1, Failed: 0, Skipped: 2 NotRun: 0 +``` diff --git a/versioned_docs/version-v5/usage/tags.mdx b/versioned_docs/version-v5/usage/tags.mdx new file mode 100644 index 00000000..153684db --- /dev/null +++ b/versioned_docs/version-v5/usage/tags.mdx @@ -0,0 +1,90 @@ +--- +title: Tags +description: Use tags on tests and blocks to categorize code and easily choose which tests to run with simple parameters +--- + +The tag parameter is now available on `Describe`, `Context` and `It` and it is possible to filter tags on any level. You can then use `-TagFilter` and `-ExcludeTagFilter` to run just the tests that you want. + +Here you can see an example of a test suite that has acceptance tests and unit tests. Some of the tests are slow, some are flaky, and some only work on Linux. Pester makes running all reliable Windows-compatible acceptance tests as simple as: + + +```powershell +Invoke-Pester $path -TagFilter "Acceptance" -ExcludeTagFilter "Flaky", "Slow", "LinuxOnly" +``` + +```powershell +Describe "Get-Beer" { + + Context "acceptance tests" -Tag "Acceptance" { + + It "acceptance test 1" -Tag "Slow", "Flaky" { + 1 | Should -Be 1 + } + + It "acceptance test 2" { + 1 | Should -Be 1 + } + + It "acceptance test 3" -Tag "WindowsOnly" { + 1 | Should -Be 1 + } + + It "acceptance test 4" -Tag "Slow" { + 1 | Should -Be 1 + } + + It "acceptance test 5" -Tag "LinuxOnly" { + 1 | Should -Be 1 + } + } + + Context "unit tests" { + + It "unit test 1" { + 1 | Should -Be 1 + } + + It "unit test 2" -Tag "LinuxOnly" { + 1 | Should -Be 1 + } + + } +} +``` + +``` +Starting test discovery in 1 files. +Discovering tests in ...\real-life-tagging-scenarios.tests.ps1. +Found 7 tests. 482ms +Test discovery finished. 800ms + +Running tests from '...\real-life-tagging-scenarios.tests.ps1' +Describing Get-Beer + Context acceptance tests + [+] acceptance test 2 50ms (29ms|20ms) + [+] acceptance test 3 42ms (19ms|23ms) +Tests completed in 1.09s +Tests Passed: 2, Failed: 0, Skipped: 0, Total: 7, NotRun: 5 +``` + +#### Tags use wildcards + +The tags are now also compared as `-like` wildcards, so you don't have to spell out the whole tag if you can't remember it. This is especially useful when you are running tests locally: + +```powershell +Invoke-Pester $path -ExcludeTagFilter "Accept*", "*nuxonly" | Out-Null +``` +``` +Starting test discovery in 1 files. +Discovering tests in ...\real-life-tagging-scenarios.tests.ps1. +Found 7 tests. 59ms +Test discovery finished. 97ms + + +Running tests from '...\real-life-tagging-scenarios.tests.ps1' +Describing Get-Beer + Context Unit tests + [+] unit test 1 15ms (7ms|8ms) +Tests completed in 269ms +Tests Passed: 1, Failed: 0, Skipped: 0, Total: 7, NotRun: 6 +``` diff --git a/versioned_docs/version-v5/usage/test-file-structure.mdx b/versioned_docs/version-v5/usage/test-file-structure.mdx new file mode 100644 index 00000000..6eb42328 --- /dev/null +++ b/versioned_docs/version-v5/usage/test-file-structure.mdx @@ -0,0 +1,213 @@ +--- +title: Test file structure +description: Pester uses special keywords and blocks to structure your tests like Describe, Context, It, BeforeAll/-Each etc. See this to learn how they relate and fit together +--- + +Pester test files follow a similar structure. Usually there is some setup to get the tested function imported and a top-level `Describe` block to hold all the tests and child blocks. Inside that `Describe` we will find the tests themselves represented by `It` blocks. Those blocks are often grouped into their own `Describe` or `Context` based on the area of code they are testing. Those groups, can each have their own setups and teardowns represented by `BeforeAll`, `BeforeEach`, `AfterEach` and `AfterAll` blocks. + +## Simple test file + +This test file is a simple as it can be. We have a `BeforeAll` setup placed at the top of the file to import the tested function from its own file. Followed by a top-level `Describe` block called "Get-Emoji" because that is the function we are testing. Inside of that `Describe` block we have a single test represented by an `It` block. This block will run and will either pass or fail to represent the result of the test. + +import GetEmoji from './_GetEmoji.mdx'; + + + +```powershell title="Get-Emoji.Tests.ps1" +BeforeAll { + . $PSCommandPath.Replace('.Tests.ps1','.ps1') +} + +Describe "Get-Emoji" { + It "Returns 🌵 (cactus)" { + Get-Emoji -Name cactus | Should -Be '🌵' + } +} +``` + +:::warning +Put all your code into `It`, `BeforeAll`, `BeforeEach`, `AfterAll` or `AfterEach`. Put no code directly into `Describe`, `Context` or on the top of your file, without wrapping it in one of these blocks. + +Any code outside one of these blocks will run during Discovery, and the results won't be available during Run which will lead to confusing results. + +See [Discovery and Run](discovery-and-run). +::: + +## More complex file + +In this file we are using more features of Pester and organize our tests into more groups based on what we are testing. Each group is represented by a `Describe` or `Context` block. Within those groups we are specifying distinct setups represented by `BeforeAll` that will run at the start of the `Describe` (or `Context`) that contains them. Specifically we use the setup to run the tested function once per group of tests to ensure that the whole group uses the same filter. This avoids typos and copy paste errors. + +```powershell title="Get-Emoji.Tests.ps1" +BeforeAll { + . $PSCommandPath.Replace('.Tests.ps1','.ps1') +} + +Describe "Get-Emoji" { + Context "Lookup by whole name" { + It "Returns 🌵 (cactus)" { + Get-Emoji -Name cactus | Should -Be '🌵' + } + + It "Returns 🦒 (giraffe)" { + Get-Emoji -Name giraffe | Should -Be '🦒' + } + } + + Context "Lookup by wildcard" { + Context "by prefix" { + BeforeAll { + $emojis = Get-Emoji -Name pen* + } + + It "Returns ✏️ (pencil)" { + $emojis | Should -Contain "✏️" + } + + It "Returns 🐧 (penguin)" { + $emojis | Should -Contain "🐧" + } + + It "Returns 😔 (pensive)" { + $emojis | Should -Contain "😔" + } + } + + Context "by contains" { + BeforeAll { + $emojis = Get-Emoji -Name *smiling* + } + + It "Returns 🙂 (slightly smiling face)" { + $emojis | Should -Contain "🙂" + } + + It "Returns 😁 (beaming face with smiling eyes)" { + $emojis | Should -Contain "😁" + } + + It "Returns 😊 (smiling face with smiling eyes)" { + $emojis | Should -Contain "😊" + } + } + } +} +``` + +Each of the groups could also use an `AfterAll` block which would clean up after the tests. This is referred to as teardown. The `AfterAll` block is guaranteed to run even if tests fail. + +Additionally we could also have a `BeforeEach` or `AfterEach` block. Those blocks work just like the `*All` blocks, but the code would run before and after each `It`. See [Setup and teardown](setup-and-teardown) for more info. + + +:::tip Describe vs. Context +In almost all cases it does not matter if you use `Describe` or `Context`. They behave the same and are the same function internally. There are only two places where we distinguish them: + +- On `Mock` when `-Scope Describe` or `-Scope Context` is used. +- In output, when the block information is written to screen. +::: + +## More complex file with test cases + +The file below can take advantage of `TestCases` (which are also aliased `-ForEach`) to repeat the `It` block once for every item in the provided array. This makes the `It` code repeat less, and makes it very easy to add new examples. + +```powershell title="Get-Emoji.Tests.ps1" +BeforeAll { + . $PSCommandPath.Replace('.Tests.ps1','.ps1') +} + +Describe "Get-Emoji" { + Context "Lookup by whole name" { + It "Returns ()" -TestCases @( + @{ Name = "cactus"; Expected = '🌵'} + @{ Name = "giraffe"; Expected = '🦒'} + ) { + Get-Emoji -Name $name | Should -Be $expected + } + } + + Context "Lookup by wildcard" { + Context "by prefix" { + BeforeAll { + $emojis = Get-Emoji -Name pen* + } + + It "Returns ()" -TestCases @( + @{ Name = "pencil"; Expected = '✏️'} + @{ Name = "penguin"; Expected = '🐧'} + @{ Name = "pensive"; Expected = '😔'} + ) { + $emojis | Should -Contain $expected + } + } + + Context "by contains" { + BeforeAll { + $emojis = Get-Emoji -Name *smiling* + } + + It "Returns ()" -TestCases @( + @{ Name = "slightly smiling face"; Expected = '🙂'} + @{ Name = "beaming face with smiling eyes"; Expected = '😁'} + @{ Name = "smiling face with smiling eyes"; Expected = '😊'} + ) { + $emojis | Should -Contain $expected + } + } + } +} +``` + +See [Data driven tests](data-driven-tests). + +## Even more complex file + +With the example above we are still far away from a really complex test file. And that is good. The simpler you are able to keep your tests the better. The more static your tests are, the easier it is to feel confident that everything works. + +You for example might notice that "by prefix" and "by contains" are very similar, and you would be able to generate them by re-using the same `Context` by just providing a different value to `-Name`. While this is technically possible using the techniques below, I would not do it. The level of complexity shown in "More complex file with test cases" is about right for 90% of tests I write. + +Take the examples below as a list of things you might need when you can't avoid them. Not as a list of things that you need to use in all of your tests to get "Advanced Pester user" achievement unlocked. Less is more. + +### Test script parameters + +Passing parameters using the PowerShell `param()` block to provide external data to the `.Tests.ps1` file: + +```powershell +param ( + $File +) + +Describe "File is not empty" { + # ... +} +``` +See [Data driven tests](data-driven-tests#providing-external-data-to-tests). + + +### Expanding data to generate `Describe` and `Context` blocks + +Much like on `It`, You can use `-ForEach` on `Describe` and `Context` to repeat it for every item in the provided array: + +```powershell +BeforeDiscovery { + $files = @( + "Get-Emoji.ps1", + "Get-Planet.ps1" + ) +} + +Describe "function <_> has help" -ForEach $files { + # .... +} +``` + +This can be paired with the test script parameters to generate tests based on external data. + +See [Data driven tests](data-driven-tests). + + +### `BeforeDiscovery` + +In Pester5 the mantra is to put all code in Pester controlled blocks. No code should be directly in the script, or directly in `Describe` or `Context` block without wrapping it in some other block. + +There is a special block called `BeforeDiscovery` that shows intent when you need to put code directly in the script, or directly in `Describe` or `Context` block. This is useful when Data driven tests. + +See [Data driven tests](data-driven-tests#beforediscovery). diff --git a/versioned_docs/version-v5/usage/test-results.mdx b/versioned_docs/version-v5/usage/test-results.mdx new file mode 100644 index 00000000..4e6a1f3f --- /dev/null +++ b/versioned_docs/version-v5/usage/test-results.mdx @@ -0,0 +1,108 @@ +--- +id: test-results +title: Showing Test Results in CI +sidebar_label: Test Results +description: Pester can output tests results to NUnit and JUnit XML reports that can be consumed by test reporting tools and CI-solutions +--- + +Pester can output test results to a XML file using the NUnit 2.5 or JUnit 4 schema. + +## [TeamCity](https://www.jetbrains.com/teamcity/) + +TeamCity includes (since v4.5) a bundled XML Test Reporting plugin that can interpret the Pester Test Results file and include the test results in TeamCity's build dashboard. Configuring Pester and TeamCity to "light up" the Pester results is easy. + +### Pester Settings + +#### Using ./bin/pester.bat + +If you are using the Pester .bat file to run your tests, test results are automatically output to Test.Xml in the root of the TeamCity agent working Directory. + +### Using Invoke-Pester + +If you are not using the Pester .bat file and are instead calling Invoke-Pester directly from a build script, Make sure to specify a path using the `-OutputFile` and type include the "-OutputFormat" parameters. The path is relative to the TeamCity agent working directory. + +```powershell +Invoke-Pester -OutputFile Test.xml -OutputFormat NUnitXml +``` + +#### Advanced Interface Configuration +In Pester v5 a configuration object ([`PesterConfiguration`](https://pester.dev/docs/usage/configuration#advanced-interface)) was introduced. In addition to specifying an `OutputFormat` and `OutputPath` you will need to `Enable` test results for a file to be produced. + +```powershell +$PesterConfig = New-PesterConfiguration +$PesterConfig.TestResult.OutputFormat = "NUnitXml" +$PesterConfig.TestResult.OutputPath = "Test.xml" +$PesterConfig.TestResult.Enabled = $True +Invoke-Pester -Configuration $PesterConfig +``` + +### TeamCity Settings + +1. In your TeamCity build configuration settings, go to the "Build Step" page. +1. Add the "XML Report Processing" Build Feature. +1. The Report Type should be set to NUnit. You can select version 2.5.0. +1. In the Monitoring Rules text box, enter the xml file path given to Pester's `-OutputXml` parameter. If you use the Pester.bat file, simply enter Test.xml. + +#### TeamCity Troubleshooting + +In some deployments of TeamCity it may be necessary to specify the Powershell version to use in the Invoke-Pester build-step -- specifying "5.1" has been observed to work. + +If Pester does not seem to be available from your PowerShell build-step, here is an example on how to install it on-the-fly: https://david-obrien.net/2016/01/continuous-integration-with-teamcity-powershell-and-git/ + +### Code Coverage + +Code coverage metrics are not included in the NUnit xml report so it is necessary to pass them to TeamCity separately using a PassThru variable and the [Build Interaction feature](https://confluence.jetbrains.com/display/TCD8/Build+Script+Interaction+with+TeamCity#BuildScriptInteractionwithTeamCity-ReportingBuildStatistics). + +```powershell +$testResults = Invoke-Pester -OutputFile Test.xml -OutputFormat NUnitXml -CodeCoverage (Get-ChildItem -Path $PSScriptRoot\*.ps1 -Exclude *.Tests.* ).FullName -PassThru +Write-Output "##teamcity[buildStatisticValue key='CodeCoverageAbsLTotal' value='$($testResults.CodeCoverage.NumberOfCommandsAnalyzed)']" +Write-Output "##teamcity[buildStatisticValue key='CodeCoverageAbsLCovered' value='$($testResults.CodeCoverage.NumberOfCommandsExecuted)']" +``` + +## [AppVeyor](https://appveyor.com) + +The concept is the same: you serialize test results as `NUnitXml` and then upload them to the CI test reporting system. + +Your [`appveyor.yml`](https://www.appveyor.com/docs/appveyor-yml) can contain section like this + +```yaml +test_script: + - ps: | + $testResultsFile = ".\TestsResults.xml" + $res = Invoke-Pester -OutputFormat NUnitXml -OutputFile $testResultsFile -PassThru + (New-Object 'System.Net.WebClient').UploadFile("https://ci.appveyor.com/api/testresults/nunit/$($env:APPVEYOR_JOB_ID)", (Resolve-Path $testResultsFile)) + if ($res.FailedCount -gt 0) { + throw "$($res.FailedCount) tests failed." + } +``` + +:::note +`if` check with `throw` is used to fail the build, if any tests are failing. +::: + +:::note +If tests write anything to the pipeline, then `$res` object will contain it as well. Be careful! +::: + +**That's it! May all your tests be green!** + +## [Azure DevOps](https://azure.microsoft.com/en-us/solutions/devops/) + +With Azure DevOps the concept is very similar again, you run pester then publish the results back to Azure DevOps. This can be done through a YAML configuration or through tasks run on the agent in the build pipeline. + +An example of a PowerShell script to run against a single pester test file. + +```powershell +# This updates pester not always necessary but worth noting +Install-Module -Name Pester -Force -SkipPublisherCheck + +Import-Module Pester + +Invoke-Pester -Script $(System.DefaultWorkingDirectory)\MyFirstModule.test.ps1 -OutputFile $(System.DefaultWorkingDirectory)\Test-Pester.XML -OutputFormat NUnitXML +``` + +Then add a Publish Test Results task, it is important to change the Test Result format to NUnit to allow Azure DevOps to ingest the output file. + +:::note +Using the Azure PowerShell task doesn't require you to enable the control option of "Continue on error" before the publish test results. If you use one of the Pester Marketplace tools your mileage may vary. +::: diff --git a/versioned_docs/version-v5/usage/testdrive.mdx b/versioned_docs/version-v5/usage/testdrive.mdx new file mode 100644 index 00000000..02484b17 --- /dev/null +++ b/versioned_docs/version-v5/usage/testdrive.mdx @@ -0,0 +1,81 @@ +--- +id: testdrive +title: Isolating File Operations using the TestDrive +sidebar_label: TestDrive +description: TestDrive is a PowerShell PSDrive where you can create temporary files used in your tests that are automatically cleaned up after your tests are finished +--- + +TestDrive is a PowerShell PSDrive for file activity limited to the scope of a block ([Describe](../commands/Describe) or [Context](../commands/Context)). + +A test may need to work with file operations and validate certain types of file activities. It is usually desirable not to perform file activity tests that will produce side effects outside of an individual test. Pester creates a PSDrive inside the user's temporary drive that is accessible via a named PSDrive `TestDrive:`. Pester will remove this drive after the tests completes. You may use this drive to isolate the file operations of your test to a temporary store. + +## Scoping + +Basic scoping rules are implemented for the TestDrive: + +1. A clean TestDrive is created per container (test-file or scriptblock) on entry to the first top-level block (Describe or Context) in that container. +2. All files and folders created by your setups and tests are available during the lifetime of that block, including inner blocks. +3. When exiting a block, files and folders created during it's lifetime will be removed. Modifications to items created in parent blocks are not reversed, see caution below. +4. When the whole container is finished, the TestDrive and all files and folders inside it is deleted. + +:::warning Modifications to existing items are not reversed +Be aware that the TestDrive content is tracked by paths. When entering a block, all paths which already exists will be excluded during cleanup when exiting the block. +In practice this means that if you create a file in the Describe block and then change its content inside the Context block, the modifications or deletions are preserved even after you left the Context block. +::: + +:::note Using TestDrive in parallel runs +Internally the TestDrive creates a randomly named folder placed in $env:Temp and links it to the TestDrive PSDrive. +Making the folder names random enables you to run multiple instances of Pester in parallel, as long as they are running as separate processes. That means running in different PowerShell.exe sessions or running using PowerShell jobs. +::: + +## Example + +```powershell +BeforeAll { + function Add-Footer($path, $footer) { + Add-Content $path -Value $footer + } +} + +Describe "Add-Footer" { + BeforeAll { + $testPath = "TestDrive:\test.txt" + Set-Content $testPath -value "my test text." + Add-Footer $testPath "-Footer" + $result = Get-Content $testPath + } + + It "adds a footer" { + (-join $result) | Should -Be "my test text.-Footer" + } +} +``` + +## Compare with Literal Path + +Use the $TestDrive variable to compare regular paths with TestDrive paths. The following +two paths will refer to the same file on disk, but the first one will contain the full file +system path to the root of the TestDrive PSDrive, rather than a PowerShell path starting with +'TestDrive:\'. + +```powershell +#eg. C:\Users\nohwnd\AppData\Local\Temp\264f1c74-464f-4387-b908-79e5eecba982\somefile.txt +$pathOne = Join-Path $TestDrive 'somefile.txt' + +$pathTwo = 'TestDrive:\somefile.txt' +``` + +To get the full path, you can use this snippet: + +```powershell +function GetFullPath { + Param( + [string] $Path + ) + return $Path.Replace('TestDrive:', (Get-PSDrive TestDrive).Root) +} +``` + +## Working with .NET Objects + +When working directly with .NET objects, it's not possible to use the convenient `TestDrive:\` PSDrive. Instead you need to use the `$TestDrive` variable which holds the actual path in a format that .NET understands. For example instead of using `TestDrive:\somefile.txt` use `$TestDrive\somefile.txt` instead. diff --git a/versioned_docs/version-v5/usage/testregistry.mdx b/versioned_docs/version-v5/usage/testregistry.mdx new file mode 100644 index 00000000..111b4038 --- /dev/null +++ b/versioned_docs/version-v5/usage/testregistry.mdx @@ -0,0 +1,43 @@ +--- +id: testregistry +title: Isolating Windows Registry Operations using the TestRegistry +sidebar_label: TestRegistry +description: TestRegistry is a PowerShell PSDrive (Windows only) to help your store temporary values used in your tests in the Windows Registry that are automatically cleaned up after your tests are finished +--- + +TestRegistry is a Windows-only PowerShell PSDrive used to isolate registry based tests. + +Pester creates a temporary, randomly named (a guid), registry key in the current user's hive under `HKCU:\Software\Pester` which is accessible as `TestRegistry:`. + +## Scoping + +Basic scoping rules are implemented for the TestRegistry in a similar way to [TestDrive](./testdrive): +1. A clean TestRegistry is created per container (test-file or scriptblock) on entry to the first top-level block (Describe or Context) in that container. +2. All keys and values created by your setups and tests are available during the lifetime of that block, including inner blocks and tests. +3. All **keys** are removed when exiting the block they were created in. Keys created in parent blocks is kept until that block is finished. +4. When the whole container is finished, the temporary registry key is deleted and all the subkeys and values with it. + +:::note Cleanup is done at key-level +Be aware that cleanup in TestRegistry currently works on registry key-level. Values created inside an existing key from the parent block will persist until the key itself is deleted when the parent block is finished. +::: + +## Example + +```powershell +BeforeAll { + function Get-InstallPath($path, $key) { + Get-ItemProperty -Path $path -Name $key | Select-Object -ExpandProperty $key + } +} + +Describe "Get-InstallPath" { + BeforeAll { + New-Item -Path TestRegistry:\ -Name TestLocation + New-ItemProperty -Path "TestRegistry:\TestLocation" -Name "InstallPath" -Value "C:\Program Files\MyApplication" + } + + It 'reads the install path from the registry' { + Get-InstallPath -Path "TestRegistry:\TestLocation" -Key "InstallPath" | Should -Be "C:\Program Files\MyApplication" + } +} +``` diff --git a/versioned_docs/version-v5/usage/troubleshooting.mdx b/versioned_docs/version-v5/usage/troubleshooting.mdx new file mode 100644 index 00000000..6043b5bc --- /dev/null +++ b/versioned_docs/version-v5/usage/troubleshooting.mdx @@ -0,0 +1,49 @@ +--- +title: Troubleshooting +description: Introduction to useful logging for troubleshooting your tests or Pester itself +--- + +### Logging + +Enable logging by using the configuration object, or by using `-Output Diagnostic`. This is especially useful for diagnosing Mocks. + +All the major components log extensively. I am using logs as a debugging tool all the time so I make sure the logs are usable and not overly verbose. See if you can figure out why `acceptance test 1` is excluded from the run, and why `acceptance test 2` runs. + +``` +Filter: (Get-Beer) There is 'Flaky, Slow, LinuxOnly' exclude tag filter. +Filter: (Get-Beer) Block did not match the exclude tag filter, moving on to the next filter. +Filter: (Get-Beer) There is 'Acceptance' include tag filter. +Filter: (Get-Beer) Block has no tags, moving to next include filter. +Filter: (Get-Beer) Block did not match any of the include filters, but it will still be included in the run, it's children will determine if it will run. +Filter: (Get-Beer.acceptance tests) There is 'Flaky, Slow, LinuxOnly' exclude tag filter. +Filter: (Get-Beer.acceptance tests) Block did not match the exclude tag filter, moving on to the next filter. +Filter: (Get-Beer.acceptance tests) There is 'Acceptance' include tag filter. +Filter: (Get-Beer.acceptance tests) Block is included, because it's tag 'Acceptance' matches tag filter 'Acceptance'. +Filter: (Get-Beer.acceptance tests.acceptance test 1) There is 'Flaky, Slow, LinuxOnly' exclude tag filter. +Filter: (Get-Beer.acceptance tests.acceptance test 1) Test is excluded, because it's tag 'Flaky' matches exclude tag filter 'Flaky'. +Filter: (Get-Beer.acceptance tests.acceptance test 2) There is 'Flaky, Slow, LinuxOnly' exclude tag filter. +Filter: (Get-Beer.acceptance tests.acceptance test 2) Test did not match the exclude tag filter, moving on to the next filter. +Filter: (Get-Beer.acceptance tests.acceptance test 2) Test is included, because its parent is included. +Filter: (Get-Beer.acceptance tests.acceptance test 3) There is 'Flaky, Slow, LinuxOnly' exclude tag filter. +Filter: (Get-Beer.acceptance tests.acceptance test 3) Test did not match the exclude tag filter, moving on to the next filter. +Filter: (Get-Beer.acceptance tests.acceptance test 3) Test is included, because its parent is included. +Filter: (Get-Beer.acceptance tests.acceptance test 4) There is 'Flaky, Slow, LinuxOnly' exclude tag filter. +Filter: (Get-Beer.acceptance tests.acceptance test 4) Test is excluded, because it's tag 'Slow' matches exclude tag filter 'Slow'. +Filter: (Get-Beer.acceptance tests.acceptance test 5) There is 'Flaky, Slow, LinuxOnly' exclude tag filter. +Filter: (Get-Beer.acceptance tests.acceptance test 5) Test is excluded, because it's tag 'LinuxOnly' matches exclude tag filter 'LinuxOnly'. +Filter: (Get-Beer.Unit tests) There is 'Flaky, Slow, LinuxOnly' exclude tag filter. +Filter: (Get-Beer.Unit tests) Block did not match the exclude tag filter, moving on to the next filter. +Filter: (Get-Beer.Unit tests) There is 'Acceptance' include tag filter. +Filter: (Get-Beer.Unit tests) Block has no tags, moving to next include filter. +Filter: (Get-Beer.Unit tests) Block did not match any of the include filters, but it will still be included in the run, it's children will determine if it will run. +Filter: (Get-Beer.Unit tests.unit test 1) There is 'Flaky, Slow, LinuxOnly' exclude tag filter. +Filter: (Get-Beer.Unit tests.unit test 1) Test did not match the exclude tag filter, moving on to the next filter. +Filter: (Get-Beer.Unit tests.unit test 1) There is 'Acceptance' include tag filter. +Filter: (Get-Beer.Unit tests.unit test 1) Test has no tags, moving to next include filter. +Filter: (Get-Beer.Unit tests.unit test 1) Test did not match any of the include filters, it will not be included in the run. +Filter: (Get-Beer.Unit tests.unit test 2) There is 'Flaky, Slow, LinuxOnly' exclude tag filter. +Filter: (Get-Beer.Unit tests.unit test 2) Test is excluded, because it's tag 'LinuxOnly' matches exclude tag filter 'LinuxOnly'. +Filter: (Get-Beer.Unit tests) Block was marked as Should run based on filters, but none of its tests or tests in children blocks were marked as should run. So the block won't run. +``` + +Please be aware that the log is currently only written to the screen and not persisted in the result object. And that the logging comes with a performance penalty. You can enable logging by using the configuration object, or by using `-Output Diagnostic`. diff --git a/versioned_docs/version-v5/usage/vscode.mdx b/versioned_docs/version-v5/usage/vscode.mdx new file mode 100644 index 00000000..a03527c3 --- /dev/null +++ b/versioned_docs/version-v5/usage/vscode.mdx @@ -0,0 +1,22 @@ +--- +title: VSCode +description: See how Visual Studio Code and its extensions helps you run and debug your Pester tests directly inside the editor +--- + +### VSCode improvements + +#### Use legacy code lens + +With Pester 5 it is finally possible to run and debug just a single test in VSCode! + +![Shows a single test being run using the new Code Lens](images/single-test.gif) + +In the latest [PowerShell](https://marketplace.visualstudio.com/items?itemName=ms-vscode.PowerShell) extension for VSCode you can enable Use Legacy Code Lens option which will enable `Run tests` on all `Describe`, `Context` and `It` blocks. You can run a whole block, any child block, or any test individually. You can also run tests that are marked as skipped by running them individually. + +Actually there is a bug, and the option is called Enable Legacy Code Lens, and is enabled by default and should be disabled for Pester 5. 😁 Take advantage of this and go try it right now! + +#### Output verbosity + +You can specify verbosity in VSCode, to see normal or detailed output, or to take it from PesterPreference. This also works for Pester 4! + +![Shows a run with normal preference that shows only errors](images/minimal-output.gif) diff --git a/versioned_sidebars/version-v5-sidebars.json b/versioned_sidebars/version-v5-sidebars.json new file mode 100644 index 00000000..d47a449b --- /dev/null +++ b/versioned_sidebars/version-v5-sidebars.json @@ -0,0 +1,79 @@ +{ + "docs": { + "Introduction": [ + "quick-start", + "introduction/installation" + ], + "Usage": [ + "usage/file-placement-and-naming", + "usage/importing-tested-functions", + "usage/test-file-structure", + "usage/discovery-and-run", + "usage/data-driven-tests", + "usage/setup-and-teardown", + "usage/tags", + "usage/skip", + "usage/mocking", + "usage/modules", + "usage/testdrive", + "usage/testregistry", + "usage/test-results", + "usage/code-coverage", + "usage/configuration", + "usage/output", + "usage/vscode", + "usage/troubleshooting" + ], + "Assertions": [ + "assertions/should-command", + "assertions/assertions", + "assertions/custom-assertions" + ], + "Migration Guides": [ + "migrations/v4-to-v5", + "migrations/breaking-changes-in-v5", + "migrations/v3-to-v4" + ], + "Additional Resources": [ + "additional-resources/articles", + "additional-resources/courses", + "additional-resources/misc", + "additional-resources/projects", + "additional-resources/videos" + ], + "Contributing": [ + "contributing/introduction", + "contributing/reporting-issues", + "contributing/feature-requests", + "contributing/pull-requests" + ], + "Command Reference": [ + "commands/Add-ShouldOperator", + "commands/AfterAll", + "commands/AfterEach", + "commands/Assert-MockCalled", + "commands/Assert-VerifiableMock", + "commands/BeforeAll", + "commands/BeforeDiscovery", + "commands/BeforeEach", + "commands/Context", + "commands/ConvertTo-JUnitReport", + "commands/ConvertTo-NUnitReport", + "commands/ConvertTo-Pester4Result", + "commands/Describe", + "commands/Export-JUnitReport", + "commands/Export-NUnitReport", + "commands/Get-ShouldOperator", + "commands/InModuleScope", + "commands/Invoke-Pester", + "commands/It", + "commands/Mock", + "commands/New-Fixture", + "commands/New-MockObject", + "commands/New-PesterConfiguration", + "commands/New-PesterContainer", + "commands/Set-ItResult", + "commands/Should" + ] + } +} diff --git a/versions.json b/versions.json index 1c249030..b96ddad1 100644 --- a/versions.json +++ b/versions.json @@ -1,3 +1,4 @@ [ + "v5", "v4" ]