diff --git a/build.ps1 b/build.ps1 index 6bb6dac0d..4eb4ed477 100644 --- a/build.ps1 +++ b/build.ps1 @@ -76,9 +76,8 @@ if ($Clean -and (Test-Path "$PSScriptRoot/bin")) { } if ($Clean) { - # Import-LocalizedData (and ModuleVersion-property) used as workaround due to unknown error on PS3 build with Test-ModuleManifest - # and because Test-ModuleManifest needs the psd1 and psm1 to be complete, but we want to generate help for config from the type - # so we need to build up here, and not after the module build, so xml based solution is better than one that validates the manifest + # Using Import-LocalizedData over Test-ModuleManifest because the latter requires psm1 and + # PesterConfiguration.Format.xml to exists which are both generated later in build script $manifest = Import-LocalizedData -FileName 'Pester.psd1' -BaseDirectory "$PSScriptRoot/src" if (-not $LockedRestore) { dotnet restore "$PSScriptRoot/src/csharp/Pester.sln" @@ -92,45 +91,13 @@ if ($Clean) { } } -function Copy-Content ($Content) { - foreach ($c in $content) { - $source, $destination = $c - - $null = New-Item -Force $destination -ItemType Directory - - Get-ChildItem $source -File | Copy-Item -Destination $destination - } -} - -$content = @( - , ("$PSScriptRoot/src/en-US/*.txt", "$PSScriptRoot/bin/en-US/") - , ("$PSScriptRoot/src/Pester.ps1", "$PSScriptRoot/bin/") - , ("$PSScriptRoot/src/Pester.psd1", "$PSScriptRoot/bin/") - , ("$PSScriptRoot/src/Pester.Format.ps1xml", "$PSScriptRoot/bin/") -) - if ($Clean) { - $content += @( - , ("$PSScriptRoot/src/schemas/JUnit4/*.xsd", "$PSScriptRoot/bin/schemas/JUnit4/") - , ("$PSScriptRoot/src/schemas/NUnit25/*.xsd", "$PSScriptRoot/bin/schemas/NUnit25/") - , ("$PSScriptRoot/src/schemas/NUnit3/*.xsd", "$PSScriptRoot/bin/schemas/NUnit3/") - , ("$PSScriptRoot/src/schemas/JaCoCo/*.dtd", "$PSScriptRoot/bin/schemas/JaCoCo/") - , ("$PSScriptRoot/src/csharp/Pester/bin/$Configuration/net452/Pester.dll", "$PSScriptRoot/bin/bin/net452/") - , ("$PSScriptRoot/src/csharp/Pester/bin/$Configuration/net452/Pester.pdb", "$PSScriptRoot/bin/bin/net452/") - , ("$PSScriptRoot/src/csharp/Pester/bin/$Configuration/netstandard2.0/Pester.dll", "$PSScriptRoot/bin/bin/netstandard2.0/") - , ("$PSScriptRoot/src/csharp/Pester/bin/$Configuration/netstandard2.0/Pester.pdb", "$PSScriptRoot/bin/bin/netstandard2.0/") - ) -} - -Copy-Content -Content $content - -if ($Clean) { - # update help for New-PesterConfiguration - if ($PSVersionTable.PSVersion.Major -gt 5) { - $null = [Reflection.Assembly]::LoadFrom("$PSScriptRoot/bin/bin/netstandard2.0/Pester.dll") + # Update PesterConfiguration help in about_PesterConfiguration + if ($PSVersionTable.PSVersion.Major -ge 6) { + $null = [Reflection.Assembly]::LoadFrom("$PSScriptRoot/src/csharp/Pester/bin/$Configuration/netstandard2.0/Pester.dll") } else { - $null = [Reflection.Assembly]::LoadFrom("$PSScriptRoot/bin/bin/net452/Pester.dll") + $null = [Reflection.Assembly]::LoadFrom("$PSScriptRoot/src/csharp/Pester/bin/$Configuration/net452/Pester.dll") } function Format-NicelyMini ($value) { @@ -177,49 +144,76 @@ if ($Clean) { foreach ($r in $section.PSObject.Properties.Name) { $option = $section.$r $default = Format-NicelyMini $option.Default - " ${r}: $($option.Description)$eol Default value: ${default}$eol" + $type = $option.Default.GetType() -as [string] + " ${r}: $($option.Description)$eol Type: ${type}$eol Default value: ${default}$eol" } } - $p = "$PSScriptRoot/src/Pester.RSpec.ps1" + $helpPath = "$PSScriptRoot/src/en-US/about_PesterConfiguration.help.txt" # in older versions utf8 means with BOM - $e = if ($PSVersionTable.PSVersion.Major -ge 7) { 'utf8BOM' } else { 'utf8' } - $f = Get-Content $p -Encoding $e + $enc = if ($PSVersionTable.PSVersion.Major -ge 7) { 'utf8BOM' } else { 'utf8' } + $helpContent = Get-Content $helpPath -Encoding $enc + + # Get section margin from the topic name on line 2 + $margin = if ($helpContent[1] -match '^(?\s*)about_') { $matches.margin } else { '' } $sbf = [System.Text.StringBuilder]'' $generated = $false - foreach ($l in $f) { - if ($l -match '^(?\s*)Sections and options:\s*$') { - $null = $sbf.AppendLine("$l$eol") + foreach ($line in $helpContent) { + if (-not $generated -and $line -match '^SECTIONS AND OPTIONS\s*$') { $generated = $true - $margin = $matches.margin - $null = $sbf.AppendLine("$margin``````") + $null = $sbf.AppendLine("$line$eol") - $generatedLines = @($generatedConfig -split $eol) - for ($i = 0; $i -lt $generatedLines.Count; $i++) { - $l = $generatedLines[$i] + foreach ($l in @($generatedConfig -split $eol)) { $m = if ($l) { $margin } else { $null } - - if ($i -eq $generatedLines.Count - 1) { - #last line should be blank - replace with codeblock end - $null = $sbf.AppendLine("$margin``````$eol") - } - else { - $null = $sbf.AppendLine("$m$l") - } + $null = $sbf.AppendLine("$m$l") } } - elseif ($generated -and ($l -match '^\s*(.PARAMETER|.EXAMPLE).*')) { + elseif ($generated -and ($line -cmatch '^SEE ALSO\s*$')) { $generated = $false } if (-not $generated) { - $null = $sbf.AppendLine($l) + $null = $sbf.AppendLine($line) } } - Set-Content -Encoding $e -Value $sbf.ToString().TrimEnd() -Path $p + Set-Content -Encoding $enc -Value $sbf.ToString().TrimEnd() -Path $helpPath +} - # generate PesterConfiguration.Format.ps1xml to ensure list view for all sections +function Copy-Content ($Content) { + foreach ($c in $content) { + $source, $destination = $c + + $null = New-Item -Force $destination -ItemType Directory + + Get-ChildItem $source -File | Copy-Item -Destination $destination + } +} + +$content = @( + , ("$PSScriptRoot/src/en-US/*.txt", "$PSScriptRoot/bin/en-US/") + , ("$PSScriptRoot/src/Pester.ps1", "$PSScriptRoot/bin/") + , ("$PSScriptRoot/src/Pester.psd1", "$PSScriptRoot/bin/") + , ("$PSScriptRoot/src/Pester.Format.ps1xml", "$PSScriptRoot/bin/") +) + +if ($Clean) { + $content += @( + , ("$PSScriptRoot/src/schemas/JUnit4/*.xsd", "$PSScriptRoot/bin/schemas/JUnit4/") + , ("$PSScriptRoot/src/schemas/NUnit25/*.xsd", "$PSScriptRoot/bin/schemas/NUnit25/") + , ("$PSScriptRoot/src/schemas/NUnit3/*.xsd", "$PSScriptRoot/bin/schemas/NUnit3/") + , ("$PSScriptRoot/src/schemas/JaCoCo/*.dtd", "$PSScriptRoot/bin/schemas/JaCoCo/") + , ("$PSScriptRoot/src/csharp/Pester/bin/$Configuration/net452/Pester.dll", "$PSScriptRoot/bin/bin/net452/") + , ("$PSScriptRoot/src/csharp/Pester/bin/$Configuration/net452/Pester.pdb", "$PSScriptRoot/bin/bin/net452/") + , ("$PSScriptRoot/src/csharp/Pester/bin/$Configuration/netstandard2.0/Pester.dll", "$PSScriptRoot/bin/bin/netstandard2.0/") + , ("$PSScriptRoot/src/csharp/Pester/bin/$Configuration/netstandard2.0/Pester.pdb", "$PSScriptRoot/bin/bin/netstandard2.0/") + ) +} + +Copy-Content -Content $content + +if ($Clean) { + # Generate PesterConfiguration.Format.ps1xml to ensure list view for all sections $configSections = $configObject.GetType().Assembly.GetExportedTypes() | Where-Object { $_.BaseType -eq [Pester.ConfigurationSection] } # Get internal ctor as public ctor always returns instanceId = zero guid prior to PS v7.1.0 $formatViewCtor = [System.Management.Automation.FormatViewDefinition].GetConstructors('Instance,NonPublic') @@ -237,7 +231,7 @@ if ($Clean) { # Create view for Option to ensure Table and hide IsModified $builder = [System.Management.Automation.TableControl]::Create().StartRowDefinition() - [Pester.Option[bool]].GetProperties() | Where-Object Name -notin 'IsModified' | ForEach-Object { + [Pester.Option[bool]].GetProperties() | Where-Object Name -NotIn 'IsModified' | ForEach-Object { $builder.AddPropertyColumn($_.Name, [System.Management.Automation.Alignment]::Undefined, $null) > $null } $tableControl = $builder.EndRowDefinition().EndTable() @@ -249,12 +243,12 @@ if ($Clean) { Export-FormatData -InputObject $typeDefs -Path "$PSScriptRoot/bin/PesterConfiguration.Format.ps1xml" } -if (-not $PSBoundParameters.ContainsKey("Inline")) { +if (-not $PSBoundParameters.ContainsKey('Inline')) { # Force inlining by env variable, build.ps1 is used in # multiple places and passing the $inline everywhere is # difficult. # Only read this option here. Don't write it. - if ($env:PESTER_BUILD_INLINE -eq "1") { + if ($env:PESTER_BUILD_INLINE -eq '1') { $Inline = $true } else { @@ -268,7 +262,6 @@ else { $env:PESTER_BUILD_INLINE = [string][int][bool] $Inline } - $null = New-Item "$PSScriptRoot/bin" -ItemType Directory -Force $script = @( diff --git a/publish/release.ps1 b/publish/release.ps1 index d733d54f8..813d11448 100644 --- a/publish/release.ps1 +++ b/publish/release.ps1 @@ -64,11 +64,8 @@ $files = @( 'bin/net452/Pester.pdb' 'bin/netstandard2.0/Pester.dll' 'bin/netstandard2.0/Pester.pdb' - 'en-US/about_BeforeEach_AfterEach.help.txt' - 'en-US/about_Mocking.help.txt' 'en-US/about_Pester.help.txt' - 'en-US/about_Should.help.txt' - 'en-US/about_TestDrive.help.txt' + 'en-US/about_PesterConfiguration.help.txt' 'schemas/JaCoCo/report.dtd' 'schemas/JUnit4/junit_schema_4.xsd' 'schemas/NUnit25/nunit_schema_2.5.xsd' diff --git a/src/Main.ps1 b/src/Main.ps1 index 3b923fc66..79d656665 100644 --- a/src/Main.ps1 +++ b/src/Main.ps1 @@ -419,16 +419,8 @@ function Invoke-Pester { https://github.com/danielpalme/ReportGenerator .PARAMETER Configuration - (Introduced v5) - [PesterConfiguration] object for Advanced Configuration - - Pester supports Simple and Advanced Configuration. - - Invoke-Pester -Configuration [] - - Default is New-PesterConfiguration. - - For help on each option see New-PesterConfiguration, or inspect the object it returns. + [PesterConfiguration] object for Advanced Configuration created using `New-PesterConfiguration`. + For help on each option see about_PesterConfiguration or inspect the object. .PARAMETER Container Specifies one or more ContainerInfo-objects that define containers with tests. @@ -571,7 +563,7 @@ function Invoke-Pester { even if the first fails. .EXAMPLE - $config = [PesterConfiguration]::Default + $config = New-PesterConfiguration $config.TestResult.Enabled = $true Invoke-Pester -Configuration $config diff --git a/src/Pester.RSpec.ps1 b/src/Pester.RSpec.ps1 index 339f8a691..9f043ea04 100644 --- a/src/Pester.RSpec.ps1 +++ b/src/Pester.RSpec.ps1 @@ -288,151 +288,11 @@ function New-PesterConfiguration { 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 - ``` + For a complete list of options, see `Get-Help about_PesterConfiguration` or https://pester.dev/docs/usage/configuration .PARAMETER 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 + See about_PesterConfiguration help topic or inspect a PesterConfiguration-object to learn about the schema and available options. .EXAMPLE @@ -476,6 +336,9 @@ function New-PesterConfiguration { .LINK https://pester.dev/docs/commands/Invoke-Pester + + .LINK + about_PesterConfiguration #> [CmdletBinding()] param( diff --git a/src/en-US/about_BeforeEach_AfterEach.help.txt b/src/en-US/about_BeforeEach_AfterEach.help.txt deleted file mode 100644 index f31ba1b80..000000000 --- a/src/en-US/about_BeforeEach_AfterEach.help.txt +++ /dev/null @@ -1,88 +0,0 @@ -TOPIC - about_BeforeEach_AfterEach - -SHORT DESCRIPTION - Describes the BeforeEach and AfterEach commands, which run a set of commands that you specify - before or after every It block. - -LONG DESCRIPTION - The the BeforeEach and AfterEach commands in the Pester module let you define setup and teardown - tasks that are performed at the beginning and end of every It block. This can eliminate duplication of code - in test scripts, ensure that each test is performed on a pristine state regardless of their - order, and perform any necessary clean-up tasks after each test. - - BeforeEach and AfterEach blocks may be defined inside of any Describe or Context. If they - are present in both a Context and its parent Describe, BeforeEach blocks in the Describe scope - are executed first, followed by BeforeEach blocks in the Context scope. AfterEach blocks are - the reverse of this, with the Context AfterEach blocks executing before Describe. - - The script blocks assigned to BeforeEach and AfterEach are dot-sourced in the Context or Describe - which contains the current It statement, so you don't have to worry about the scope of variable - assignments. Any variables that are assigned values within a BeforeEach block can be used inside - the body of the It block. - - BeforeAll and AfterAll are used the same way as BeforeEach and AfterEach, except that they are - executed at the beginning and end of their containing Describe or Context block. This is - essentially syntactic sugar for the following arrangement of code: - - Describe 'Something' { - try - { - - - - } - finally - { - - } - } - - - SYNTAX AND PLACEMENT - Unlike most of the commands in a Pester script, BeforeEach, AfterEach, BeforeAll and AfterAll blocks - apply to the entire Describe or Context scope in which they are defined, regardless of the order of - commands inside the Describe or Context. In other words, even if an It block appears before BeforeEach - or AfterEach in the tests file, the BeforeEach and AfterEach will still be executed. Likewise, BeforeAll - code will be executed at the beginning of a Context or Describe block regardless of where it is found, - and AfterAll code will execute at the end of the Context or Describe. - - - EXAMPLES - Describe 'Testing BeforeEach and AfterEach' { - $afterEachVariable = 'AfterEach has not been executed yet' - - It 'Demonstrates that BeforeEach may be defined after the It command' { - $beforeEachVariable | Should -Be 'Set in a describe-scoped BeforeEach' - $afterEachVariable | Should -Be 'AfterEach has not been executed yet' - $beforeAllVariable | Should -Be 'BeforeAll has been executed' - } - - It 'Demonstrates that AfterEach has executed after the end of the first test' { - $afterEachVariable | Should -Be 'AfterEach has been executed' - } - - BeforeEach { - $beforeEachVariable = 'Set in a describe-scoped BeforeEach' - } - - AfterEach { - $afterEachVariable = 'AfterEach has been executed' - } - - BeforeAll { - $beforeAllVariable = 'BeforeAll has been executed' - } - } - -SEE ALSO - about_Pester - about_Should - about_Mocking - about_TestDrive - about_about_Try_Catch_Finally - Describe - Context - Should - It - Invoke-Pester diff --git a/src/en-US/about_Mocking.help.txt b/src/en-US/about_Mocking.help.txt deleted file mode 100644 index d10aa65a1..000000000 --- a/src/en-US/about_Mocking.help.txt +++ /dev/null @@ -1,207 +0,0 @@ -TOPIC - about_Mocking - -SHORT 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. - -LONG 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 - For detailed information about the functions in the Pester module, use Get-Help. - - Mock - Mocks the behavior of an existing command with an alternate - implementation. - - Assert-VerifiableMock - Checks if any Verifiable Mock has not been invoked. If so, this will - throw an exception. - - Assert-MockCalled - Checks if a Mocked command has been called a certain number of times - and throws an exception if it has not. - - EXAMPLE - function Build ($version) { - Write-Host "a build was run for version: $version" - } - - function BuildIfChanged { - $thisVersion = Get-Version - $nextVersion = Get-NextVersion - if ($thisVersion -ne $nextVersion) { Build $nextVersion } - return $nextVersion - } - - $here = Split-Path -Parent $MyInvocation.MyCommand.Path - $sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path).Replace(".Tests.", ".") - . "$here\$sut" - - Describe "BuildIfChanged" { - Context "When there are Changes" { - 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" { - Assert-VerifiableMock - } - It "returns the next version number" { - $result | Should -Be 1.2 - } - } - Context "When there are no Changes" { - Mock Get-Version { return 1.1 } - Mock Get-NextVersion { return 1.1 } - Mock Build {} - - $result = BuildIfChanged - - It "Should not build the next version" { - Assert-MockCalled Build -Times 0 -ParameterFilter {$version -eq 1.1} - } - } - } - - - MOCKING CALLS TO COMMANDS MADE FROM INSIDE SCRIPT MODULES - - Let's say you have code like this inside a script module (.psm1 file): - - 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 - - Beginning in Pester 3.0, there are two ways to write a unit test for a module that - mocks the calls to Get-Version and Get-NextVersion from the module's BuildIfChanged - command. The first is to inject mocks into a module: - - In these examples, the PSM1 file, MyModule.psm1 is installed in $env:PSModulePath on - the local computer. - - Import-Module MyModule - - Describe "BuildIfChanged" { - Context "When there are Changes" { - Mock -ModuleName MyModule Get-Version { return 1.1 } - Mock -ModuleName MyModule Get-NextVersion { return 1.2 } - - # To demonstrate that you can mock calls to commands other than functions - # defined in the same module, we'll mock a call to Write-Host. - - 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" { - Assert-VerifiableMock - } - - It "returns the next version number" { - $result | Should -Be 1.2 - } - } - - Context "When there are no Changes" { - 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" { - Assert-MockCalled Build -ModuleName MyModule -Times 0 -ParameterFilter { - $version -eq 1.1 - } - } - } - } - - - In this sample test script, all calls to Mock and Assert-MockCalled have the - -ModuleName MyModule parameter added. This tells Pester to inject the mock into the module 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. For example, you could not call the Build function directly. - - The InModuleScope command causes entire sections of your test script to execute inside the targeted - script module. This gives you access to unexported members of the module. For example: - - Import-Module MyModule - - Describe "Unit testing the module's internal Build function:" { - InModuleScope MyModule { - $testVersion = 5.0 - Mock Write-Host { } - - Build $testVersion - - It 'Outputs the correct message' { - Assert-MockCalled Write-Host -ParameterFilter { - $Object -eq "a build was run for version: $testVersion" - } - } - } - } - - When using InModuleScope, you no longer need to specify a ModuleName parameter when calling - Mock or Assert-MockCalled for commands in the module. You can also directly call the Build - function that the module does not export. - -SEE ALSO - Mock - Assert-VerifiableMock - Assert-MockCalled - InModuleScope - Describe - Context - It - - The following articles are useful for further understanding of Pester Mocks. - Pester Mock and Test Drive, by Jakub Jareš: - http://www.powershellmagazine.com/2014/09/30/pester-mock-and-testdrive/ - Pester and Mocking, by Mickey Gousset: - http://www.systemcentercentral.com/day-53-pester-mocking/ - Mocking Missing Cmdlets with Pester, by Iain Brighton: - http://virtualengine.co.uk/2015/mocking-missing-cmdlets-with-pester/ - Testing Mocked Output with Pester, by Steven Murawski: - http://stevenmurawski.com/powershell/2014/02/testing-returned-objects-with-pester/ - - The following articles are useful for deeper understanding of Mocking in general. - Answer to the Question "What is the Purpose of Mock Objects" by Bert F: - http://stackoverflow.com/a/3623574/5514075 - Mocks Aren't Stubs, by Martin Fowler: - http://martinfowler.com/articles/mocksArentStubs.html - The Art of Mocking, by Gil Zilberfeld: - http://www.methodsandtools.com/archive/archive.php?id=122 diff --git a/src/en-US/about_Pester.help.txt b/src/en-US/about_Pester.help.txt index a32ecf78b..ad8ec2587 100644 --- a/src/en-US/about_Pester.help.txt +++ b/src/en-US/about_Pester.help.txt @@ -2,32 +2,32 @@ about_Pester SHORT DESCRIPTION - Pester is a test framework for Windows PowerShell. Use the Pester language - and its commands to write and run tests that verify that your scripts and - modules work as designed. - - Pester 3.4.0 supports Windows PowerShell 2.0 and greater. + Pester is a test framework for PowerShell. Use the Pester language + and its commands to write and run tests that verifies that your scripts, modules, + infrastructure and more works as intended. LONG DESCRIPTION - Pester introduces a professional test framework for Windows PowerShell - commands. You can use Pester to test commands of any supported type, - including scripts, cmdlets, functions, CIM commands, workflows, and DSC - resources, and test these commands in modules of all types. - - Each Pester test compares actual to expected output using a collection of - comparison operators that mirror the familiar operators in Windows - PowerShell. In this way, Pester supports "dynamic testing", that is, it - tests the code while it's running, instead of just evaluating code syntax - ("static testing"). - - Once your Pester tests are written are verified to work correctly, you can - run them automatically or on demand to verify that the output didn't change - and that any code changes did not introduce errors. You can also add your - tests to the build scripts of a continuous integration system, and add new - tests at any time. - - - WHAT CAN PESTER TEST? + 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 configurable file naming convention *.Tests.ps1, and uses a simple set of functions including: + -- Describe: Creates a required test container. + -- Context: Creates an optional scoped test sub-container. + -- It: Creates a test. + -- Should*: Operators that help you compare actual vs expected values inside a test. + -- Mock: Replace behaviours of any commands to make them return consistent values. + + 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, but also as part of your + build/deployment scripts in a CI or CD pipeline for validation. + + Other notable features included in Pester: + -- Test results exported to popular file formats for easier reporting + -- Code coverage to measure and report on how much of your code is actually tested + -- TestDrive and TestRegistry (Windows only) PSDrives to temporarily store files and values during your tests with automatic cleanup. + +WHAT CAN PESTER TEST? Pester is designed to support "test-driven development" (TDD), in which you write and run tests before writing your code, thereby using the test as a code specification. @@ -41,257 +41,16 @@ LONG DESCRIPTION isolation and "integration tests" that verify that functions can be used together to generate expected results. - Pester creates and manages a temporary drive (PSDrive named TestDrive:) that - you can use to simulate a file system. For more information, see - about_TestDrive. - Pester also has "mocking" commands that replace the actual output of - commands with output that you specify. Mocking lets you test your commands - with varied input without creating and maintaining fake entries in a file - or database, or commenting-out and inserting code just for testing. For more - information, see about_Mocking. - - - THE PESTER LANGUAGE - To make it easier to write tests, Pester uses a language especially designed - for testing. This "domain-specific language" (DSL) hides the standard - verb-noun syntax of PowerShell commands. - - To make the language more fluent, the command parameters are positional, so - you don't typically use parameter names. - - For example, this "gets all widgets" test uses the Pester language, - including its "It", "Should", and "Be" commands. The test verifies that the - actual output of the Get-Widget cmdlet is the same as the expected value in - the $allWidgets variables. - - It "gets all widgets" { - Get-Widget | Should -Be $allWidgets - } - - - To learn the Pester language, start by reading the following About and - cmdlet help topics: - - -- Describe: Creates a required test container. - -- Context: Creates an optional scoped test sub-container. - -- It: Creates a test. - -- about_Should Compares actual to expected values. This topic also - lists all valid values of Be, which specify the - comparison operator used in the test. - - - - HOW TO CREATE TEST FILES - To start using Pester, create a script and a test file that tests the - script. If you already have a script, you can create a test file for it. - - Pester test files are Windows PowerShell scripts with a .Tests.ps1 file name - extension. The distinctive file name extension enables Pester to identify - tests and distinguish them from other scripts. - - Typically, the test file and file it tests have the same base file name, - such as: - - New-Log.ps1 - New-Log.Tests.ps1 - - For a quick start, use the New-Fixture cmdlet in the Pester module. It - creates a script with an empty function and a matching test file with a - valid test. - - For example, this command creates a New-Log.ps1 script and a - New-Log.Tests.ps1 test script in the C:\Scripts\LogScripts directory. - - New-Fixture -Path C:\Scripts\LogScripts -Name New-Log - - Directory: C:\Scripts\LogScripts - - - Mode LastWriteTime Length Name - ---- ------------- ------ ---- - -a---- 4/18/2016 9:51 AM 30 New-Log.ps1 - -a---- 4/18/2016 9:51 AM 262 New-Log.Tests.ps1 - - - The similar names do not automatically associate the test file and script - file. The test file must include code to import ("dot-source") the - functions, aliases, and variables in the script being tested into the scope - of the test script. - - For example: - . .\New-Log.ps1 - -or- - . C:\Scripts\LogScripts\New-Log.ps1 - - - Many Pester test files, including the files that New-Fixture creates, begin with these - statements. - - $here = Split-Path -Parent $MyInvocation.MyCommand.Path - $sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path) -replace '\.Tests\.', '.' - . "$here\$sut" - - This code finds the current path of the test file at run time and saves it - in the $here variable. Then, it finds the script based on the path in $here. - This code assumes that the script has the same base name and is located in - the same directory as the test file. - - You can use any code in the test file that finds the script, but be sure - that the test file has the required *.Tests.ps1 file name extension. - - - - HOW TO RUN PESTER TESTS - Pester tests are Windows PowerShell scripts (.ps1 files), so you can run - them at the command line, or in any editor. - - Pester also has an Invoke-Pester cmdlet with useful parameters. By default, - Invoke-Pester runs all the tests in a directory and all of its subdirectories - recursively, but you can run selected tests by specifying a script name or - name pattern, a test name, or a test tag. - - Invoke-Pester parameters also let you save the test output in NUnitXml or - JUnitXml formats that are commonly used by reporting tools. - - For example, the following command runs all tests in the current directory - and all subdirectories recursively. It writes output to the host, but does - not generate any objects. - - Invoke-Pester - - In contrast, this command runs only the tests in the New-Log.Tests.ps1 file - that have the 'EventVwr' tag. It writes the test results as custom objects - and saves them in NUnitXml format in the NewLogTests.xml file. It also runs - an optional code coverage test to verify that all lines in the script ran - at least once during the tests. - - Invoke-Pester -Script C:\Tests\New-Log.Tests.ps1 ` - -Tag EventVwr -OutputFile .\NewLogTests.xml -OutputFormat NUnitXml ` - -CodeCoverage - - - To run the New-Log.Tests.ps1 file that New-Fixture created, change to its - local directory or a parent directory, and run Invoke-Pester. You can also - use the Script parameter of Invoke-Pester to run only the New-Log.Tests.ps1 - test. - - PS C:\Scripts> Invoke-Pester -Script .\New-Log.Tests.ps1 - - For more information about Invoke-Pester, type: Get-Help Invoke-Pester - - - EXAMPLE - For your first Pester test, use the New-Fixture cmdlet to create a script - file and matching test file. - - For example: - - New-Fixture -Path C:\TestPester -Name Get-Hello - - Directory: C:\TestPester - - - Mode LastWriteTime Length Name - ---- ------------- ------ ---- - -a---- 4/18/2016 9:51 AM 30 Get-Hello.ps1 - -a---- 4/18/2016 9:51 AM 262 Get-Hello.Tests.ps1 - - - The Get-Hello.ps1 script contains an empty Get-Hello.ps1 function. - - function Get-Hello {} - - The Get-Hello.Tests.ps1 file contains an empty Pester test that is named - for the Get-Hello function. - - Describe "Get-Hello" { - It "does something useful" { - $true | Should -Be $false - } - } - - To run the test, use Invoke-Pester. For example, - - Invoke-Pester C:\TestPester - - When you run the test, it fails by design, because Should compares $True to - $False using the equal operator ("Be") and $True doesn't equal $False. - - - To start testing the Get-Hello function, change $True to Get-Hello and - $False to "Hello". Now, the test compares the output of Get-Hello output to - 'hello'. - - It should still fail, because Get-Hello doesn't return anything. - - Describe "New-Log" { - It "does something useful" { - Get-Hello | Should -Be 'Hello' - } - } - - - To make the test pass, change the Get-Hello function so it returns 'hello'. - Then, in steps, change $False to more interesting values, then change the - Get-Hello function output to make the test pass. - - You can also experiment with other comparison operators, such as the BeLike - (supports wildcards) and BeExactly (case sensitive), and BeLikeExactly - operators. For more, information about comparison operators in Pester, see - about_Should. - - - PESTER TEST OUTPUT - When you run a test, Pester use a variation of Write-Host to write - color-coded text to the console. You'll quickly learn to recognize the - purple test names and green (passing) and red (failing) test results with - the elapsed time of the test. - - Describing Get-Profile - [+] Gets all profiles 156ms - [+] Gets only profiles 24ms - - The output ends with a summary of the test results. - - Tests completed in 3.47s - Tests Passed: 20, Failed: 1, Skipped: 0, Inconclusive: 0, NotRun: 0 - - However, because Pester uses Write-Host, it does not write to the output - stream (stdout), so there are no output objects to save in a variable or - redirect to a file. - - To direct Pester to create custom objects, use its PassThru parameter. The - result is a single PSCustomObject with a TestResult property that one - TestResult custom object for each test in the test file. - - To save the custom objects to a file, use the OutputFile and OutputFormat - parameters of Invoke-Pester, which save the output in NUnitXml and - JUnitXml formats that are easy to parse and commonly used by reporting - tools. - - - - REAL-WORLD EXAMPLES - For help in writing Pester tests, examine the extensive collection of tests - that Pester uses to verify its Windows PowerShell code. - - To find the Pester tests in the Pester module directory, type: - - dir \*Tests.ps1 -Recurse - - -or- + commands with output that you specify, making unit testing easier by controlling and getting consistent output. - dir (Get-Module Pester -ListAvailable).ModuleBase -Include *Tests.ps1 -Recurse +HOW DO I GET STARTED? +You've already done the hard part by discovering and installing this module. +Visit https://pester.dev/docs/quick-start to get an introduction to using Pester with examples and documentation for +all mentioned features and more. SEE ALSO Pester website: https://pester.dev - Describe - Context - It - New-Fixture Invoke-Pester - about_Mocking - about_Should - about_TestDrive + about_PesterConfiguration diff --git a/src/en-US/about_PesterConfiguration.help.txt b/src/en-US/about_PesterConfiguration.help.txt new file mode 100644 index 000000000..5057e0042 --- /dev/null +++ b/src/en-US/about_PesterConfiguration.help.txt @@ -0,0 +1,215 @@ +TOPIC + about_PesterConfiguration + +SHORT DESCRIPTION + Pester uses a PesterConfiguration-object to configure all of it's options. It is the source of truth for the defaults and provides all supported options. + +LONG DESCRIPTION + Pester can be invoked using either a limited set of parameters in Invoke-Pester (Simple interface) or + by providing a PesterConfiguration object (Advanced interface) that supports all available options. + + When Invoke-Pester is invoked using the simple parameters it is internally translated to a full configuration-object, + using the default values for any undefined options. + + The configuration object can be navigated interactively in the console to view all options including description, current and default values. + +EXAMPLE + Below we can se an example of how to run Pester using a configuration object: + + # Get default configuration + $configuration = New-PesterConfiguration + # Changing a few options including the path for our test files. + $configuration.Run.Path = '.\tests' + $configuration.Filter.Tag = 'Acceptance' + $configuration.Filter.ExcludeTag = 'WindowsOnly' + $configuration.Output.Verbosity = 'Detailed' + # Run Pester + Invoke-Pester -Configuration $configuration + +SECTIONS AND OPTIONS + + Run: + Path: Directories to be searched for tests, paths directly to test files, or combination of both. + Type: string[] + Default value: @('.') + + ExcludePath: Directories or files to be excluded from the run. + Type: string[] + Default value: @() + + ScriptBlock: ScriptBlocks containing tests to be executed. + Type: scriptblock[] + Default value: @() + + Container: ContainerInfo objects containing tests to be executed. + Type: Pester.ContainerInfo[] + Default value: @() + + TestExtension: Filter used to identify test files. + Type: string + 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. + Type: bool + Default value: $false + + Throw: Throw an exception when test run fails. When used together with Exit, throwing an exception is preferred. + Type: bool + Default value: $false + + PassThru: Return result object to the pipeline after finishing the test run. + Type: bool + Default value: $false + + SkipRun: Runs the discovery phase but skips run. Use it with PassThru to get object populated with all tests. + Type: bool + Default value: $false + + SkipRemainingOnFailure: Skips remaining tests after failure for selected scope, options are None, Run, Container and Block. + Type: string + Default value: 'None' + + Filter: + Tag: Tags of Describe, Context or It to be run. + Type: string[] + Default value: @() + + ExcludeTag: Tags of Describe, Context or It to be excluded from the run. + Type: string[] + 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' + Type: string[] + Default value: @() + + ExcludeLine: Exclude by file and scriptblock start line, takes precedence over Line. + Type: string[] + Default value: @() + + FullName: Full name of test with -like wildcards, joined by dot. Example: '*.describe Get-Item.test1' + Type: string[] + Default value: @() + + CodeCoverage: + Enabled: Enable CodeCoverage. + Type: bool + Default value: $false + + OutputFormat: Format to use for code coverage report. Possible values: JaCoCo, CoverageGutters + Type: string + Default value: 'JaCoCo' + + OutputPath: Path relative to the current directory where code coverage report is saved. + Type: string + Default value: 'coverage.xml' + + OutputEncoding: Encoding of the output file. + Type: string + 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. + Type: string[] + Default value: @() + + ExcludeTests: Exclude tests from code coverage. This uses the TestFilter from general configuration. + Type: bool + Default value: $true + + RecursePaths: Will recurse through directories in the Path option. + Type: bool + Default value: $true + + CoveragePercentTarget: Target percent of code coverage that you want to achieve, default 75%. + Type: decimal + Default value: 75 + + UseBreakpoints: EXPERIMENTAL: When false, use Profiler based tracer to do CodeCoverage instead of using breakpoints. + Type: bool + Default value: $true + + SingleHitBreakpoints: Remove breakpoint when it is hit. + Type: bool + Default value: $true + + TestResult: + Enabled: Enable TestResult. + Type: bool + Default value: $false + + OutputFormat: Format to use for test result report. Possible values: NUnitXml, NUnit2.5, NUnit3 or JUnitXml + Type: string + Default value: 'NUnitXml' + + OutputPath: Path relative to the current directory where test result report is saved. + Type: string + Default value: 'testResults.xml' + + OutputEncoding: Encoding of the output file. + Type: string + Default value: 'UTF8' + + TestSuiteName: Set the name assigned to the root 'test-suite' element. + Type: string + 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. + Type: string + 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'. + Type: bool + Default value: $false + + WriteDebugMessages: Write Debug messages to screen. + Type: bool + 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. + Type: string[] + Default value: @('Discovery', 'Skip', 'Mock', 'CodeCoverage') + + ShowNavigationMarkers: Write paths after every block and test, for easy navigation in VSCode. + Type: bool + 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. + Type: bool + Default value: $false + + Output: + Verbosity: The verbosity of output, options are None, Normal, Detailed and Diagnostic. + Type: string + Default value: 'Normal' + + StackTraceVerbosity: The verbosity of stacktrace output, options are None, FirstLine, Filtered and Full. + Type: string + Default value: 'Filtered' + + CIFormat: The CI format of error output in build logs, options are None, Auto, AzureDevops and GithubActions. + Type: string + Default value: 'Auto' + + CILogLevel: The CI log level in build logs, options are Error and Warning. + Type: string + Default value: 'Error' + + RenderMode: The mode used to render console output, options are Auto, Ansi, ConsoleColor and Plaintext. + Type: string + Default value: 'Auto' + + TestDrive: + Enabled: Enable TestDrive. + Type: bool + Default value: $true + + TestRegistry: + Enabled: Enable TestRegistry. + Type: bool + Default value: $true + +SEE ALSO + Pester website: https://pester.dev + New-PesterConfiguration + Invoke-Pester diff --git a/src/en-US/about_Should.help.txt b/src/en-US/about_Should.help.txt deleted file mode 100644 index 3e03df2ff..000000000 --- a/src/en-US/about_Should.help.txt +++ /dev/null @@ -1,251 +0,0 @@ -TOPIC - about_Should - -SHORT DESCRIPTION - Provides assertion convenience methods for comparing objects and throwing - test failures when test expectations fail. - -LONG DESCRIPTION - Should is an Extension of System.Object and can be used as a native type - inside Describe blocks. The various Should member methods can be invoked - directly from an object being compared. It is typically used in individual - It blocks to verify the results of an expectation. The Should method is - typically called from the "actual" object being compared and takes the - expected" object as a parameter. Should includes several members that - perform various comparisons of objects and will throw a PesterFailure when - the objects do not evaluate to be comparable. - -SHOULD MEMBERS - GENERAL - Be - Compares one object with another for equality and throws if the two - objects are not the same. - - $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. - - $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. - - [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. - - $actual="Actual value" - $actual | Should -BeExactly "Actual value" # Test will pass - $actual | Should -BeExactly "actual value" # Test will fail - - BeNullOrEmpty - Checks values for null or empty (strings). The static [String]::IsNullOrEmpty() method is used to do the comparison. - - $null | Should -BeNullOrEmpty # Test will pass - $null | Should -Not -BeNullOrEmpty # Test will fail - @() | Should -BeNullOrEmpty # Test will pass - "" | Should -BeNullOrEmpty # Test will pass - BeTrue - Asserts that the value is true, or truthy. - - $true | Should -BeTrue - 1 | Should -BeTrue - 1,2,3 | Should -BeTrue - - BeFalse - Asserts that the value is false of falsy. - - $false | Should -BeFalse - 0 | Should -BeFalse - $null | Should -BeFalse - - BeOfType, HaveType - 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: - - $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 -HaveType 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 - - - TEXT - BeLike - Asserts that the actual value matches a wildcard pattern using PowerShell's -like operator. This comparison is not case-sensitive. - - $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 -like operator. This comparison is case-sensitive. - - $actual="Actual value" - $actual | Should -BeLikeExactly "Actual *" # Test will pass - $actual | Should -BeLikeExactly "actual *" # Test will fail - - Match - Uses a regular expression to compare two objects. This comparison is not case sensitive. - - "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. - - "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. - - "I am a value" | Should -MatchExactly "I am" # Test will pass - "I am a value" | Should -MatchExactly "I Am" # Test will fail - - COMPARISON - 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. - - 2 | Should -BeGreaterThan 0 - - 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. - - 2 | Should -BeGreaterOrEqual 0 - 2 | Should -BeGreaterOrEqual 2 - - 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. - - 1 | Should -BeLessThan 10 - - 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. - - 1 | Should -BeLessOrEqual 10 - 10 | Should -BeLessOrEqual 10 - - COLLECTION - BeIn - Asserts that a collection of values contain a specific value. Uses PowerShell's -contains operator to confirm. - - 1 | Should -BeIn @(1,2,3,'a','b','c') - - Contain - Asserts that collection contains a specific value. Uses PowerShell's -contains operator to confirm. - - 1,2,3 | Should -Contain 1 - - HaveCount - Asserts that a collection has the expected amount of items. - - 1,2,3 | Should -HaveCount 3 - - FILE - 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. - - $actual=(Dir . )[0].FullName - Remove-Item $actual - $actual | Should -Exist # Test will fail - - FileContentMatch - Checks to see if a file contains the specified text. This search is not case sensitive and uses regular expressions. - - 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. - - 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 - - FileContentMatchExactly - Checks to see if a file contains the specified text. This search is case sensitive and uses regular expressions to match the text. - - 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 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. - - $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. - - $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. - - - EXCEPTIONS - Throw - Checks if an exception was thrown. Enclose input in a script block. - - { 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 - - Warning: The input object must be a ScriptBlock, otherwise it is processed outside of the assertion. - - Get-Process -Name "process" -ErrorAction Stop | Should -Throw # Should pass, but the exception thrown by Get-Process causes the test to fail. - - NEGATIVE ASSERTIONS - Any of the Should operators described above can be negated by using the word "Not" before the operator. For example: - - 'one' | Should -Not -Be 'Two' - { Get-Item $env:SystemRoot } | Should -Not -Throw - - USING SHOULD IN A TEST - - function Add-Numbers($a, $b) { - return $a + $b - } - - Describe "Add-Numbers" { - - It "adds positive numbers" { - $sum = Add-Numbers 2 3 - $sum | Should -Be 3 - } - } - - This test will fail since 3 will not be equal to the sum of 2 and 3. - - BECAUSE - Every built in assertion allows you to specify -Because parameter, to give more meaning to your tests. - - function Get-Group { $null } - $groups = 1..10 | Get-Group -Size 3 - $groups | Should -HaveCount 4 -Because "because 10 items are split into three groups with 3 members and one extra group with 1 member" - - Which fails with: "Expected a collection with size {4}, because 10 items are split into three groups with 3 members and one extra group with 1 member, but got collection with size {1} []. - -SEE ALSO - Describe - Context - It diff --git a/src/en-US/about_TestDrive.help.txt b/src/en-US/about_TestDrive.help.txt deleted file mode 100644 index 28cd87bf0..000000000 --- a/src/en-US/about_TestDrive.help.txt +++ /dev/null @@ -1,44 +0,0 @@ -TOPIC - about_TestDrive - -SHORT DESCRIPTION - A PSDrive for file activity limited to the scope of a singe Describe or - Context block. - -LONG DESCRIPTION - 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 - names PSDrive TestDrive:. Pester will remove this drive after the test - completes. You may use this drive to isolate the file operations of your - test to a temporary store. - -EXAMPLE - 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") - } - } - - When this test completes, the contents of the TestDrive PSDrive will - be removed. - -SEE ALSO - Context - Describe - It - about_Should