Showing preview only (3,286K chars total). Download the full file or copy to clipboard to get everything.
Repository: giMini/mimiDbg
Branch: master
Commit: 236a5f1d7d35
Files: 349
Total size: 3.1 MB
Directory structure:
gitextract_imkf2kq6/
├── .gitattributes
├── .gitignore
├── DbgShell/
│ ├── x64/
│ │ ├── DbgShell.exe.config
│ │ ├── DbgShell.pdb
│ │ ├── DbgShellExt.iobj
│ │ ├── DbgShellExt.ipdb
│ │ ├── DbgShellExt.pdb
│ │ ├── DbgShellTest/
│ │ │ ├── CoCreateShim.iobj
│ │ │ ├── CoCreateShim.ipdb
│ │ │ ├── CoCreateShim.pdb
│ │ │ ├── DbgShellTest.psd1
│ │ │ ├── DbgShellTest.psm1
│ │ │ ├── Pester/
│ │ │ │ ├── CHANGELOG.md
│ │ │ │ ├── Functions/
│ │ │ │ │ ├── Assertions/
│ │ │ │ │ │ ├── Be.Tests.ps1
│ │ │ │ │ │ ├── Be.ps1
│ │ │ │ │ │ ├── BeGreaterThan.Tests.ps1
│ │ │ │ │ │ ├── BeGreaterThan.ps1
│ │ │ │ │ │ ├── BeLessThan.Tests.ps1
│ │ │ │ │ │ ├── BeLessThan.ps1
│ │ │ │ │ │ ├── BeNullOrEmpty.Tests.ps1
│ │ │ │ │ │ ├── BeNullOrEmpty.ps1
│ │ │ │ │ │ ├── BeOfType.Tests.ps1
│ │ │ │ │ │ ├── BeOfType.ps1
│ │ │ │ │ │ ├── Contain.Tests.ps1
│ │ │ │ │ │ ├── Contain.ps1
│ │ │ │ │ │ ├── ContainExactly.Tests.ps1
│ │ │ │ │ │ ├── ContainExactly.ps1
│ │ │ │ │ │ ├── Exist.Tests.ps1
│ │ │ │ │ │ ├── Exist.ps1
│ │ │ │ │ │ ├── Match.Tests.ps1
│ │ │ │ │ │ ├── Match.ps1
│ │ │ │ │ │ ├── MatchExactly.Tests.ps1
│ │ │ │ │ │ ├── MatchExactly.ps1
│ │ │ │ │ │ ├── PesterThrow.Tests.ps1
│ │ │ │ │ │ ├── PesterThrow.ps1
│ │ │ │ │ │ ├── Set-TestInconclusive.ps1
│ │ │ │ │ │ ├── Should.Tests.ps1
│ │ │ │ │ │ ├── Should.ps1
│ │ │ │ │ │ └── Test-Assertion.ps1
│ │ │ │ │ ├── BreakAndContinue.Tests.ps1
│ │ │ │ │ ├── Context.Tests.ps1
│ │ │ │ │ ├── Context.ps1
│ │ │ │ │ ├── Coverage.Tests.ps1
│ │ │ │ │ ├── Coverage.ps1
│ │ │ │ │ ├── Describe.Tests.ps1
│ │ │ │ │ ├── Describe.ps1
│ │ │ │ │ ├── GlobalMock-A.Tests.ps1
│ │ │ │ │ ├── GlobalMock-B.Tests.ps1
│ │ │ │ │ ├── In.Tests.ps1
│ │ │ │ │ ├── In.ps1
│ │ │ │ │ ├── InModuleScope.Tests.ps1
│ │ │ │ │ ├── InModuleScope.ps1
│ │ │ │ │ ├── It.Tests.ps1
│ │ │ │ │ ├── It.ps1
│ │ │ │ │ ├── Mock.Tests.ps1
│ │ │ │ │ ├── Mock.ps1
│ │ │ │ │ ├── New-Fixture.Tests.ps1
│ │ │ │ │ ├── New-Fixture.ps1
│ │ │ │ │ ├── PesterState.Tests.ps1
│ │ │ │ │ ├── PesterState.ps1
│ │ │ │ │ ├── SetupTeardown.Tests.ps1
│ │ │ │ │ ├── SetupTeardown.ps1
│ │ │ │ │ ├── TestDrive.Tests.ps1
│ │ │ │ │ ├── TestDrive.ps1
│ │ │ │ │ ├── TestResults.Tests.ps1
│ │ │ │ │ ├── TestResults.ps1
│ │ │ │ │ └── TestsRunningInCleanRunspace.Tests.ps1
│ │ │ │ ├── LICENSE
│ │ │ │ ├── Pester.Tests.ps1
│ │ │ │ ├── Pester.psd1
│ │ │ │ ├── Pester.psm1
│ │ │ │ ├── README.md
│ │ │ │ ├── Snippets/
│ │ │ │ │ ├── Context.snippets.ps1xml
│ │ │ │ │ ├── Describe.snippets.ps1xml
│ │ │ │ │ ├── It.snippets.ps1xml
│ │ │ │ │ ├── ShouldBe.snippets.ps1xml
│ │ │ │ │ ├── ShouldBeGreaterThan.snippets.ps1xml
│ │ │ │ │ ├── ShouldBeLessThan.snippets.ps1xml
│ │ │ │ │ ├── ShouldBeNullOrEmpty.snippets.ps1xml
│ │ │ │ │ ├── ShouldContain.snippets.ps1xml
│ │ │ │ │ ├── ShouldExist.snippets.ps1xml
│ │ │ │ │ ├── ShouldMatch.snippets.ps1xml
│ │ │ │ │ ├── ShouldNotBe.snippets.ps1xml
│ │ │ │ │ ├── ShouldNotBeNullOrEmpty.snippets.ps1xml
│ │ │ │ │ ├── ShouldNotContain.snippets.ps1xml
│ │ │ │ │ ├── ShouldNotExist.snippets.ps1xml
│ │ │ │ │ ├── ShouldNotMatch.snippets.ps1xml
│ │ │ │ │ ├── ShouldNotThrow.snippets.ps1xml
│ │ │ │ │ └── ShouldThrow.snippets.ps1xml
│ │ │ │ ├── en-US/
│ │ │ │ │ ├── about_BeforeEach_AfterEach.help.txt
│ │ │ │ │ ├── about_Mocking.help.txt
│ │ │ │ │ ├── about_Pester.help.txt
│ │ │ │ │ ├── about_TestDrive.help.txt
│ │ │ │ │ └── about_should.help.txt
│ │ │ │ └── nunit_schema_2.5.xsd
│ │ │ ├── TestManagedCommon.pdb
│ │ │ ├── TestManagedConsoleApp.exe.config
│ │ │ ├── TestManagedConsoleApp.pdb
│ │ │ ├── TestNativeConsoleApp.exp
│ │ │ ├── TestNativeConsoleApp.iobj
│ │ │ ├── TestNativeConsoleApp.ipdb
│ │ │ ├── TestNativeConsoleApp.lib
│ │ │ ├── TestNativeConsoleApp.pdb
│ │ │ ├── Tests/
│ │ │ │ ├── Disasm.Tests.ps1
│ │ │ │ ├── Dumps.Tests.ps1
│ │ │ │ ├── Gu.Tests.ps1
│ │ │ │ ├── Kill.Tests.ps1
│ │ │ │ ├── MultiProcDetachAttach.Tests.ps1
│ │ │ │ ├── NamespaceTests/
│ │ │ │ │ ├── ContentTests.ps1
│ │ │ │ │ ├── CopyItem.ps1
│ │ │ │ │ ├── DriveTests.ps1
│ │ │ │ │ ├── Globbing.ps1
│ │ │ │ │ ├── MoveItem.ps1
│ │ │ │ │ ├── ProviderTests.metadata
│ │ │ │ │ └── RenameItem.ps1
│ │ │ │ ├── ReentrantConversion.Tests.ps1
│ │ │ │ ├── StlTypeConversion.Tests.ps1
│ │ │ │ ├── TemplateMatching.Tests.ps1
│ │ │ │ ├── TrickySymbolValueConversions.Tests.ps1
│ │ │ │ ├── ValueConverterQueries.Tests.ps1
│ │ │ │ ├── VariantConversion.Tests.ps1
│ │ │ │ └── WriteMem.Tests.ps1
│ │ │ ├── v2Lib.pdb
│ │ │ └── v4Lib.pdb
│ │ ├── Debugger/
│ │ │ ├── DbgEngWrapper.dll.metagen
│ │ │ ├── DbgEngWrapper.pdb
│ │ │ ├── DbgNativeUtil.iobj
│ │ │ ├── DbgNativeUtil.ipdb
│ │ │ ├── DbgNativeUtil.pdb
│ │ │ ├── DbgProvider.pdb
│ │ │ ├── Debugger.ArgumentCompleters.ps1
│ │ │ ├── Debugger.ArgumentCompleters.shared.ps1
│ │ │ ├── Debugger.Converters.COM.ps1
│ │ │ ├── Debugger.Converters.NT.ps1
│ │ │ ├── Debugger.Converters.WinRT.ps1
│ │ │ ├── Debugger.Converters.stl.ps1
│ │ │ ├── Debugger.Converters.win32.ps1
│ │ │ ├── Debugger.Converters.wrl.ps1
│ │ │ ├── Debugger.Converters.xaml.ps1
│ │ │ ├── Debugger.DebuggeeTypes.NT.psfmt
│ │ │ ├── Debugger.DebuggeeTypes.Win32.psfmt
│ │ │ ├── Debugger.DebuggeeTypes.atl.psfmt
│ │ │ ├── Debugger.DebuggeeTypes.clr.psfmt
│ │ │ ├── Debugger.DebuggeeTypes.psfmt
│ │ │ ├── Debugger.DebuggeeTypes.wrl.psfmt
│ │ │ ├── Debugger.DebuggeeTypes.xaml.psfmt
│ │ │ ├── Debugger.Format.Color.ps1xml
│ │ │ ├── Debugger.Format.ps1xml
│ │ │ ├── Debugger.Formatting.psm1
│ │ │ ├── Debugger.psd1
│ │ │ ├── Debugger.psfmt
│ │ │ ├── Debugger.psm1
│ │ │ ├── FmtUtils.ps1
│ │ │ ├── GetPsContextFunc.ps1
│ │ │ ├── KernelMode.ps1
│ │ │ ├── Microsoft.Diagnostics.Runtime.pdb
│ │ │ ├── Microsoft.Diagnostics.Runtime.xml
│ │ │ ├── OtherUtils.ps1
│ │ │ ├── Types.ps1xml
│ │ │ └── en-us/
│ │ │ ├── DbgProvider.dll-Help.xml
│ │ │ ├── about_Color.help.txt
│ │ │ ├── about_CustomFormatting.help.txt
│ │ │ ├── about_CustomSymbolValueConversion.help.txt
│ │ │ ├── about_DbgShell.help.txt
│ │ │ ├── about_DbgShell_GettingStarted.help.txt
│ │ │ ├── about_DerivedTypeDetection.help.txt
│ │ │ ├── about_HowTo_Write_a_Symbol_Value_Converter.help.txt
│ │ │ └── about_MemoryCommands.help.txt
│ │ ├── TypeInfoDebugging/
│ │ │ └── TypeInfoDebugging.psm1
│ │ └── doc/
│ │ ├── Color.md
│ │ ├── CustomFormattingEngine.md
│ │ ├── DbgEngWrapper.md
│ │ ├── DerivedTypeDetection.md
│ │ ├── GettingStarted.md
│ │ └── SymbolValueConversion.md
│ └── x86/
│ ├── DbgShell.exe.config
│ ├── DbgShell.pdb
│ ├── DbgShellExt.iobj
│ ├── DbgShellExt.ipdb
│ ├── DbgShellExt.pdb
│ ├── DbgShellTest/
│ │ ├── CoCreateShim.iobj
│ │ ├── CoCreateShim.ipdb
│ │ ├── CoCreateShim.pdb
│ │ ├── DbgShellTest.psd1
│ │ ├── DbgShellTest.psm1
│ │ ├── Pester/
│ │ │ ├── CHANGELOG.md
│ │ │ ├── Functions/
│ │ │ │ ├── Assertions/
│ │ │ │ │ ├── Be.Tests.ps1
│ │ │ │ │ ├── Be.ps1
│ │ │ │ │ ├── BeGreaterThan.Tests.ps1
│ │ │ │ │ ├── BeGreaterThan.ps1
│ │ │ │ │ ├── BeLessThan.Tests.ps1
│ │ │ │ │ ├── BeLessThan.ps1
│ │ │ │ │ ├── BeNullOrEmpty.Tests.ps1
│ │ │ │ │ ├── BeNullOrEmpty.ps1
│ │ │ │ │ ├── BeOfType.Tests.ps1
│ │ │ │ │ ├── BeOfType.ps1
│ │ │ │ │ ├── Contain.Tests.ps1
│ │ │ │ │ ├── Contain.ps1
│ │ │ │ │ ├── ContainExactly.Tests.ps1
│ │ │ │ │ ├── ContainExactly.ps1
│ │ │ │ │ ├── Exist.Tests.ps1
│ │ │ │ │ ├── Exist.ps1
│ │ │ │ │ ├── Match.Tests.ps1
│ │ │ │ │ ├── Match.ps1
│ │ │ │ │ ├── MatchExactly.Tests.ps1
│ │ │ │ │ ├── MatchExactly.ps1
│ │ │ │ │ ├── PesterThrow.Tests.ps1
│ │ │ │ │ ├── PesterThrow.ps1
│ │ │ │ │ ├── Set-TestInconclusive.ps1
│ │ │ │ │ ├── Should.Tests.ps1
│ │ │ │ │ ├── Should.ps1
│ │ │ │ │ └── Test-Assertion.ps1
│ │ │ │ ├── BreakAndContinue.Tests.ps1
│ │ │ │ ├── Context.Tests.ps1
│ │ │ │ ├── Context.ps1
│ │ │ │ ├── Coverage.Tests.ps1
│ │ │ │ ├── Coverage.ps1
│ │ │ │ ├── Describe.Tests.ps1
│ │ │ │ ├── Describe.ps1
│ │ │ │ ├── GlobalMock-A.Tests.ps1
│ │ │ │ ├── GlobalMock-B.Tests.ps1
│ │ │ │ ├── In.Tests.ps1
│ │ │ │ ├── In.ps1
│ │ │ │ ├── InModuleScope.Tests.ps1
│ │ │ │ ├── InModuleScope.ps1
│ │ │ │ ├── It.Tests.ps1
│ │ │ │ ├── It.ps1
│ │ │ │ ├── Mock.Tests.ps1
│ │ │ │ ├── Mock.ps1
│ │ │ │ ├── New-Fixture.Tests.ps1
│ │ │ │ ├── New-Fixture.ps1
│ │ │ │ ├── PesterState.Tests.ps1
│ │ │ │ ├── PesterState.ps1
│ │ │ │ ├── SetupTeardown.Tests.ps1
│ │ │ │ ├── SetupTeardown.ps1
│ │ │ │ ├── TestDrive.Tests.ps1
│ │ │ │ ├── TestDrive.ps1
│ │ │ │ ├── TestResults.Tests.ps1
│ │ │ │ ├── TestResults.ps1
│ │ │ │ └── TestsRunningInCleanRunspace.Tests.ps1
│ │ │ ├── LICENSE
│ │ │ ├── Pester.Tests.ps1
│ │ │ ├── Pester.psd1
│ │ │ ├── Pester.psm1
│ │ │ ├── README.md
│ │ │ ├── Snippets/
│ │ │ │ ├── Context.snippets.ps1xml
│ │ │ │ ├── Describe.snippets.ps1xml
│ │ │ │ ├── It.snippets.ps1xml
│ │ │ │ ├── ShouldBe.snippets.ps1xml
│ │ │ │ ├── ShouldBeGreaterThan.snippets.ps1xml
│ │ │ │ ├── ShouldBeLessThan.snippets.ps1xml
│ │ │ │ ├── ShouldBeNullOrEmpty.snippets.ps1xml
│ │ │ │ ├── ShouldContain.snippets.ps1xml
│ │ │ │ ├── ShouldExist.snippets.ps1xml
│ │ │ │ ├── ShouldMatch.snippets.ps1xml
│ │ │ │ ├── ShouldNotBe.snippets.ps1xml
│ │ │ │ ├── ShouldNotBeNullOrEmpty.snippets.ps1xml
│ │ │ │ ├── ShouldNotContain.snippets.ps1xml
│ │ │ │ ├── ShouldNotExist.snippets.ps1xml
│ │ │ │ ├── ShouldNotMatch.snippets.ps1xml
│ │ │ │ ├── ShouldNotThrow.snippets.ps1xml
│ │ │ │ └── ShouldThrow.snippets.ps1xml
│ │ │ ├── en-US/
│ │ │ │ ├── about_BeforeEach_AfterEach.help.txt
│ │ │ │ ├── about_Mocking.help.txt
│ │ │ │ ├── about_Pester.help.txt
│ │ │ │ ├── about_TestDrive.help.txt
│ │ │ │ └── about_should.help.txt
│ │ │ └── nunit_schema_2.5.xsd
│ │ ├── TestManagedCommon.pdb
│ │ ├── TestManagedConsoleApp.exe.config
│ │ ├── TestManagedConsoleApp.pdb
│ │ ├── TestNativeConsoleApp.exp
│ │ ├── TestNativeConsoleApp.iobj
│ │ ├── TestNativeConsoleApp.ipdb
│ │ ├── TestNativeConsoleApp.lib
│ │ ├── TestNativeConsoleApp.pdb
│ │ ├── Tests/
│ │ │ ├── Disasm.Tests.ps1
│ │ │ ├── Dumps.Tests.ps1
│ │ │ ├── Gu.Tests.ps1
│ │ │ ├── Kill.Tests.ps1
│ │ │ ├── MultiProcDetachAttach.Tests.ps1
│ │ │ ├── NamespaceTests/
│ │ │ │ ├── ContentTests.ps1
│ │ │ │ ├── CopyItem.ps1
│ │ │ │ ├── DriveTests.ps1
│ │ │ │ ├── Globbing.ps1
│ │ │ │ ├── MoveItem.ps1
│ │ │ │ ├── ProviderTests.metadata
│ │ │ │ └── RenameItem.ps1
│ │ │ ├── ReentrantConversion.Tests.ps1
│ │ │ ├── StlTypeConversion.Tests.ps1
│ │ │ ├── TemplateMatching.Tests.ps1
│ │ │ ├── TrickySymbolValueConversions.Tests.ps1
│ │ │ ├── ValueConverterQueries.Tests.ps1
│ │ │ ├── VariantConversion.Tests.ps1
│ │ │ └── WriteMem.Tests.ps1
│ │ ├── v2Lib.pdb
│ │ └── v4Lib.pdb
│ ├── Debugger/
│ │ ├── DbgEngWrapper.dll.metagen
│ │ ├── DbgEngWrapper.pdb
│ │ ├── DbgNativeUtil.iobj
│ │ ├── DbgNativeUtil.ipdb
│ │ ├── DbgNativeUtil.pdb
│ │ ├── DbgProvider.pdb
│ │ ├── Debugger.ArgumentCompleters.ps1
│ │ ├── Debugger.ArgumentCompleters.shared.ps1
│ │ ├── Debugger.Converters.COM.ps1
│ │ ├── Debugger.Converters.NT.ps1
│ │ ├── Debugger.Converters.WinRT.ps1
│ │ ├── Debugger.Converters.stl.ps1
│ │ ├── Debugger.Converters.win32.ps1
│ │ ├── Debugger.Converters.wrl.ps1
│ │ ├── Debugger.Converters.xaml.ps1
│ │ ├── Debugger.DebuggeeTypes.NT.psfmt
│ │ ├── Debugger.DebuggeeTypes.Win32.psfmt
│ │ ├── Debugger.DebuggeeTypes.atl.psfmt
│ │ ├── Debugger.DebuggeeTypes.clr.psfmt
│ │ ├── Debugger.DebuggeeTypes.psfmt
│ │ ├── Debugger.DebuggeeTypes.wrl.psfmt
│ │ ├── Debugger.DebuggeeTypes.xaml.psfmt
│ │ ├── Debugger.Format.Color.ps1xml
│ │ ├── Debugger.Format.ps1xml
│ │ ├── Debugger.Formatting.psm1
│ │ ├── Debugger.psd1
│ │ ├── Debugger.psfmt
│ │ ├── Debugger.psm1
│ │ ├── FmtUtils.ps1
│ │ ├── GetPsContextFunc.ps1
│ │ ├── KernelMode.ps1
│ │ ├── Microsoft.Diagnostics.Runtime.pdb
│ │ ├── Microsoft.Diagnostics.Runtime.xml
│ │ ├── OtherUtils.ps1
│ │ ├── Types.ps1xml
│ │ └── en-us/
│ │ ├── DbgProvider.dll-Help.xml
│ │ ├── about_Color.help.txt
│ │ ├── about_CustomFormatting.help.txt
│ │ ├── about_CustomSymbolValueConversion.help.txt
│ │ ├── about_DbgShell.help.txt
│ │ ├── about_DbgShell_GettingStarted.help.txt
│ │ ├── about_DerivedTypeDetection.help.txt
│ │ ├── about_HowTo_Write_a_Symbol_Value_Converter.help.txt
│ │ └── about_MemoryCommands.help.txt
│ ├── TypeInfoDebugging/
│ │ └── TypeInfoDebugging.psm1
│ └── doc/
│ ├── Color.md
│ ├── CustomFormattingEngine.md
│ ├── DbgEngWrapper.md
│ ├── DerivedTypeDetection.md
│ ├── GettingStarted.md
│ └── SymbolValueConversion.md
└── Readme.md
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitattributes
================================================
# Auto detect text files and perform LF normalization
* text=auto
# Custom for Visual Studio
*.cs diff=csharp
# Standard to msysgit
*.doc diff=astextplain
*.DOC diff=astextplain
*.docx diff=astextplain
*.DOCX diff=astextplain
*.dot diff=astextplain
*.DOT diff=astextplain
*.pdf diff=astextplain
*.PDF diff=astextplain
*.rtf diff=astextplain
*.RTF diff=astextplain
================================================
FILE: .gitignore
================================================
# Windows image file caches
Thumbs.db
ehthumbs.db
# Folder config file
Desktop.ini
# Recycle Bin used on file shares
$RECYCLE.BIN/
# Windows Installer files
*.cab
*.msi
*.msm
*.msp
# Windows shortcuts
*.lnk
# =========================
# Operating System Files
# =========================
# OSX
# =========================
.DS_Store
.AppleDouble
.LSOverride
# Thumbnails
._*
# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
================================================
FILE: DbgShell/x64/DbgShell.exe.config
================================================
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6"/>
</startup>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<probing privatePath="Debugger"/>
</assemblyBinding>
</runtime>
</configuration>
================================================
FILE: DbgShell/x64/DbgShellTest/DbgShellTest.psd1
================================================
#
# Module manifest for module 'DbgShellTest'
#
@{
# Script module or binary module file associated with this manifest
RootModule = "filesystem::$PSScriptRoot\TestManagedCommon.dll"
# Version number of this module.
ModuleVersion = '1.0'
# ID used to uniquely identify this module
GUID = '8919DA18-FF4F-49DD-BE65-40DC8A3D0D0C'
# Author of this module
Author = 'Microsoft Corporation'
# Company or vendor of this module
CompanyName = 'Microsoft Corporation'
# Copyright statement for this module
Copyright = '(c) Microsoft Corporation. All rights reserved.'
# Minimum version of the Windows PowerShell engine required by this module
PowerShellVersion = '3.0'
# Name of the Windows PowerShell host required by this module
PowerShellHostName = ''
# Minimum version of the Windows PowerShell host required by this module
PowerShellHostVersion = ''
# Minimum version of the .NET Framework required by this module
DotNetFrameworkVersion = '4.0'
# Minimum version of the common language runtime (CLR) required by this module
CLRVersion = '4.0'
# Processor architecture (None, X86, Amd64, IA64) required by this module
ProcessorArchitecture = ''
# Modules that must be imported into the global environment prior to importing this module
RequiredModules = @( "filesystem::$PSScriptRoot\Pester\Pester.psd1" )
# Assemblies that must be loaded prior to importing this module
RequiredAssemblies = @()
# Script files (.ps1) that are run in the caller's environment prior to importing this module
ScriptsToProcess = @()
# Type files (.ps1xml) to be loaded when importing this module
TypesToProcess = @()
# Format files (.ps1xml) to be loaded when importing this module
FormatsToProcess = @()
# Modules to import as nested modules of the module specified in ModuleToProcess
NestedModules = @( "filesystem::$PSScriptRoot\DbgShellTest.psm1" )
# Functions to export from this module
FunctionsToExport = @( 'New-TestApp',
'ntna',
'ntma',
'DoFullTestPass',
'Get-DbgTypeCacheStats',
'PostTestCheckAndResetCacheStats' )
# Cmdlets to export from this module
CmdletsToExport = '*'
# Variables to export from this module
VariablesToExport = '*'
# Aliases to export from this module
AliasesToExport = '*'
# List of all modules packaged with this module
ModuleList = @()
# List of all files packaged with this module
FileList = @()
# Private data to pass to the module specified in ModuleToProcess
PrivateData = ''
# HelpInfo URI of this module
#HelpInfoURI = 'http://go.microsoft.com/fwlink/?LinkId=216168'
}
================================================
FILE: DbgShell/x64/DbgShellTest/DbgShellTest.psm1
================================================
Set-StrictMode -Version Latest
[void] (New-PSDrive Tests FileSystem "$PSScriptRoot\Tests" -Scope Global)
$script:dumpsRelativePath = '..\..\..\..\Dumps'
if( [System.IO.Directory]::Exists( "$PSScriptRoot\$dumpsRelativePath" ) )
{
[void] (New-PSDrive Dumps FileSystem "$PSScriptRoot\$dumpsRelativePath" -Scope Global)
}
$MyInvocation.MyCommand.ScriptBlock.Module.OnRemove =
{
Remove-PSDrive -Name 'Tests' -Force
$dd = Get-PSDrive 'Dumps*' # use a wildcard because I don't want an error if it's not there.
foreach( $d in $dd )
{
if( $d.Name -eq 'Dumps' )
{
$d | Remove-PSDrive -Force
break
}
}
} # end OnRemove handler
Write-Host ''
Write-Host "Tests are located under the Tests:\ drive. Type something like ""Invoke-Pester Tests:\*.ps1"" to run them. Or use DoFullTestPass to run them for all combinations of the optional test inputs (path bugginess style and provider-/drive-qualified working directory)."
Write-Host ''
Set-Alias Run-Test Invoke-Pester
function script:Find-TestApp
{
[CmdletBinding()]
param( [Parameter( Mandatory = $true, Position = 0 )]
[ValidateNotNullOrEmpty()]
[string] $TestApp,
[Parameter( Mandatory = $false )]
[ValidateSet( 'x86', 'x64', 'matching', 'cross' )]
[string] $Platform = 'matching'
)
begin { }
end { }
process
{
try
{
[string] $path = $null
if( $Platform -eq 'matching' )
{
$path = 'bin:\DbgShellTest\' + $TestApp + '.exe'
$path = $executionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath( $path )
}
else
{
if( $Platform -eq 'cross' ) {
if( [System.Environment]::Is64BitProcess ) {
$Platform = 'x86'
} else {
$Platform = 'x64'
}
}
$platformRoot = [System.IO.Path]::GetDirectoryName( (Get-PSDrive 'bin').Root )
$path = [System.IO.Path]::Combine( $platformRoot, $Platform, 'DbgShellTest', $TestApp )
$path = $path + '.exe'
}
if( ![System.IO.File]::Exists( $path ) )
{
throw "There is no '$TestApp' test app. (at least not yet...) Path tried was: $path"
}
return $path
}
finally { }
} # end process
} # end function Find-TestApp
function script:Find-Windbg
{
[CmdletBinding()]
param( [Parameter( Mandatory = $true, Position = 0 )]
[ValidateNotNullOrEmpty()]
[string] $which
)
begin { }
end { }
process
{
try
{
[string] $dir = Find-WindbgDir
if( !$dir )
{
throw "Can't find windbg dir."
}
[string] $path = Join-Path $dir $which
if( ![System.IO.File]::Exists( $path ) )
{
throw "Can't find '$path'. You may need to modify this function in DbgShellTest.psm1 (or make sure that windbg is installed in a common location)."
}
return $path
}
finally { }
} # end process
} # end function Find-Windbg
<#
.Synopsis
Starts a new process for debugging, either launching under the debugger, or launching it then attaching.
#>
function New-TestApp
{
[CmdletBinding()]
param( [Parameter( Mandatory = $true, Position = 0 )]
[ValidateNotNullOrEmpty()]
[ValidateSet( 'TestManagedConsoleApp', 'TestNativeConsoleApp' )] # TODO: implement other test apps!
[string] $TestApp,
[Parameter( Mandatory = $false )]
[ValidateSet( 'x86', 'x64', 'matching', 'cross' )]
[string] $Platform = 'matching',
[Parameter( Mandatory = $false, Position = 3 )]
[string] $Arguments,
[Parameter( Mandatory = $false, Position = 4 )]
[ValidateNotNullOrEmpty()]
[string] $TargetName = "testApp",
[Parameter( Mandatory = $false )]
[switch] $Attach,
[Parameter( Mandatory = $false )]
[Alias( 'gi' )]
[switch] $SkipInitialBreakpoint,
[Parameter( Mandatory = $false )]
[Alias( 'gf' )]
[switch] $SkipFinalBreakpoint,
[Parameter( Mandatory = $false )]
[switch] $UseWindbgInstead,
# Useful from test scripts, so that they aren' popping up windows all over.
[Parameter( Mandatory = $false )]
[switch] $HiddenTargetWindow
)
begin { }
end { }
process
{
if( $UseWindbgInstead -and $PSBoundParameters.ContainsKey( 'TargetName' ) )
{
Write-Warning "The -TargetName parameter doesn't make sense with -UseWindbgInstead."
}
if( (Test-Path "Dbg:\$TargetName") -and !$UseWindbgInstead )
{
throw "The name '$TargetName' is already in use; please use a different name."
}
[string] $path = Find-TestApp $TestApp -Platform $Platform
$testAppReadyEvent = New-InheritableEvent
$pauseEvent = New-InheritableEvent
try
{
if( $Attach )
{
if( $SkipInitialBreakpoint -and !$UseWindbgInstead )
{
Write-Warning "The -Attach option coordinates with the target test app, in order to guarantee that we always get attached at a consistent, deterministic spot (because this command is for testing). By using the -SkipInitialBreakpoint along with the -Attach option, this command will not get a chance to set the `"you may now continue execution`" event until the app breaks for some reason (for instance, you can cause this by typing CTRL+C in the target test app's window)."
# TODO: Perhaps instead we could not really skip the initial
# breakpoint, but instead issue a Resume-DbgProcess ("g") as soon as
# we hit it.
}
$arglist = ("SetEvent $($testAppReadyEvent.SafeWaitHandle.DangerousGetHandle().ToString()) ; WaitEvent $($pauseEvent.SafeWaitHandle.DangerousGetHandle().ToString())" + " ; " + $Arguments)
# The -UseNewEnvironment is important; it causes Start-Process
# to not use ShellExecute. (We don't want to use ShellExecute
# because we need the child proc to inherit the handles to the
# synchronization events.)
$startProcArgs = @{ 'FilePath' = $path
'ArgumentList' = $arglist
'UseNewEnvironment' = $true
'PassThru' = $true
}
if( $HiddenTargetWindow -and !(Test-Path Variable:\__globalForceShowTestWindows) )
{
$startProcArgs[ 'WindowStyle' ] = 'Hidden'
}
$proc = Start-Process @startProcArgs
[bool] $ready = $false
while( !$proc.HasExited -and !$ready )
{
# It could crash before we get attached. We poll for that so we won't
# get hung if that happens.
$ready = $testAppReadyEvent.WaitOne( 5000 )
}
if( $proc.HasExited )
{
Assert (!$ready)
Write-Error "Hmmm... the test process died before we could attach (pid was $($proc.Id))."
}
else
{
# Start-Sleep -Milli 500
if( $UseWindbgInstead ) {
[object[]] $flags = @()
if( $SkipInitialBreakpoint ) { $flags += '-g' }
if( $SkipFinalBreakpoint ) { $flags += '-G' }
& (Find-Windbg 'windbg.exe') @flags -p $proc.Id
# Need to wait for windbg to get attached. Hopefully this is long
# enough.
Write-Host "Waiting for windbg to get attached..." -Fore Cyan
Start-Sleep -Milli 5000
} else {
$proc | Connect-Process -TargetName $TargetName `
-SkipInitialBreakpoint:$SkipInitialBreakpoint `
-SkipFinalBreakpoint:$SkipFinalBreakpoint
}
[void] $pauseEvent.Set()
}
}
else # !$Attach
{
if( $UseWindbgInstead ) {
if( $HiddenTargetWindow )
{
Write-Warning 'The -HiddenTargetWindow is ignored when launching windbg.'
}
[object[]] $flags = @()
if( $SkipInitialBreakpoint ) { $flags += '-g' }
if( $SkipFinalBreakpoint ) { $flags += '-G' }
$arglist = "$flags $path $Arguments"
Start-Process (Find-Windbg 'windbg.exe') -ArgumentList $arglist -UseNewEnvironment
} else {
$startDbgProcOptions = @{ 'FilePath' = $path
'TargetName' = $TargetName
'SkipInitialBreakpoint' = $SkipInitialBreakpoint
'SkipFinalBreakpoint' = $SkipFinalBreakpoint
'ArgumentList' = $Arguments
}
if( $HiddenTargetWindow )
{
$startDbgProcOptions[ 'ConsoleOption' ] = 'NoConsole'
}
Start-DbgProcess @startDbgProcOptions
}
}
}
finally
{
$testAppReadyEvent.Dispose()
$pauseEvent.Dispose()
}
}
} # end function New-TestApp
<#
.Synopsis
Convenient shortcut to attach to a new TestNativeConsoleApp.exe process.
#>
function ntna
{
[CmdletBinding()]
param( [Parameter( Mandatory = $false, Position = 0 )]
[string] $Arguments,
[Parameter( Mandatory = $false, Position = 1 )]
[ValidateNotNullOrEmpty()]
[string] $TargetName = "testApp"
)
begin { }
end { }
process
{
try
{
New-TestApp TestNativeConsoleApp -Attach -TargetName $TargetName -Arguments $Arguments
}
finally { }
}
} # end function ntna
<#
.Synopsis
Convenient shortcut to attach to a new TestManagedConsoleApp.exe process.
#>
function ntma
{
[CmdletBinding()]
param( [Parameter( Mandatory = $false, Position = 0 )]
[string] $Arguments,
[Parameter( Mandatory = $false, Position = 1 )]
[ValidateNotNullOrEmpty()]
[string] $TargetName = "testApp"
)
begin { }
end { }
process
{
try
{
New-TestApp TestManagedConsoleApp -Attach -TargetName $TargetName -Arguments $Arguments
}
finally { }
}
} # end function ntma
<#
.Synopsis
Runs all the tests (Tests:\*.ps1) multiple times for all combinations of PathBugginessStyle and using a provider-qualified working directory or not.
function DoFullTestPass()
{
[string] $testName = "Full regression test pass"
[bool] $alreadyRanGlobbing = $false
Import-Module TE.PowerShell
# Fortunately, the WEX logging state is re-entrant/refcounted.
[WEX.Logging.Interop.LogController]::InitializeLogging()
Log-StartGroup $testName
foreach( $pbs in @( [MS.Dbg.PathBugginessStyle]::RegistryProvider, [MS.Dbg.PathBugginessStyle]::CertificateProvider ) )
{
foreach( $upqwd in @( $false, $true ) )
{
$testProps = Get-TestProperties
$testProps[ "PathBugginessStyle" ] = $pbs
$testProps[ "UseProviderQualifiedWorkingDirectory" ] = $upqwd
if( $alreadyRanGlobbing )
{
Run-Test Tests:\*.ps1 -Exclude Tests:\Globbing.ps1
}
else
{
Run-Test Tests:\*.ps1
$alreadyRanGlobbing = $true
}
}
}
Log-EndGroup $testName
[WEX.Logging.Interop.LogController]::FinalizeLogging()
} # end DoFullTestPass
#>
function Get-DbgTypeCacheStats
{
[CmdletBinding()]
param()
begin { }
end { }
process
{
try
{
$hits = [MS.Dbg.DbgTypeInfo]::CacheHits
$misses = [MS.Dbg.DbgTypeInfo]::CacheMisses
if( $misses -gt 0 )
{
$hitPercent = [int] (($hits / $misses) * 100)
}
else
{
$hitPercent = 'NaN'
}
return [PSCustomObject] @{ 'Hits' = $hits ;
'Misses' = $misses ;
'HitPercent' = $hitPercent }
}
finally { }
}
}
function PostTestCheckAndResetCacheStats
{
[CmdletBinding()]
param()
begin { }
end { }
process
{
try
{
$cs = Get-DbgTypeCacheStats
Write-Host "DbgTypeInfo cache stats: $($cs.Hits) hits, $($cs.Misses) misses ($($cs.HitPercent)%)." -Fore Cyan
if( 0 -ne ([MS.Dbg.DbgTypeInfo]::GetCacheSize()) )
{
Write-Warning "Cache size should currently be zero (because we should not be attached to anything)."
}
[MS.Dbg.DbgTypeInfo]::ResetCacheStatistics()
}
finally { }
}
}
================================================
FILE: DbgShell/x64/DbgShellTest/Pester/CHANGELOG.md
================================================
## 3.4.6 (January 13, 2017)
- Fix bug with -Show parameter on PowerShell v4 and older [GH-677]
- Add commas to test run summary [GH-676]
## 3.4.5 (January 12, 2017)
- Add -Show parameter to filter on-screen output [GH-647]
- Add BeIn assertion to assert an item is part of an array [GH-646]
- Fix test drive to work on PSCore [GH-643]
## 3.4.4 (November 12, 2016)
- Add New-MockObject function that creates empty objects for almost any .NET class [GH-635]
## 3.4.3 (August 25, 2016)
- Fixed mocking for certain cmdlets containing dynamic parameters in PowerShell 5.1. [GH-599]
## 3.4.2 (August 2, 2016)
- Bug fix when multiple cmdlets with the same name exist in PowerShell 5.1. [GH-588]
## 3.4.1 (July 22, 2016)
- Updated code to use Get-CimInstance if possible, then Get-WmiObject, for Nano compatibility. [GH-484]
- Fixed failure message output of Should BeLike / BeLikeExactly. [GH-497]
- Added some missing information to about_Should help. [GH-519]
- Made -OutputFormat parameter optional, defaulting to NUnitXml. [GH-503]
- Fix error message of Should Throw when null input is provided [GH-521]
- Fix mocking bug on functions that contain certain parameter names (Metadata, etc). [GH-583]
## 3.4.0 (February 29, 2016)
- Bug fix for PSv2 when no matching scripts are found by Invoke-Pester. [GH-441]
- Added "Should BeLike" assertion. [GH-456]
- Discarded unwanted pipeline output from BeforeEach / AfterEach / BeforeAll / AfterAll. [GH-468]
- Allowed closures to be used as mocks. [GH-465]
- Fixed invalid NUnit XML output if test script had a syntax error. [GH-467]
- Fix for mocking advanced functions that define a parameter named 'Args'. [GH-471]
- Fixed bug when trying to mock a command with a weird name containing a single quotation mark. [GH-474]
- Fixed bug for mocking Cmdlets that do not contain any positional parameters. [GH-477]
- Fixed bug when calling a mocked command from inside the mock. [GH-478]
- Added PesterOption parameter, and a switch to tweak console output for better VSCode extension functionality. [GH-479]
## 3.3.14 (December 16, 2015)
- Fixed Coverage analysis output, which broke in 3.3.12. [GH-440]
## 3.3.13 (December 10, 2015)
- Fixed a bug where mocking Get-Command would result in infinite recursion. [GH-437]
## 3.3.12 (December 8, 2015)
- Fixed a bug with mocking dynamic parameters on latest Windows 10 / PSv5 builds. [GH-419]
- Fix for NUnit XML export on .NET core. [GH-420]
- Added Set-TestInconclusive command. [GH-421]
- Mocking improvements for calling original commands with begin/process/end blocks. [GH-422]
- Case insensitive replacement of Test in help [GH-428]
- Improve stack trace and exception console output [GH-426]
- Added support for intercepting module-qualified calls to a mocked command. [GH-432]
- Improved Assert-MockCalled to allow it to be passed an alias as the -CommandName.
## 3.3.11 (September 8, 2015)
- Fixed a bug where mocking New-Object would cause a stack overflow. [GH-405]
## 3.3.10 (August 14, 2015)
- Fully qualified calls to Get-Content within Mocking code, to avoid triggering client's mocked versions of that command. [GH-362]
- Fixed a scoping error when calling the original command if no parameter filters match the call. [GH-362]
- Added Ignore alias for -Skip on the It command, and updated NUnit output to flag these tests as Ignored instead of Skipped, for better integration with things like TeamCity. [GH-368]
- Added support for Unicode to Should Contain. [GH-378]
- Added support for side-by-side installations to chocolateyInstall.ps1. [GH-401]
## 3.3.9 (May 23, 2015)
- Fixed Describe's handling of TestName filter when multiple strings are passed to Invoke-Pester's -TestName parameter.
- Failing BeforeEach or AfterEach will fail the test [GH-326]
- Added BeOfType operator to the Should command. [GH-327]
- Fixed BeforeEach / etc parsing in PSv3+ so breakpoints and automatic variables ($PSCommandPath, etc) will work properly. [GH-333]
- Fixed bug in 'Should Be' when comparing strings, and null or empty strings are piped in to the Should command. [GH-333]
- Added some calls to Write-Progress in the It command. [GH-322]
- Bug fix when mocking functions that are in the global scope; the original functions were being lost when the Describe block ended. [GH-323]
- Improved failed assertion output from Assert-MockCalled; now behaves more like Should. [GH-324]
- Added -ExclusiveFilter parameter to Assert-MockCalled. Works like -ParameterFilter, except there also must not be any calls to the mocked command which do _not_ match the filter.
- Added the "bin" folder to the PATH environment variable when installing from Chocolatey. Also removed the hard-coded -OutputXml and -Strict parameters from this file; only -EnableExit is always used from the bat file now. [GH-281]
- PassThru object (when used in conjunction with -CodeCoverage) now includes information about Hit commands in addition to Missed commands. [GH-341]
- Improvements to support for mocking advanced functions with dynamic parameters. [GH-346]
- Fix for PowerShell v2 bug when mocking commands that have an -ArgumentList parameter with validation attributes. [GH-354]
- Fixed stack trace output when the call to Should is in a file other than the file that contains the It block. [GH-358]
## 3.3.8 (April 15, 2015)
- Further mocking fixes around the use of $ExecutionContext in client scope. [GH-307]
## 3.3.7 (April 15, 2015)
- Added workaround for GetDynamicParameters() bug that was affecting mocks on the ActiveDirectory module in Windows 7. [GH-295]
- Revised Mocking code to avoid potential bugs when functions define parameters named $ExecutionContext or $MyInvocation. [GH-304]
- Mocked functions no longer call Get-MockDynamicParameters if the original function had no dynamicparam block. [GH-306]
## 3.3.6 (March 19, 2015)
- Fix for mocking aliases for commands that are in scopes that Pester can't normally see. [GH-267]
- Added line information to test failure output in Should assertion failures. [GH-266]
- Added support for passing named parameters or positional arguments to test scripts, and for calling test scripts that are not named *.Tests.ps1. [GH-272]
- Made Pester compliant with StrictMode. [GH-274]
- Improved error message when InModuleScope finds multiple modules loaded with the same name. [GH-276]
- Updated build script to allow for custom root folder in the nupkg. [GH-254]
- Improved error messages for InModuleScope and Mock -ModuleName when multiple modules with the same name are loaded. Also enabled these commands to work if only one of the loaded modules is a Script module. [GH-278]
- Added some graceful handling of test code that has a misplaced break or continue statement. [GH-290]
## 3.3.5 (January 23, 2015)
- Updated tests to allow PRs to be automatically tested, with status updates to GitHub, by our CI server.
- Added Snippets directory to the nuget packages, and updated code so the module won't fail to import if Snippets are missing.
## 3.3.4 (January 22, 2015)
- No changes; publishing again to fix broken PowerShellGet upload.
## 3.3.2 (January 19, 2015)
- Performance Improvements
## 3.3.1 (January 12, 2015)
- Import ISESteroids snippets on load
- Updated Code Coverage analysis to be compatible with the PowerShell 5.0 AST when analyzing DSC configurations. [GH-249]
## 3.3.0 (January 10, 2015)
- Validate manifest version, changelog version and tag version
- Added BeforeAll and AfterAll commands
- Updated code to take advantage of -ErrorAction Ignore in PowerShell v3+.
- Add ISESteroids snippets but do not import them
## 3.2.0 (December 3, 2014)
- Added BeGreaterThan and BeLessThan assertions to Should.
- Add -Quiet parameter for Invoke-Pester that disables the output written to screen by Write-Host [GH-223]
- Fix Error output for TestDrive [GH-232]
- Add ExcludeTagFilter parameter [GH-234]
- Add different color schemes for dark and light backgrounds
## 3.1.1 (October 29, 2014)
- Fix Skipped and Pending
- Fix output format on non-US systems
## 3.1 (October 23, 2014)
- Fix mocking of Get-ItemProperty
- Fix mocking commands with parameters named $FunctionName, $ModuleName or $ArgumentList under some circumstances. [GH-215]
- Add Skipped and Pending test results
- Added support for parameterized tests to the It command.
- Deprecated -OutputXml parameter, added -OutputFile and -OutputFormat parameters.
- Added new updated NUnit export format. Original format still available as -OutputFormat LegacyNUnitXml.
- Stopped forcing -ParameterFilter blocks to return explicit booleans, preventing some unnecessary null reference exceptions.
## 3.0.3 (October 12, 2014)
- Can be installed from PowerShellGet
- Version updated to solve issue on PowerShellGet
## 3.0.2 (September 8, 2014)
- Coverage Analysis now ignores closing conditions of do/while and do/until loops, which were giving false failures. [GH-200]
- Calls to Functions and Cmdlets with dynamic parameters can now be mocked. [GH-203]
- Mock now avoids assigning strings to items in the Function provider, bypassing a PowerShell 3.0 bug.
- Bug fix when mocking executables or functions with no param block. [GH-209]
- Replace the nuget.exe with version 2.8.2 and set the Team City server to use the same version.
## 3.0.1.1 (August 28, 2014)
- Fixing wrong version in the manifest, publishing new version so I can update it on Nuget/Chocolatey
## 3.0.1 (August 28, 2014)
- Fix nuspec specification to build the 3.0.0 package correctly
- Add verbose output for Be and BeExactly string comparison [GH-192]
- Fixed NUnit XML output (missing close tag for failure element.) [GH-195]
## 3.0.0 (August 21, 2014)
- Fix code coverage tests so they do not left breakpoints set [GH-149]
- Add better output for hashtables in code coverage [GH-150]
- Fix Invoke-Pester -OutputXml usage of relative paths
- Remove Validate-Xml function
- Remove legacy object adaptations support
- Remove tests testing usage of the global scope
- Add function name to Code coverage output [GH-152]
- Suppress pipeline output in Context / Describe [GH-155]
- Coverage Output Update [GH-156]
- Add initial implementation of BeforeEach / AfterEach [GH-158]
- CodeCoverage of files containing DSC Configurations [GH-163]
- Rolling back some earlier Pester Scope changes [GH-164]
- Legacy expectations cleanup [GH-165]
- Invoke-Pester tests path fix [GH-166]
- Assert-MockCalled default ModuleName fix. [GH-167]
- Output exception source when test fails [GH-147]
- Fix for PesterThrowFailureMessage on PowerShell 2.0. [GH-171]
- Pester.bat no longer enables StrictMode. [GH-172]
- Fixed default behavior of fixture parameter in Describe and Context. [GH-174]
- Syntax errors in test files, as well as terminating errors from Describe or Context blocks are now treated as failed tests. [GH-168]
- Mock lifetime is no longer tied to It blocks. [GH-176]
- Add module manifest
- Added multiple lines to failure messages from Should Be and Should BeExactly. Updated console output code to support blank lines in failure messages and stack traces. [GH-185]
- Fixed stack trace information when test failures come from inside InModuleScope blocks, or from something other than a Should assertion. [GH-183]
- Fixed stack trace information from Describe and Context block errors in PowerShell 2.0. [GH-186]
- Fixed a problem with parameter / argument resolution in mocked cmdlets / advanced functions. [GH-187]
- Improved error reporting when Pester commands are called outside of a Describe block. [GH-188]
- Extensive updates to help files and comment-based help for v3.0 release. [GH-190]
## 3.0.0-beta2 (July 4, 2014)
- Add code coverage [GH-148]
- Fix TestName
- Fix direct execution of tests when the script is dot-sourced to global scope [GH-144]
- Fix mock parameter filter in strict mode [GH-143]
- Fix nUnit schema compatibility
- Fix special characters in nUnit output
## 3.0.0-beta (June 24, 2014)
- Add full support for module mocking
- Isolate Pester internals from tested code [GH-139]
- Tests.ps1 files can be run directly [GH-139]
- Add It scope to TestDrive
- Add It scope to Mock
- Add Scope parameter to Assert-MockCalled
- Measure test time more precisely
## 2.1.0 (June 15, 2014)
- Process It blocks in memory [GH-123]
- Fixed -ExecutionPolicy in pester.bat [GH-130]
- Add support for mocking internal module functions, aliases, exe and filters. [GH-126]
- Fix TestDrive clean up [GH-129]
- Fix ShouldArgs in Strict-Mode [GH-134]
- Fix initialize $PesterException [GH-136]
- Validate Should Assertion methods [GH-135]
- Fix using commands without fully qualified names [GH-137]
- Enable latest strict mode when running Pester tests using Pester.bat
## 2.0.4 (March 9, 2014)
- Fixed issue where TestDrive doesn't work with paths with . characters
[GH-52]
- Fixed issues when mocking Out-File [GH-71]
- Exposing TestDrive with Get-TestDriveItem [GH-70]
- Fixed bug where mocking Remove-Item caused cleanup to break [GH-68]
- Added -Passthru to Setup to obtain file system object references [GH-69]
- Can assert on exception messages from Throw assertions [GH-58]
- Fixed assertions on empty functions [GH-50]
- Fixed New-Fixture so it creates proper syntax in tests [GH-49]
- Fixed assertions on Object arrays [GH-61]
- Fixed issue where curly brace misalignment would cause issues [GH-90]
- Better contrasting output colours [GH-92]
- New-Fixture handles "." properly [GH-86]
- Fixed mix scoping of It and Context [GH-98] and [GH-99]
- Test Drives are randomly generated, which should allow concurrent Pester processes [GH-100] and [GH-94]
- Fixed nUnit test failing on non-US computers [GH-109]
- Add case sensitive Be, Contain and Match assertions [GH-107]
- Fix Pester template self-tests [GH-113]
- Time is output to the XML report [GH-95]
- Internal fixes to remove unnecessary dependencies among functions
- Cleaned up Invoke-Pester interface
- Make output better structured
- Add -PassThru to Invoke-Pester [GH-102], [GH-84] and [GH-46]
- Makes New-Fixture -Path option more resilient [GH-114]
- Make the New-Fixture input accept any path and output objects
- Move New-Fixture to separate script
- Remove Write-UsageForNewFixture
- Fix Should Throw filtering by exception message [GH-125]
## 2.0.3 (Apr 16, 2013)
- Fixed line number reported in pester failure when using new pipelined
should assertions [GH-40]
- Added describe/context scoping for mocks [GH-42]
## 2.0.2 (Feb 28, 2013)
- Fixed exit code bug that was introduced in version 2.0.0
## 2.0.1 (Feb 3, 2013)
- Renamed -EnableLegacyAssertions to -EnableLegacyExpectations
## 2.0.0 (Feb 2, 2013)
- Functionality equivalent to 1.2.0 except legacy assertions disabled by
default. This is a breaking change for anyone who is already using Pester
## 1.2.0 (Feb 2, 2013)
- Fixing many of the scoping issues [GH-9]
- Ability to tag describes [GH-35]
- Added new assertion syntax (eg: 1 | Should Be 1)
- Added 'Should Throw' assertion [GH-37]
- Added 'Should BeNullOrEmpty' assertion [GH-39]
- Added negative assertions with the 'Not' keyword
- Added 'Match' assertion
- Added -DisableOldStyleAssertions [GH-19] and [GH-27]
- Added Contain assertion which tests file contents [GH-13]
## 1.1.1 (Dec 29, 2012)
- Add should.not_be [GH-38]
## 1.1.0 (Nov 4, 2012)
- Add mocking functionality [GH-26]
## Previous
This changelog is inspired by the
[Vagrant](https://github.com/mitchellh/vagrant/blob/master/CHANGELOG.md) file.
Hopefully this will help keep the releases tidy and understandable.
================================================
FILE: DbgShell/x64/DbgShellTest/Pester/Functions/Assertions/Be.Tests.ps1
================================================
Set-StrictMode -Version Latest
InModuleScope Pester {
Describe "PesterBe" {
It "returns true if the 2 arguments are equal" {
Test-PositiveAssertion (PesterBe 1 1)
}
It "returns true if the 2 arguments are equal and have different case" {
Test-PositiveAssertion (PesterBe "A" "a")
}
It "returns false if the 2 arguments are not equal" {
Test-NegativeAssertion (PesterBe 1 2)
}
}
Describe "PesterBeFailureMessage" {
#the correctness of difference index value and the arrow pointing to the correct place
#are not tested here thoroughly, but the behaviour was visually checked and is
#implicitly tested by using the whole output in the following tests
It "Returns nothing for two identical strings" {
#this situation should actually never happen, as the code is called
#only when the objects are not equal
$string = "string"
PesterBeFailureMessage $string $string | Should BeNullOrEmpty
}
It "Outputs less verbose message for two different objects that are not strings" {
PesterBeFailureMessage 2 1 | Should Be "Expected: {1}`nBut was: {2}"
}
It "Outputs verbose message for two strings of different length" {
PesterBeFailureMessage "actual" "expected" | Should Be "Expected string length 8 but was 6. Strings differ at index 0.`nExpected: {expected}`nBut was: {actual}`n-----------^"
}
It "Outputs verbose message for two different strings of the same length" {
PesterBeFailureMessage "x" "y" | Should Be "String lengths are both 1. Strings differ at index 0.`nExpected: {y}`nBut was: {x}`n-----------^"
}
It "Replaces non-printable characters correctly" {
PesterBeFailureMessage "`n`r`b`0`tx" "`n`r`b`0`ty" | Should Be "String lengths are both 6. Strings differ at index 5.`nExpected: {\n\r\b\0\ty}`nBut was: {\n\r\b\0\tx}`n---------------------^"
}
It "The arrow points to the correct position when non-printable characters are replaced before the difference" {
PesterBeFailureMessage "123`n456" "123`n789" | Should Be "String lengths are both 7. Strings differ at index 4.`nExpected: {123\n789}`nBut was: {123\n456}`n----------------^"
}
It "The arrow points to the correct position when non-printable characters are replaced after the difference" {
PesterBeFailureMessage "abcd`n123" "abc!`n123" | Should Be "String lengths are both 8. Strings differ at index 3.`nExpected: {abc!\n123}`nBut was: {abcd\n123}`n--------------^"
}
}
}
InModuleScope Pester {
Describe "BeExactly" {
It "passes if letter case matches" {
'a' | Should BeExactly 'a'
}
It "fails if letter case doesn't match" {
'A' | Should Not BeExactly 'a'
}
It "passes for numbers" {
1 | Should BeExactly 1
2.15 | Should BeExactly 2.15
}
}
Describe "PesterBeExactlyFailureMessage" {
It "Writes verbose message for strings that differ by case" {
PesterBeExactlyFailureMessage "a" "A" | Should Be "String lengths are both 1. Strings differ at index 0.`nExpected: {A}`nBut was: {a}`n-----------^"
}
}
}
================================================
FILE: DbgShell/x64/DbgShellTest/Pester/Functions/Assertions/Be.ps1
================================================
#Be
function PesterBe($value, $expected) {
return ($expected -eq $value)
}
function PesterBeFailureMessage($value, $expected) {
if (-not (($expected -is [string]) -and ($value -is [string])))
{
return "Expected: {$expected}`nBut was: {$value}"
}
<#joining the output strings to a single string here, otherwise I get
Cannot find an overload for "Exception" and the argument count: "4".
at line: 63 in C:\Users\nohwnd\github\pester\Functions\Assertions\Should.ps1
This is a quickwin solution, doing the join in the Should directly might be better
way of doing this. But I don't want to mix two problems.
#>
( Get-CompareStringMessage -Expected $expected -Actual $value ) -join "`n"
}
function NotPesterBeFailureMessage($value, $expected) {
return "Expected: value was {$value}, but should not have been the same"
}
#BeExactly
function PesterBeExactly($value, $expected) {
return ($expected -ceq $value)
}
function PesterBeExactlyFailureMessage($value, $expected) {
if (-not (($expected -is [string]) -and ($value -is [string])))
{
return "Expected exactly: {$expected}`nBut was: {$value}"
}
<#joining the output strings to a single string here, otherwise I get
Cannot find an overload for "Exception" and the argument count: "4".
at line: 63 in C:\Users\nohwnd\github\pester\Functions\Assertions\Should.ps1
This is a quickwin solution, doing the join in the Should directly might be better
way of doing this. But I don't want to mix two problems.
#>
( Get-CompareStringMessage -Expected $expected -Actual $value -CaseSensitive ) -join "`n"
}
function NotPesterBeExactlyFailureMessage($value, $expected) {
return "Expected: value was {$value}, but should not have been exactly the same"
}
#common functions
function Get-CompareStringMessage {
param(
[Parameter(Mandatory=$true)]
[AllowEmptyString()]
[String]$Expected,
[Parameter(Mandatory=$true)]
[AllowEmptyString()]
[String]$Actual,
[switch]$CaseSensitive
)
$expectedLength = $expected.Length
$actualLength = $actual.Length
$maxLength = $expectedLength,$actualLength | & $SafeCommands['Sort-Object'] -Descending | & $SafeCommands['Select-Object'] -First 1
$differenceIndex = $null
for ($i = 0; $i -lt $maxLength -and ($null -eq $differenceIndex); ++$i){
$differenceIndex = if ($CaseSensitive -and ($expected[$i] -cne $actual[$i]))
{
$i
}
elseif ($expected[$i] -ne $actual[$i])
{
$i
}
}
[string]$output = $null
if ($null -ne $differenceIndex)
{
if ($expected.Length -ne $actual.Length) {
"Expected string length $expectedLength but was $actualLength. Strings differ at index $differenceIndex."
}
else
{
"String lengths are both $expectedLength. Strings differ at index $differenceIndex."
}
"Expected: {{{0}}}" -f ( $expected | Expand-SpecialCharacters )
"But was: {{{0}}}" -f ( $actual | Expand-SpecialCharacters )
$specialCharacterOffset = $null
if ($differenceIndex -ne 0)
{
#count all the special characters before the difference
$specialCharacterOffset = ($actual[0..($differenceIndex-1)] |
& $SafeCommands['Where-Object'] {"`n","`r","`t","`b","`0" -contains $_} |
& $SafeCommands['Measure-Object'] |
& $SafeCommands['Select-Object'] -ExpandProperty Count)
}
'-'*($differenceIndex+$specialCharacterOffset+11)+'^'
}
}
function Expand-SpecialCharacters {
param (
[Parameter(Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[AllowEmptyString()]
[string[]]$InputObject)
process {
$InputObject -replace "`n","\n" -replace "`r","\r" -replace "`t","\t" -replace "`0", "\0" -replace "`b","\b"
}
}
================================================
FILE: DbgShell/x64/DbgShellTest/Pester/Functions/Assertions/BeGreaterThan.Tests.ps1
================================================
Set-StrictMode -Version Latest
InModuleScope Pester {
Describe "PesterBeGreaterThan" {
It "passes if value greater than expected" {
Test-PositiveAssertion (PesterBeGreaterThan 2 1)
2 | Should BeGreaterThan 1
}
It "fails if values equal" {
Test-NegativeAssertion (PesterBeGreaterThan 3 3)
}
It "fails if value less than expected" {
Test-NegativeAssertion (PesterBeGreaterThan 4 5)
}
}
}
================================================
FILE: DbgShell/x64/DbgShellTest/Pester/Functions/Assertions/BeGreaterThan.ps1
================================================
function PesterBeGreaterThan($value, $expected)
{
return [bool]($value -gt $expected)
}
function PesterBeGreaterThanFailureMessage($value,$expected)
{
return "Expected {$value} to be greater than {$expected}"
}
function NotPesterBeGreaterThanFailureMessage($value,$expected)
{
return "Expected {$value} to be less than or equal to {$expected}"
}
================================================
FILE: DbgShell/x64/DbgShellTest/Pester/Functions/Assertions/BeLessThan.Tests.ps1
================================================
Set-StrictMode -Version Latest
InModuleScope Pester {
Describe "PesterBeLessThan" {
It "passes if value Less than expected" {
Test-PositiveAssertion (PesterBeLessThan 1 2)
1 | Should BeLessThan 2
}
It "fails if values equal" {
Test-NegativeAssertion (PesterBeLessThan 3 3)
}
It "fails if value greater than expected" {
Test-NegativeAssertion (PesterBeLessThan 5 4)
}
}
}
================================================
FILE: DbgShell/x64/DbgShellTest/Pester/Functions/Assertions/BeLessThan.ps1
================================================
function PesterBeLessThan($value, $expected)
{
return [bool]($value -lt $expected)
}
function PesterBeLessThanFailureMessage($value,$expected)
{
return "Expected {$value} to be less than {$expected}"
}
function NotPesterBeLessThanFailureMessage($value,$expected)
{
return "Expected {$value} to be greater than or equal to {$expected}"
}
================================================
FILE: DbgShell/x64/DbgShellTest/Pester/Functions/Assertions/BeNullOrEmpty.Tests.ps1
================================================
Set-StrictMode -Version Latest
InModuleScope Pester {
Describe "PesterBeNullOrEmpty" {
It "should return true if null" {
Test-PositiveAssertion (PesterBeNullOrEmpty $null)
}
It "should return true if empty string" {
Test-PositiveAssertion (PesterBeNullOrEmpty "")
}
It "should return true if empty array" {
Test-PositiveAssertion (PesterBeNullOrEmpty @())
}
}
}
================================================
FILE: DbgShell/x64/DbgShellTest/Pester/Functions/Assertions/BeNullOrEmpty.ps1
================================================
function PesterBeNullOrEmpty($value) {
if ($null -eq $value) {
return $true
}
if ([String] -eq $value.GetType()) {
return [String]::IsNullOrEmpty($value)
}
if ($null -ne $value.PSObject.Properties['Count'] -and
$null -ne $value.Count) {
return $value.Count -lt 1
}
return $false
}
function PesterBeNullOrEmptyFailureMessage($value) {
return "Expected: value to be empty but it was {$value}"
}
function NotPesterBeNullOrEmptyFailureMessage {
return "Expected: value to not be empty"
}
================================================
FILE: DbgShell/x64/DbgShellTest/Pester/Functions/Assertions/BeOfType.Tests.ps1
================================================
Set-StrictMode -Version Latest
InModuleScope Pester {
Describe "PesterBeOfType" {
It "passes if value is of the expected type" {
Test-PositiveAssertion (PesterBeOfType 1 ([int]))
Test-PositiveAssertion (PesterBeOfType 1 "Int")
1 | Should BeOfType Int
2.0 | Should BeOfType ([double])
}
It "fails if value is of a different types" {
Test-NegativeAssertion (PesterBeOfType 2 double)
Test-NegativeAssertion (PesterBeOfType 2.0 ([string]))
}
It "fails if type isn't a type" {
Test-NegativeAssertion (PesterBeOfType 5 NotAType)
}
}
}
================================================
FILE: DbgShell/x64/DbgShellTest/Pester/Functions/Assertions/BeOfType.ps1
================================================
function PesterBeOfType($value, $expectedType) {
trap [System.Management.Automation.PSInvalidCastException] { return $false }
if($expectedType -is [string] -and !($expectedType -as [Type])) {
$expectedType = $expectedType -replace '^\[(.*)\]$','$1'
}
return [bool]($value -is $expectedType)
}
function PesterBeOfTypeFailureMessage($value, $expectedType) {
if($expectedType -is [string] -and !($expectedType -as [Type])) {
$expectedType = $expectedType -replace '^\[(.*)\]$','$1'
}
if($Type = $expectedType -as [type]) {
return "Expected: ${value} to be of type [$Type]"
} else {
return "Expected: ${value} to be of type [$expectedType], but unable to find type [$expectedType]. Make sure that the assembly that contains that type is loaded."
}
}
function NotPesterBeOfTypeFailureMessage($value, $expectedType) {
if($expectedType -is [string] -and -not $expectedType -as [Type]) {
$expectedType = $expectedType -replace '^\[(.*)\]$','$1'
}
if($Type = $expectedType -as [type]) {
return "Expected: {$value} to be of any type except [${Type}], but it's a [${Type}]"
} else {
return "Expected: ${value} to be of any type except [$expectedType], but unable to find type [$expectedType]. Make sure that the assembly that contains that type is loaded."
}
}
================================================
FILE: DbgShell/x64/DbgShellTest/Pester/Functions/Assertions/Contain.Tests.ps1
================================================
Set-StrictMode -Version Latest
InModuleScope Pester {
Describe "PesterContain" {
Context "when testing file contents" {
Setup -File "test.txt" "this is line 1`nrush is awesome`nAnd this is Unicode: ☺"
It "returns true if the file contains the specified content" {
Test-PositiveAssertion (PesterContain "$TestDrive\test.txt" "rush")
}
It "returns true if the file contains the specified content with different case" {
Test-PositiveAssertion (PesterContain "$TestDrive\test.txt" "RUSH")
}
It "returns false if the file does not contain the specified content" {
Test-NegativeAssertion (PesterContain "$TestDrive\test.txt" "slime")
}
It "returns true if the file contains the specified UTF8 content" {
Test-PositiveAssertion (PesterContain "$TestDrive\test.txt" "☺")
}
}
}
}
================================================
FILE: DbgShell/x64/DbgShellTest/Pester/Functions/Assertions/Contain.ps1
================================================
function PesterContain($file, $contentExpectation) {
return ((& $SafeCommands['Get-Content'] -Encoding UTF8 $file) -match $contentExpectation)
}
function PesterContainFailureMessage($file, $contentExpectation) {
return "Expected: file ${file} to contain {$contentExpectation}"
}
function NotPesterContainFailureMessage($file, $contentExpectation) {
return "Expected: file {$file} to not contain ${contentExpectation} but it did"
}
================================================
FILE: DbgShell/x64/DbgShellTest/Pester/Functions/Assertions/ContainExactly.Tests.ps1
================================================
Set-StrictMode -Version Latest
InModuleScope Pester {
Describe "PesterContainExactly" {
Context "when testing file contents" {
Setup -File "test.txt" "this is line 1`nPester is awesome`nAnd this is Unicode: ☺"
It "returns true if the file contains the specified content exactly" {
Test-PositiveAssertion (PesterContainExactly "$TestDrive\test.txt" "Pester")
}
It "returns false if the file does not contain the specified content exactly" {
Test-NegativeAssertion (PesterContainExactly "$TestDrive\test.txt" "pESTER")
}
It "returns true if the file contains the specified Unicode content exactly" {
Test-PositiveAssertion (PesterContainExactly "$TestDrive\test.txt" "☺")
}
}
}
}
================================================
FILE: DbgShell/x64/DbgShellTest/Pester/Functions/Assertions/ContainExactly.ps1
================================================
function PesterContainExactly($file, $contentExpectation) {
return ((& $SafeCommands['Get-Content'] -Encoding UTF8 $file) -cmatch $contentExpectation)
}
function PesterContainExactlyFailureMessage($file, $contentExpectation) {
return "Expected: file ${file} to contain exactly {$contentExpectation}"
}
function NotPesterContainExactlyFailureMessage($file, $contentExpectation) {
return "Expected: file {$file} to not contain exactly ${contentExpectation} but it did"
}
================================================
FILE: DbgShell/x64/DbgShellTest/Pester/Functions/Assertions/Exist.Tests.ps1
================================================
Set-StrictMode -Version Latest
InModuleScope Pester {
Describe "PesterExist" {
It "returns true for paths that exist" {
Test-PositiveAssertion (PesterExist $TestDrive)
}
It "returns false for paths do not exist" {
Test-NegativeAssertion (PesterExist "$TestDrive\nonexistent")
}
It 'works for path with escaped [ ] characters' {
New-Item -Path "TestDrive:\[test].txt" -ItemType File | Out-Null
"TestDrive:\``[test``].txt" | Should Exist
}
It 'returns correct result for function drive' {
function f1 {}
'function:f1' | Should Exist
}
It 'returns correct result for env drive' {
$env:test = 'somevalue'
'env:test' | Should Exist
}
}
}
================================================
FILE: DbgShell/x64/DbgShellTest/Pester/Functions/Assertions/Exist.ps1
================================================
function PesterExist($value) {
& $SafeCommands['Test-Path'] $value
}
function PesterExistFailureMessage($value) {
return "Expected: {$value} to exist"
}
function NotPesterExistFailureMessage($value) {
return "Expected: ${value} to not exist, but it was found"
}
================================================
FILE: DbgShell/x64/DbgShellTest/Pester/Functions/Assertions/Match.Tests.ps1
================================================
Set-StrictMode -Version Latest
InModuleScope Pester {
Describe "Match" {
It "returns true for things that match" {
PesterMatch "foobar" "ob" | Should Be $true
}
It "returns false for things that do not match" {
PesterMatch "foobar" "slime" | Should Be $false
}
It "passes for strings with different case" {
PesterMatch "foobar" "FOOBAR" | Should Be $true
}
It "uses regular expressions" {
PesterMatch "foobar" "\S{6}" | Should Be $true
}
}
}
================================================
FILE: DbgShell/x64/DbgShellTest/Pester/Functions/Assertions/Match.ps1
================================================
function PesterMatch($value, $expectedMatch) {
return ($value -match $expectedMatch)
}
function PesterMatchFailureMessage($value, $expectedMatch) {
return "Expected: {$value} to match the expression {$expectedMatch}"
}
function NotPesterMatchFailureMessage($value, $expectedMatch) {
return "Expected: ${value} to not match the expression ${expectedMatch}"
}
================================================
FILE: DbgShell/x64/DbgShellTest/Pester/Functions/Assertions/MatchExactly.Tests.ps1
================================================
Set-StrictMode -Version Latest
InModuleScope Pester {
Describe "MatchExactly" {
It "returns true for things that match exactly" {
PesterMatchExactly "foobar" "ob" | Should Be $true
}
It "returns false for things that do not match exactly" {
PesterMatchExactly "foobar" "FOOBAR" | Should Be $false
}
It "uses regular expressions" {
PesterMatchExactly "foobar" "\S{6}" | Should Be $true
}
}
}
================================================
FILE: DbgShell/x64/DbgShellTest/Pester/Functions/Assertions/MatchExactly.ps1
================================================
function PesterMatchExactly($value, $expectedMatch) {
return ($value -cmatch $expectedMatch)
}
function PesterMatchExactlyFailureMessage($value, $expectedMatch) {
return "Expected: {$value} to exactly match the expression {$expectedMatch}"
}
function NotPesterMatchExactlyFailureMessage($value, $expectedMatch) {
return "Expected: ${value} to not match the expression ${expectedMatch} exactly"
}
================================================
FILE: DbgShell/x64/DbgShellTest/Pester/Functions/Assertions/PesterThrow.Tests.ps1
================================================
Set-StrictMode -Version Latest
InModuleScope Pester {
Describe "PesterThrow" {
It "returns true if the statement throws an exception" {
Test-PositiveAssertion (PesterThrow { throw })
}
It "returns false if the statement does not throw an exception" {
Test-NegativeAssertion (PesterThrow { 1 + 1 })
}
It "returns true if the statement throws an exception and the actual error text matches the expected error text" {
$expectedErrorMessage = "expected error message"
Test-PositiveAssertion (PesterThrow { throw $expectedErrorMessage } $expectedErrorMessage)
}
It "returns false if the statement throws an exception and the actual error does not match the expected error text" {
$unexpectedErrorMessage = "unexpected error message"
$expectedErrorMessage = "some expected error message"
Test-NegativeAssertion (PesterThrow { throw $unexpectedErrorMessage} $expectedErrorMessage)
}
It "returns true if the statement throws an exception and the actual error text matches the expected error pattern" {
Test-PositiveAssertion (PesterThrow { throw "expected error"} "error")
}
It "throws ArgumentException if null ScriptBlock is provided" {
try {
Test-PositiveAssertion (PesterThrow $null)
throw "Should throw exception, but no exception was thrown."
}
catch [ArgumentException] {
#do nothing. we expect argument exception to happen
}
}
}
Describe "Get-DoMessagesMatch" {
It "returns true if the actual message is the same as the expected message" {
$expectedErrorMessage = "expected"
$actualErrorMessage = "expected"
$result = Get-DoMessagesMatch $actualErrorMessage $expectedErrorMessage
$result | Should Be $True
}
It "returns false if the actual message is not the same as the expected message" {
$expectedErrorMessage = "some expected message"
$actualErrorMessage = "unexpected"
$result = Get-DoMessagesMatch $actualErrorMessage $expectedErrorMessage
$result | Should Be $False
}
It "returns false is there's no expectation" {
$result = Get-DoMessagesMatch "" ""
$result | Should Be $False
}
It "returns true if the expected error is contained in the actual message" {
$actualErrorMessage = "this is a long error message"
$expectedText = "long error"
$result = Get-DoMessagesMatch $actualErrorMessage $expectedText
$result | Should Be $True
}
}
Describe 'PesterThrowFailureMessage' {
$testScriptPath = Join-Path $TestDrive.FullName test.ps1
It 'returns false if the actual message is not the same as the expected message' {
$unexpectedErrorMessage = 'unexpected'
$expectedErrorMessage = 'some expected message'
Set-Content -Path $testScriptPath -Value "throw '$unexpectedErrorMessage'"
PesterThrow { & $testScriptPath } $expectedErrorMessage > $null
$result = PesterThrowFailureMessage $unexpectedErrorMessage $expectedErrorMessage
$result | Should Match "^Expected: the expression to throw an exception with message {$expectedErrorMessage}, an exception was raised, message was {$unexpectedErrorMessage}`n from $([RegEx]::Escape($testScriptPath)):\d+ char:\d+"
}
It 'returns true if the actual message is the same as the expected message' {
PesterThrow { } > $null
$result = PesterThrowFailureMessage 'error message'
$result | Should Be 'Expected: the expression to throw an exception'
}
}
Describe 'NotPesterThrowFailureMessage' {
$testScriptPath = Join-Path $TestDrive.FullName test.ps1
It 'returns false if the actual message is not the same as the expected message' {
$unexpectedErrorMessage = 'unexpected'
$expectedErrorMessage = 'some expected message'
Set-Content -Path $testScriptPath -Value "throw '$unexpectedErrorMessage'"
PesterThrow { & $testScriptPath } $expectedErrorMessage > $null
$result = NotPesterThrowFailureMessage $unexpectedErrorMessage $expectedErrorMessage
$result | Should Match "^Expected: the expression not to throw an exception with message {$expectedErrorMessage}, an exception was raised, message was {$unexpectedErrorMessage}`n from $([RegEx]::Escape($testScriptPath)):\d+ char:\d+"
}
It 'returns true if the actual message is the same as the expected message' {
Set-Content -Path $testScriptPath -Value "throw 'error message'"
PesterThrow { & $testScriptPath } > $null
$result = NotPesterThrowFailureMessage 'error message'
$result | Should Match "^Expected: the expression not to throw an exception. Message was {error message}`n from $([RegEx]::Escape($testScriptPath)):\d+ char:\d+"
}
}
}
================================================
FILE: DbgShell/x64/DbgShellTest/Pester/Functions/Assertions/PesterThrow.ps1
================================================
$ActualExceptionMessage = ""
$ActualExceptionWasThrown = $false
# because this is a script block, the user will have to
# wrap the code they want to assert on in { }
function PesterThrow([scriptblock] $script, $expectedErrorMessage) {
if ($null -eq $script) {
throw (New-Object -TypeName ArgumentNullException -ArgumentList "script","Scriptblock not found. Input to 'Throw' and 'Not Throw' must be enclosed in curly braces.")
}
$Script:ActualExceptionMessage = ""
$Script:ActualExceptionWasThrown = $false
try {
# Redirect to $null so script output does not enter the pipeline
& $script > $null
} catch {
$Script:ActualExceptionWasThrown = $true
$Script:ActualExceptionMessage = $_.Exception.Message
$Script:ActualExceptionLine = Get-ExceptionLineInfo $_.InvocationInfo
}
if ($ActualExceptionWasThrown) {
return Get-DoMessagesMatch $ActualExceptionMessage $expectedErrorMessage
}
return $false
}
function Get-DoMessagesMatch($value, $expected) {
if ($expected -eq "") { return $false }
return $value.Contains($expected)
}
function Get-ExceptionLineInfo($info) {
# $info.PositionMessage has a leading blank line that we need to account for in PowerShell 2.0
$positionMessage = $info.PositionMessage -split '\r?\n' -match '\S' -join "`r`n"
return ($positionMessage -replace "^At ","from ")
}
function PesterThrowFailureMessage($value, $expected) {
if ($expected) {
return "Expected: the expression to throw an exception with message {{{0}}}, an exception was {2}raised, message was {{{1}}}`n {3}" -f
$expected, $ActualExceptionMessage,(@{$true="";$false="not "}[$ActualExceptionWasThrown]),($ActualExceptionLine -replace "`n","`n ")
} else {
return "Expected: the expression to throw an exception"
}
}
function NotPesterThrowFailureMessage($value, $expected) {
if ($expected) {
return "Expected: the expression not to throw an exception with message {{{0}}}, an exception was {2}raised, message was {{{1}}}`n {3}" -f
$expected, $ActualExceptionMessage,(@{$true="";$false="not "}[$ActualExceptionWasThrown]),($ActualExceptionLine -replace "`n","`n ")
} else {
return "Expected: the expression not to throw an exception. Message was {{{0}}}`n {1}" -f $ActualExceptionMessage,($ActualExceptionLine -replace "`n","`n ")
}
}
================================================
FILE: DbgShell/x64/DbgShellTest/Pester/Functions/Assertions/Set-TestInconclusive.ps1
================================================
function New-InconclusiveErrorRecord ([string] $Message, [string] $File, [string] $Line, [string] $LineText) {
$exception = New-Object Exception $Message
$errorID = 'PesterTestInconclusive'
$errorCategory = [Management.Automation.ErrorCategory]::InvalidResult
# we use ErrorRecord.TargetObject to pass structured information about the error to a reporting system.
$targetObject = @{Message = $Message; File = $File; Line = $Line; LineText = $LineText}
$errorRecord = New-Object Management.Automation.ErrorRecord $exception, $errorID, $errorCategory, $targetObject
return $errorRecord
}
function Set-TestInconclusive {
param (
[string] $Message
)
Assert-DescribeInProgress -CommandName Set-TestInconclusive
$lineText = $MyInvocation.Line.TrimEnd("`n")
$line = $MyInvocation.ScriptLineNumber
$file = $MyInvocation.ScriptName
throw ( New-InconclusiveErrorRecord -Message $Message -File $file -Line $line -LineText $lineText)
}
================================================
FILE: DbgShell/x64/DbgShellTest/Pester/Functions/Assertions/Should.Tests.ps1
================================================
Set-StrictMode -Version Latest
InModuleScope Pester {
Describe "Parse-ShouldArgs" {
It "sanitizes assertions functions" {
$parsedArgs = Parse-ShouldArgs TestFunction
$parsedArgs.AssertionMethod | Should Be PesterTestFunction
}
It "works with strict mode when using 'switch' style tests" {
Set-StrictMode -Version Latest
{ throw 'Test' } | Should Throw
}
Context "for positive assertions" {
$parsedArgs = Parse-ShouldArgs testMethod, 1
It "gets the expected value from the 2nd argument" {
$ParsedArgs.ExpectedValue | Should Be 1
}
It "marks the args as a positive assertion" {
$ParsedArgs.PositiveAssertion | Should Be $true
}
}
Context "for negative assertions" {
$parsedArgs = Parse-ShouldArgs Not, testMethod, 1
It "gets the expected value from the third argument" {
$ParsedArgs.ExpectedValue | Should Be 1
}
It "marks the args as a negative assertion" {
$ParsedArgs.PositiveAssertion | Should Be $false
}
}
Context "for the throw assertion" {
$parsedArgs = Parse-ShouldArgs Throw
It "translates the Throw assertion to PesterThrow" {
$ParsedArgs.AssertionMethod | Should Be PesterThrow
}
}
}
Describe "Get-TestResult" {
Context "for positive assertions" {
function PesterTest { return $true }
$shouldArgs = Parse-ShouldArgs Test
It "returns false if the test returns true" {
Get-TestResult $shouldArgs | Should Be $false
}
}
Context "for negative assertions" {
function PesterTest { return $false }
$shouldArgs = Parse-ShouldArgs Not, Test
It "returns false if the test returns false" {
Get-TestResult $shouldArgs | Should Be $false
}
}
}
Describe "Get-FailureMessage" {
Context "for positive assertions" {
function PesterTestFailureMessage($v, $e) { return "slime $e $v" }
$shouldArgs = Parse-ShouldArgs Test, 1
It "should return the positive assertion failure message" {
Get-FailureMessage $shouldArgs 2 | Should Be "slime 1 2"
}
}
Context "for negative assertions" {
function NotPesterTestFailureMessage($v, $e) { return "not slime $e $v" }
$shouldArgs = Parse-ShouldArgs Not, Test, 1
It "should return the negative assertion failure message" {
Get-FailureMessage $shouldArgs 2 | Should Be "not slime 1 2"
}
}
}
Describe -Tag "Acceptance" "Should" {
It "can use the Be assertion" {
1 | Should Be 1
}
It "can use the Not Be assertion" {
1 | Should Not Be 2
}
It "can use the BeNullOrEmpty assertion" {
$null | Should BeNullOrEmpty
@() | Should BeNullOrEmpty
"" | Should BeNullOrEmpty
}
It "can use the Not BeNullOrEmpty assertion" {
@("foo") | Should Not BeNullOrEmpty
"foo" | Should Not BeNullOrEmpty
" " | Should Not BeNullOrEmpty
@(1,2,3) | Should Not BeNullOrEmpty
12345 | Should Not BeNullOrEmpty
$item1 = New-Object PSObject -Property @{Id=1; Name="foo"}
$item2 = New-Object PSObject -Property @{Id=2; Name="bar"}
@($item1, $item2) | Should Not BeNullOrEmpty
}
It "can handle exception thrown assertions" {
{ foo } | Should Throw
}
It "can handle exception should not be thrown assertions" {
{ $foo = 1 } | Should Not Throw
}
It "can handle Exist assertion" {
$TestDrive | Should Exist
}
It "can handle the Match assertion" {
"abcd1234" | Should Match "d1"
}
It "can test for file contents" {
Setup -File "test.foo" "expected text"
"$TestDrive\test.foo" | Should Contain "expected text"
}
It "ensures all assertion functions provide failure messages" {
$assertionFunctions = @("PesterBe", "PesterThrow", "PesterBeNullOrEmpty", "PesterExist",
"PesterMatch", "PesterContain")
$assertionFunctions | % {
"function:$($_)FailureMessage" | Should Exist
"function:Not$($_)FailureMessage" | Should Exist
}
}
# TODO understand the purpose of this test, perhaps some better wording
It "can process functions with empty output as input" {
function ReturnNothing {}
# TODO figure out why this is the case
if ($PSVersionTable.PSVersion -eq "2.0") {
{ $(ReturnNothing) | Should Not BeNullOrEmpty } | Should Not Throw
} else {
{ $(ReturnNothing) | Should Not BeNullOrEmpty } | Should Throw
}
}
It 'All failure message functions are present' {
$assertionFunctions = Get-Command -CommandType Function -Module Pester |
Select-Object -ExpandProperty Name |
Where-Object { $_ -like 'Pester*' -and $_ -notlike '*FailureMessage' }
$missingFunctions = @(
foreach ($assertionFunction in $assertionFunctions)
{
$positiveFailureMessage = "${assertionFunction}FailureMessage"
$negativeFailureMessage = "Not${assertionFunction}FailureMessage"
if (-not (Test-Path function:$positiveFailureMessage)) { $positiveFailureMessage }
if (-not (Test-Path function:$negativeFailureMessage)) { $negativeFailureMessage }
}
)
[string]$missingFunctions | Should BeNullOrEmpty
}
}
}
================================================
FILE: DbgShell/x64/DbgShellTest/Pester/Functions/Assertions/Should.ps1
================================================
function Parse-ShouldArgs([array] $shouldArgs) {
if ($null -eq $shouldArgs) { $shouldArgs = @() }
$parsedArgs = @{
PositiveAssertion = $true
ExpectedValue = $null
}
$assertionMethodIndex = 0
$expectedValueIndex = 1
if ($shouldArgs.Count -gt 0 -and $shouldArgs[0].ToLower() -eq "not") {
$parsedArgs.PositiveAssertion = $false
$assertionMethodIndex += 1
$expectedValueIndex += 1
}
if ($assertionMethodIndex -lt $shouldArgs.Count)
{
$parsedArgs.AssertionMethod = "Pester$($shouldArgs[$assertionMethodIndex])"
}
else
{
throw 'You cannot call Should without specifying an assertion method.'
}
if ($expectedValueIndex -lt $shouldArgs.Count)
{
$parsedArgs.ExpectedValue = $shouldArgs[$expectedValueIndex]
}
return $parsedArgs
}
function Get-TestResult($shouldArgs, $value) {
$assertionMethod = $shouldArgs.AssertionMethod
$command = & $SafeCommands['Get-Command'] $assertionMethod -CommandType Function -ErrorAction $script:IgnoreErrorPreference
if ($null -eq $command)
{
$assertionMethod = $assertionMethod -replace '^Pester'
throw "'$assertionMethod' is not a valid Should operator."
}
$testResult = (& $assertionMethod $value $shouldArgs.ExpectedValue)
if ($shouldArgs.PositiveAssertion) {
return -not $testResult
}
return $testResult
}
function Get-FailureMessage($shouldArgs, $value) {
$failureMessageFunction = "$($shouldArgs.AssertionMethod)FailureMessage"
if (-not $shouldArgs.PositiveAssertion) {
$failureMessageFunction = "Not$failureMessageFunction"
}
return (& $failureMessageFunction $value $shouldArgs.ExpectedValue)
}
function New-ShouldErrorRecord ([string] $Message, [string] $File, [string] $Line, [string] $LineText) {
$exception = & $SafeCommands['New-Object'] Exception $Message
$errorID = 'PesterAssertionFailed'
$errorCategory = [Management.Automation.ErrorCategory]::InvalidResult
# we use ErrorRecord.TargetObject to pass structured information about the error to a reporting system.
$targetObject = @{Message = $Message; File = $File; Line = $Line; LineText = $LineText}
$errorRecord = & $SafeCommands['New-Object'] Management.Automation.ErrorRecord $exception, $errorID, $errorCategory, $targetObject
return $errorRecord
}
function Should {
<#
.SYNOPSIS
Should is a keyword what is used to define an assertion inside It block.
.DESCRIPTION
Should is a keyword what is used to define an assertion inside the It block.
Should provides assertion methods for verify assertion e.g. comparing objects.
If assertion is not met the test fails and an exception is throwed up.
Should can be used more than once in the It block if more than one assertion
need to be verified. Each Should keywords need to be located in a new line.
Test will be passed only when all assertion will be met (logical conjuction).
.LINK
about_Should
about_Pester
#>
begin {
Assert-DescribeInProgress -CommandName Should
$parsedArgs = Parse-ShouldArgs $args
}
end {
$input.MoveNext()
do {
$value = $input.Current
$testFailed = Get-TestResult $parsedArgs $value
if ($testFailed) {
$lineText = $MyInvocation.Line.TrimEnd("`n")
$line = $MyInvocation.ScriptLineNumber
$file = $MyInvocation.ScriptName
$failureMessage = Get-FailureMessage $parsedArgs $value
throw ( New-ShouldErrorRecord -Message $failureMessage -File $file -Line $line -LineText $lineText)
}
} until ($input.MoveNext() -eq $false)
}
}
================================================
FILE: DbgShell/x64/DbgShellTest/Pester/Functions/Assertions/Test-Assertion.ps1
================================================
function Test-PositiveAssertion($result) {
if (-not $result) {
throw "Expecting expression to pass, but it failed"
}
}
function Test-NegativeAssertion($result) {
if ($result) {
throw "Expecting expression to pass, but it failed"
}
}
================================================
FILE: DbgShell/x64/DbgShellTest/Pester/Functions/BreakAndContinue.Tests.ps1
================================================
Describe 'Clean handling of break and continue' {
# If this test 'fails', it'll just cause most of the rest of the tests to never execute (and we won't see any actual failures.)
# The CI job monitors metrics, though, and will fail the build if the number of tests drops too much.
Context 'Break' {
break
}
Context 'Continue' {
continue
}
It 'Did not abort the whole test run' { $null = $null }
}
================================================
FILE: DbgShell/x64/DbgShellTest/Pester/Functions/Context.Tests.ps1
================================================
Set-StrictMode -Version Latest
Describe 'Testing Context' {
It 'Has a non-mandatory fixture parameter which throws the proper error message if missing' {
$command = Get-Command Context -Module Pester
$command | Should Not Be $null
$parameter = $command.Parameters['Fixture']
$parameter | Should Not Be $null
# Some environments (Nano/CoreClr) don't have all the type extensions
$attribute = $parameter.Attributes | Where-Object { $_ -is [System.Management.Automation.ParameterAttribute] }
$isMandatory = $null -ne $attribute -and $attribute.Mandatory
$isMandatory | Should Be $false
{ Context Bogus } | Should Throw 'No test script block is provided'
}
}
================================================
FILE: DbgShell/x64/DbgShellTest/Pester/Functions/Context.ps1
================================================
function Context {
<#
.SYNOPSIS
Provides logical grouping of It blocks within a single Describe block.
.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.
.PARAMETER Name
The name of the Context. This is a phrase describing a set of tests within
a Describe block.
.PARAMETER Fixture
Script that is executed. This may include setup specific to the context
and one or more It blocks that validate the expected outcomes.
.EXAMPLE
function Add-Numbers($a, $b) {
return $a + $b
}
Describe "Add-Numbers" {
Context "when root does not exist" {
It "..." { ... }
}
Context "when root does exist" {
It "..." { ... }
It "..." { ... }
It "..." { ... }
}
}
.LINK
Describe
It
BeforeEach
AfterEach
about_Should
about_Mocking
about_TestDrive
#>
param(
[Parameter(Mandatory = $true)]
[string] $Name,
[ValidateNotNull()]
[ScriptBlock] $Fixture = $(Throw "No test script block is provided. (Have you put the open curly brace on the next line?)")
)
Assert-DescribeInProgress -CommandName Context
$Pester.EnterContext($Name )
$TestDriveContent = Get-TestDriveChildItem
$Pester.CurrentContext | Write-Context
try
{
Add-SetupAndTeardown -ScriptBlock $Fixture
Invoke-TestGroupSetupBlocks -Scope $pester.Scope
do
{
$null = & $Fixture
} until ($true)
}
catch
{
$firstStackTraceLine = $_.InvocationInfo.PositionMessage.Trim() -split '\r?\n' | & $SafeCommands['Select-Object'] -First 1
$Pester.AddTestResult('Error occurred in Context block', "Failed", $null, $_.Exception.Message, $firstStackTraceLine, $null, $null, $_)
$Pester.TestResult[-1] | Write-PesterResult
}
finally
{
Invoke-TestGroupTeardownBlocks -Scope $pester.Scope
Clear-SetupAndTeardown
Clear-TestDrive -Exclude ($TestDriveContent | & $SafeCommands['Select-Object'] -ExpandProperty FullName)
Exit-MockScope
$Pester.LeaveContext()
}
}
================================================
FILE: DbgShell/x64/DbgShellTest/Pester/Functions/Coverage.Tests.ps1
================================================
if ($PSVersionTable.PSVersion.Major -le 2) { return }
InModuleScope Pester {
Describe 'Code Coverage Analysis' {
$root = (Get-PSDrive TestDrive).Root
$null = New-Item -Path $root\TestScript.ps1 -ItemType File -ErrorAction SilentlyContinue
Set-Content -Path $root\TestScript.ps1 -Value @'
function FunctionOne
{
function NestedFunction
{
'I am the nested function.'
'I get fully executed.'
}
if ($true)
{
'I am functionOne'
NestedFunction
}
}
function FunctionTwo
{
'I am function two. I never get called.'
}
FunctionOne
'@
Context 'Entire file' {
$testState = New-PesterState -Path $root
# Path deliberately duplicated to make sure the code doesn't produce multiple breakpoints for the same commands
Enter-CoverageAnalysis -CodeCoverage "$root\TestScript.ps1", "$root\TestScript.ps1" -PesterState $testState
It 'Has the proper number of breakpoints defined' {
$testState.CommandCoverage.Count | Should Be 7
}
$null = & "$root\TestScript.ps1"
$coverageReport = Get-CoverageReport -PesterState $testState
It 'Reports the proper number of executed commands' {
$coverageReport.NumberOfCommandsExecuted | Should Be 6
}
It 'Reports the proper number of analyzed commands' {
$coverageReport.NumberOfCommandsAnalyzed | Should Be 7
}
It 'Reports the proper number of analyzed files' {
$coverageReport.NumberOfFilesAnalyzed | Should Be 1
}
It 'Reports the proper number of missed commands' {
$coverageReport.MissedCommands.Count | Should Be 1
}
It 'Reports the correct missed command' {
$coverageReport.MissedCommands[0].Command | Should Be "'I am function two. I never get called.'"
}
It 'Reports the proper number of hit commands' {
$coverageReport.HitCommands.Count | Should Be 6
}
It 'Reports the correct hit command' {
$coverageReport.HitCommands[0].Command | Should Be "'I am the nested function.'"
}
Exit-CoverageAnalysis -PesterState $testState
}
Context 'Single function with missed commands' {
$testState = New-PesterState -Path $root
Enter-CoverageAnalysis -CodeCoverage @{Path = "$root\TestScript.ps1"; Function = 'FunctionTwo'} -PesterState $testState
It 'Has the proper number of breakpoints defined' {
$testState.CommandCoverage.Count | Should Be 1
}
$null = & "$root\TestScript.ps1"
$coverageReport = Get-CoverageReport -PesterState $testState
It 'Reports the proper number of executed commands' {
$coverageReport.NumberOfCommandsExecuted | Should Be 0
}
It 'Reports the proper number of analyzed commands' {
$coverageReport.NumberOfCommandsAnalyzed | Should Be 1
}
It 'Reports the proper number of missed commands' {
$coverageReport.MissedCommands.Count | Should Be 1
}
It 'Reports the correct missed command' {
$coverageReport.MissedCommands[0].Command | Should Be "'I am function two. I never get called.'"
}
It 'Reports the proper number of hit commands' {
$coverageReport.HitCommands.Count | Should Be 0
}
Exit-CoverageAnalysis -PesterState $testState
}
Context 'Single function with no missed commands' {
$testState = New-PesterState -Path $root
Enter-CoverageAnalysis -CodeCoverage @{Path = "$root\TestScript.ps1"; Function = 'FunctionOne'} -PesterState $testState
It 'Has the proper number of breakpoints defined' {
$testState.CommandCoverage.Count | Should Be 5
}
$null = & "$root\TestScript.ps1"
$coverageReport = Get-CoverageReport -PesterState $testState
It 'Reports the proper number of executed commands' {
$coverageReport.NumberOfCommandsExecuted | Should Be 5
}
It 'Reports the proper number of analyzed commands' {
$coverageReport.NumberOfCommandsAnalyzed | Should Be 5
}
It 'Reports the proper number of missed commands' {
$coverageReport.MissedCommands.Count | Should Be 0
}
It 'Reports the proper number of hit commands' {
$coverageReport.HitCommands.Count | Should Be 5
}
It 'Reports the correct hit command' {
$coverageReport.HitCommands[0].Command | Should Be "'I am the nested function.'"
}
Exit-CoverageAnalysis -PesterState $testState
}
Context 'Range of lines' {
$testState = New-PesterState -Path $root
Enter-CoverageAnalysis -CodeCoverage @{Path = "$root\TestScript.ps1"; StartLine = 11; EndLine = 12 } -PesterState $testState
It 'Has the proper number of breakpoints defined' {
$testState.CommandCoverage.Count | Should Be 2
}
$null = & "$root\TestScript.ps1"
$coverageReport = Get-CoverageReport -PesterState $testState
It 'Reports the proper number of executed commands' {
$coverageReport.NumberOfCommandsExecuted | Should Be 2
}
It 'Reports the proper number of analyzed commands' {
$coverageReport.NumberOfCommandsAnalyzed | Should Be 2
}
It 'Reports the proper number of missed commands' {
$coverageReport.MissedCommands.Count | Should Be 0
}
It 'Reports the proper number of hit commands' {
$coverageReport.HitCommands.Count | Should Be 2
}
It 'Reports the correct hit command' {
$coverageReport.HitCommands[0].Command | Should Be "'I am functionOne'"
}
Exit-CoverageAnalysis -PesterState $testState
}
Context 'Wildcard resolution' {
$testState = New-PesterState -Path $root
Enter-CoverageAnalysis -CodeCoverage @{Path = "$root\*.ps1"; Function = '*' } -PesterState $testState
It 'Has the proper number of breakpoints defined' {
$testState.CommandCoverage.Count | Should Be 6
}
$null = & "$root\TestScript.ps1"
$coverageReport = Get-CoverageReport -PesterState $testState
It 'Reports the proper number of executed commands' {
$coverageReport.NumberOfCommandsExecuted | Should Be 5
}
It 'Reports the proper number of analyzed commands' {
$coverageReport.NumberOfCommandsAnalyzed | Should Be 6
}
It 'Reports the proper number of analyzed files' {
$coverageReport.NumberOfFilesAnalyzed | Should Be 1
}
It 'Reports the proper number of missed commands' {
$coverageReport.MissedCommands.Count | Should Be 1
}
It 'Reports the correct missed command' {
$coverageReport.MissedCommands[0].Command | Should Be "'I am function two. I never get called.'"
}
It 'Reports the proper number of hit commands' {
$coverageReport.HitCommands.Count | Should Be 5
}
It 'Reports the correct hit command' {
$coverageReport.HitCommands[0].Command | Should Be "'I am the nested function.'"
}
Exit-CoverageAnalysis -PesterState $testState
}
}
Describe 'Stripping common parent paths' {
$paths = @(
Normalize-Path 'C:\Common\Folder\UniqueSubfolder1/File.ps1'
Normalize-Path 'C:\Common\Folder\UniqueSubfolder2/File2.ps1'
Normalize-Path 'C:\Common\Folder\UniqueSubfolder3/File3.ps1'
)
$commonPath = Get-CommonParentPath -Path $paths
$expectedCommonPath = Normalize-Path 'C:\Common/Folder'
It 'Identifies the correct parent path' {
$commonPath | Should Be $expectedCommonPath
}
$expectedRelativePath = Normalize-Path 'UniqueSubfolder1/File.ps1'
$relativePath = Get-RelativePath -Path $paths[0] -RelativeTo $commonPath
It 'Strips the common path correctly' {
$relativePath | Should Be $expectedRelativePath
}
}
if ((Get-Module -ListAvailable PSDesiredStateConfiguration) -and $PSVersionTable.PSVersion.Major -ge 4)
{
Describe 'Analyzing coverage of a DSC configuration' {
$root = (Get-PSDrive TestDrive).Root
$null = New-Item -Path $root\TestScriptWithConfiguration.ps1 -ItemType File -ErrorAction SilentlyContinue
Set-Content -Path $root\TestScriptWithConfiguration.ps1 -Value @'
$line1 = $true # Triggers breakpoint
$line2 = $true # Triggers breakpoint
configuration MyTestConfig # does NOT trigger breakpoint
{
Node localhost # Triggers breakpoint
{
WindowsFeature XPSViewer # Triggers breakpoint
{
Name = 'XPS-Viewer' # does NOT trigger breakpoint
Ensure = 'Present' # does NOT trigger breakpoint
}
}
return # does NOT trigger breakpoint
$doesNotExecute = $true # Triggers breakpoint
}
$line3 = $true # Triggers breakpoint
return # does NOT trigger breakpoint
$doesnotexecute = $true # Triggers breakpoint
'@
$testState = New-PesterState -Path $root
Enter-CoverageAnalysis -CodeCoverage "$root\TestScriptWithConfiguration.ps1" -PesterState $testState
It 'Has the proper number of breakpoints defined' {
$testState.CommandCoverage.Count | Should Be 7
}
$null = . "$root\TestScriptWithConfiguration.ps1"
$coverageReport = Get-CoverageReport -PesterState $testState
It 'Reports the proper number of missed commands before running the configuration' {
$coverageReport.MissedCommands.Count | Should Be 4
}
MyTestConfig -OutputPath $root
$coverageReport = Get-CoverageReport -PesterState $testState
It 'Reports the proper number of missed commands after running the configuration' {
$coverageReport.MissedCommands.Count | Should Be 2
}
Exit-CoverageAnalysis -PesterState $testState
}
}
}
================================================
FILE: DbgShell/x64/DbgShellTest/Pester/Functions/Coverage.ps1
================================================
if ($PSVersionTable.PSVersion.Major -le 2)
{
function Exit-CoverageAnalysis { }
function Get-CoverageReport { }
function Show-CoverageReport { }
function Enter-CoverageAnalysis {
param ( $CodeCoverage )
if ($CodeCoverage) { & $SafeCommands['Write-Error'] 'Code coverage analysis requires PowerShell 3.0 or later.' }
}
return
}
function Enter-CoverageAnalysis
{
[CmdletBinding()]
param (
[object[]] $CodeCoverage,
[object] $PesterState
)
$coverageInfo =
foreach ($object in $CodeCoverage)
{
Get-CoverageInfoFromUserInput -InputObject $object
}
$PesterState.CommandCoverage = @(Get-CoverageBreakpoints -CoverageInfo $coverageInfo)
}
function Exit-CoverageAnalysis
{
param ([object] $PesterState)
& $SafeCommands['Set-StrictMode'] -Off
$breakpoints = @($PesterState.CommandCoverage.Breakpoint) -ne $null
if ($breakpoints.Count -gt 0)
{
& $SafeCommands['Remove-PSBreakpoint'] -Breakpoint $breakpoints
}
}
function Get-CoverageInfoFromUserInput
{
param (
[Parameter(Mandatory = $true)]
[object]
$InputObject
)
if ($InputObject -is [System.Collections.IDictionary])
{
$unresolvedCoverageInfo = Get-CoverageInfoFromDictionary -Dictionary $InputObject
}
else
{
$unresolvedCoverageInfo = New-CoverageInfo -Path ([string]$InputObject)
}
Resolve-CoverageInfo -UnresolvedCoverageInfo $unresolvedCoverageInfo
}
function New-CoverageInfo
{
param ([string] $Path, [string] $Function = $null, [int] $StartLine = 0, [int] $EndLine = 0)
return [pscustomobject]@{
Path = $Path
Function = $Function
StartLine = $StartLine
EndLine = $EndLine
}
}
function Get-CoverageInfoFromDictionary
{
param ([System.Collections.IDictionary] $Dictionary)
[string] $path = Get-DictionaryValueFromFirstKeyFound -Dictionary $Dictionary -Key 'Path', 'p'
if ([string]::IsNullOrEmpty($path))
{
throw "Coverage value '$Dictionary' is missing required Path key."
}
$startLine = Get-DictionaryValueFromFirstKeyFound -Dictionary $Dictionary -Key 'StartLine', 'Start', 's'
$endLine = Get-DictionaryValueFromFirstKeyFound -Dictionary $Dictionary -Key 'EndLine', 'End', 'e'
[string] $function = Get-DictionaryValueFromFirstKeyFound -Dictionary $Dictionary -Key 'Function', 'f'
$startLine = Convert-UnknownValueToInt -Value $startLine -DefaultValue 0
$endLine = Convert-UnknownValueToInt -Value $endLine -DefaultValue 0
return New-CoverageInfo -Path $path -StartLine $startLine -EndLine $endLine -Function $function
}
function Convert-UnknownValueToInt
{
param ([object] $Value, [int] $DefaultValue = 0)
try
{
return [int] $Value
}
catch
{
return $DefaultValue
}
}
function Resolve-CoverageInfo
{
param ([psobject] $UnresolvedCoverageInfo)
$path = $UnresolvedCoverageInfo.Path
try
{
$resolvedPaths = & $SafeCommands['Resolve-Path'] -Path $path -ErrorAction Stop
}
catch
{
& $SafeCommands['Write-Error'] "Could not resolve coverage path '$path': $($_.Exception.Message)"
return
}
$filePaths =
foreach ($resolvedPath in $resolvedPaths)
{
$item = & $SafeCommands['Get-Item'] -LiteralPath $resolvedPath
if ($item -is [System.IO.FileInfo] -and ('.ps1','.psm1') -contains $item.Extension)
{
$item.FullName
}
elseif (-not $item.PsIsContainer)
{
& $SafeCommands['Write-Warning'] "CodeCoverage path '$path' resolved to a non-PowerShell file '$($item.FullName)'; this path will not be part of the coverage report."
}
}
$params = @{
StartLine = $UnresolvedCoverageInfo.StartLine
EndLine = $UnresolvedCoverageInfo.EndLine
Function = $UnresolvedCoverageInfo.Function
}
foreach ($filePath in $filePaths)
{
$params['Path'] = $filePath
New-CoverageInfo @params
}
}
function Get-CoverageBreakpoints
{
[CmdletBinding()]
param (
[object[]] $CoverageInfo
)
$fileGroups = @($CoverageInfo | & $SafeCommands['Group-Object'] -Property Path)
foreach ($fileGroup in $fileGroups)
{
& $SafeCommands['Write-Verbose'] "Initializing code coverage analysis for file '$($fileGroup.Name)'"
$totalCommands = 0
$analyzedCommands = 0
:commandLoop
foreach ($command in Get-CommandsInFile -Path $fileGroup.Name)
{
$totalCommands++
foreach ($coverageInfoObject in $fileGroup.Group)
{
if (Test-CoverageOverlapsCommand -CoverageInfo $coverageInfoObject -Command $command)
{
$analyzedCommands++
New-CoverageBreakpoint -Command $command
continue commandLoop
}
}
}
& $SafeCommands['Write-Verbose'] "Analyzing $analyzedCommands of $totalCommands commands in file '$($fileGroup.Name)' for code coverage"
}
}
function Get-CommandsInFile
{
param ([string] $Path)
$errors = $null
$tokens = $null
$ast = [System.Management.Automation.Language.Parser]::ParseFile($Path, [ref] $tokens, [ref] $errors)
if ($PSVersionTable.PSVersion.Major -ge 5)
{
# In PowerShell 5.0, dynamic keywords for DSC configurations are represented by the DynamicKeywordStatementAst
# class. They still trigger breakpoints, but are not a child class of CommandBaseAst anymore.
$predicate = {
$args[0] -is [System.Management.Automation.Language.DynamicKeywordStatementAst] -or
$args[0] -is [System.Management.Automation.Language.CommandBaseAst]
}
}
else
{
$predicate = { $args[0] -is [System.Management.Automation.Language.CommandBaseAst] }
}
$searchNestedScriptBlocks = $true
$ast.FindAll($predicate, $searchNestedScriptBlocks)
}
function Test-CoverageOverlapsCommand
{
param ([object] $CoverageInfo, [System.Management.Automation.Language.Ast] $Command)
if ($CoverageInfo.Function)
{
Test-CommandInsideFunction -Command $Command -Function $CoverageInfo.Function
}
else
{
Test-CoverageOverlapsCommandByLineNumber @PSBoundParameters
}
}
function Test-CommandInsideFunction
{
param ([System.Management.Automation.Language.Ast] $Command, [string] $Function)
for ($ast = $Command; $null -ne $ast; $ast = $ast.Parent)
{
$functionAst = $ast -as [System.Management.Automation.Language.FunctionDefinitionAst]
if ($null -ne $functionAst -and $functionAst.Name -like $Function)
{
return $true
}
}
return $false
}
function Test-CoverageOverlapsCommandByLineNumber
{
param ([object] $CoverageInfo, [System.Management.Automation.Language.Ast] $Command)
$commandStart = $Command.Extent.StartLineNumber
$commandEnd = $Command.Extent.EndLineNumber
$coverStart = $CoverageInfo.StartLine
$coverEnd = $CoverageInfo.EndLine
# An EndLine value of 0 means to cover the entire rest of the file from StartLine
# (which may also be 0)
if ($coverEnd -le 0) { $coverEnd = [int]::MaxValue }
return (Test-RangeContainsValue -Value $commandStart -Min $coverStart -Max $coverEnd) -or
(Test-RangeContainsValue -Value $commandEnd -Min $coverStart -Max $coverEnd)
}
function Test-RangeContainsValue
{
param ([int] $Value, [int] $Min, [int] $Max)
return $Value -ge $Min -and $Value -le $Max
}
function New-CoverageBreakpoint
{
param ([System.Management.Automation.Language.Ast] $Command)
if (IsIgnoredCommand -Command $Command) { return }
$params = @{
Script = $Command.Extent.File
Line = $Command.Extent.StartLineNumber
Column = $Command.Extent.StartColumnNumber
Action = { }
}
$breakpoint = & $SafeCommands['Set-PSBreakpoint'] @params
[pscustomobject] @{
File = $Command.Extent.File
Function = Get-ParentFunctionName -Ast $Command
Line = $Command.Extent.StartLineNumber
Command = Get-CoverageCommandText -Ast $Command
Breakpoint = $breakpoint
}
}
function IsIgnoredCommand
{
param ([System.Management.Automation.Language.Ast] $Command)
if (-not $Command.Extent.File)
{
# This can happen if the script contains "configuration" or any similarly implemented
# dynamic keyword. PowerShell modifies the script code and reparses it in memory, leading
# to AST elements with no File in their Extent.
return $true
}
if ($PSVersionTable.PSVersion.Major -ge 4)
{
if ($Command.Extent.Text -eq 'Configuration')
{
# More DSC voodoo. Calls to "configuration" generate breakpoints, but their HitCount
# stays zero (even though they are executed.) For now, ignore them, unless we can come
# up with a better solution.
return $true
}
if (IsChildOfHashtableDynamicKeyword -Command $Command)
{
# The lines inside DSC resource declarations don't trigger their breakpoints when executed,
# just like the "configuration" keyword itself. I don't know why, at this point, but just like
# configuration, we'll ignore it so it doesn't clutter up the coverage analysis with useless junk.
return $true
}
}
if (IsClosingLoopCondition -Command $Command)
{
# For some reason, the closing expressions of do/while and do/until loops don't trigger their breakpoints.
# To avoid useless clutter, we'll ignore those lines as well.
return $true
}
return $false
}
function IsChildOfHashtableDynamicKeyword
{
param ([System.Management.Automation.Language.Ast] $Command)
for ($ast = $Command.Parent; $null -ne $ast; $ast = $ast.Parent)
{
if ($PSVersionTable.PSVersion.Major -ge 5)
{
# The ast behaves differently for DSC resources with version 5+. There's a new DynamicKeywordStatementAst class,
# and they no longer are represented by CommandAst objects.
if ($ast -is [System.Management.Automation.Language.DynamicKeywordStatementAst] -and
$ast.CommandElements[-1] -is [System.Management.Automation.Language.HashtableAst])
{
return $true
}
}
else
{
if ($ast -is [System.Management.Automation.Language.CommandAst] -and
$null -ne $ast.DefiningKeyword -and
$ast.DefiningKeyword.BodyMode -eq [System.Management.Automation.Language.DynamicKeywordBodyMode]::Hashtable)
{
return $true
}
}
}
return $false
}
function IsClosingLoopCondition
{
param ([System.Management.Automation.Language.Ast] $Command)
$ast = $Command
while ($null -ne $ast.Parent)
{
if (($ast.Parent -is [System.Management.Automation.Language.DoWhileStatementAst] -or
$ast.Parent -is [System.Management.Automation.Language.DoUntilStatementAst]) -and
$ast.Parent.Condition -eq $ast)
{
return $true
}
$ast = $ast.Parent
}
return $false
}
function Get-ParentFunctionName
{
param ([System.Management.Automation.Language.Ast] $Ast)
$parent = $Ast.Parent
while ($null -ne $parent -and $parent -isnot [System.Management.Automation.Language.FunctionDefinitionAst])
{
$parent = $parent.Parent
}
if ($null -eq $parent)
{
return ''
}
else
{
return $parent.Name
}
}
function Get-CoverageCommandText
{
param ([System.Management.Automation.Language.Ast] $Ast)
$reportParentExtentTypes = @(
[System.Management.Automation.Language.ReturnStatementAst]
[System.Management.Automation.Language.ThrowStatementAst]
[System.Management.Automation.Language.AssignmentStatementAst]
[System.Management.Automation.Language.IfStatementAst]
)
$parent = Get-ParentNonPipelineAst -Ast $Ast
if ($null -ne $parent)
{
if ($parent -is [System.Management.Automation.Language.HashtableAst])
{
return Get-KeyValuePairText -HashtableAst $parent -ChildAst $Ast
}
elseif ($reportParentExtentTypes -contains $parent.GetType())
{
return $parent.Extent.Text
}
}
return $Ast.Extent.Text
}
function Get-ParentNonPipelineAst
{
param ([System.Management.Automation.Language.Ast] $Ast)
$parent = $null
if ($null -ne $Ast) { $parent = $Ast.Parent }
while ($parent -is [System.Management.Automation.Language.PipelineAst])
{
$parent = $parent.Parent
}
return $parent
}
function Get-KeyValuePairText
{
param (
[System.Management.Automation.Language.HashtableAst] $HashtableAst,
[System.Management.Automation.Language.Ast] $ChildAst
)
& $SafeCommands['Set-StrictMode'] -Off
foreach ($keyValuePair in $HashtableAst.KeyValuePairs)
{
if ($keyValuePair.Item2.PipelineElements -contains $ChildAst)
{
return '{0} = {1}' -f $keyValuePair.Item1.Extent.Text, $keyValuePair.Item2.Extent.Text
}
}
# This shouldn't happen, but just in case, default to the old output of just the expression.
return $ChildAst.Extent.Text
}
function Get-CoverageMissedCommands
{
param ([object[]] $CommandCoverage)
$CommandCoverage | & $SafeCommands['Where-Object'] { $_.Breakpoint.HitCount -eq 0 }
}
function Get-CoverageHitCommands
{
param ([object[]] $CommandCoverage)
$CommandCoverage | & $SafeCommands['Where-Object'] { $_.Breakpoint.HitCount -gt 0 }
}
function Get-CoverageReport
{
param ([object] $PesterState)
$totalCommandCount = $PesterState.CommandCoverage.Count
$missedCommands = @(Get-CoverageMissedCommands -CommandCoverage $PesterState.CommandCoverage | & $SafeCommands['Select-Object'] File, Line, Function, Command)
$hitCommands = @(Get-CoverageHitCommands -CommandCoverage $PesterState.CommandCoverage | & $SafeCommands['Select-Object'] File, Line, Function, Command)
$analyzedFiles = @($PesterState.CommandCoverage | & $SafeCommands['Select-Object'] -ExpandProperty File -Unique)
$fileCount = $analyzedFiles.Count
$executedCommandCount = $totalCommandCount - $missedCommands.Count
[pscustomobject] @{
NumberOfCommandsAnalyzed = $totalCommandCount
NumberOfFilesAnalyzed = $fileCount
NumberOfCommandsExecuted = $executedCommandCount
NumberOfCommandsMissed = $missedCommands.Count
MissedCommands = $missedCommands
HitCommands = $hitCommands
AnalyzedFiles = $analyzedFiles
}
}
function Show-CoverageReport
{
param ([object] $CoverageReport)
if ($null -eq $CoverageReport -or $CoverageReport.NumberOfCommandsAnalyzed -eq 0)
{
return
}
$totalCommandCount = $CoverageReport.NumberOfCommandsAnalyzed
$fileCount = $CoverageReport.NumberOfFilesAnalyzed
$executedPercent = ($CoverageReport.NumberOfCommandsExecuted / $CoverageReport.NumberOfCommandsAnalyzed).ToString("P2")
$commandPlural = $filePlural = ''
if ($totalCommandCount -gt 1) { $commandPlural = 's' }
if ($fileCount -gt 1) { $filePlural = 's' }
$commonParent = Get-CommonParentPath -Path $CoverageReport.AnalyzedFiles
$report = $CoverageReport.MissedCommands | & $SafeCommands['Select-Object'] -Property @(
@{ Name = 'File'; Expression = { Get-RelativePath -Path $_.File -RelativeTo $commonParent } }
'Function'
'Line'
'Command'
)
Write-Screen ''
Write-Screen 'Code coverage report:'
Write-Screen "Covered $executedPercent of $totalCommandCount analyzed command$commandPlural in $fileCount file$filePlural."
if ($CoverageReport.MissedCommands.Count -gt 0)
{
Write-Screen ''
Write-Screen 'Missed commands:'
$report | & $SafeCommands['Format-Table'] -AutoSize | & $SafeCommands['Out-String'] | Write-Screen
}
}
function Get-CommonParentPath
{
param ([string[]] $Path)
$pathsToTest = @(
$Path |
Normalize-Path |
& $SafeCommands['Select-Object'] -Unique
)
if ($pathsToTest.Count -gt 0)
{
$parentPath = & $SafeCommands['Split-Path'] -Path $pathsToTest[0] -Parent
while ($parentPath.Length -gt 0)
{
$nonMatches = $pathsToTest -notmatch "^$([regex]::Escape($parentPath))"
if ($nonMatches.Count -eq 0)
{
return $parentPath
}
else
{
$parentPath = & $SafeCommands['Split-Path'] -Path $parentPath -Parent
}
}
}
return [string]::Empty
}
function Get-RelativePath
{
param ( [string] $Path, [string] $RelativeTo )
return $Path -replace "^$([regex]::Escape("$RelativeTo$([System.IO.Path]::DirectorySeparatorChar)"))?"
}
function Normalize-Path
{
[CmdletBinding()]
param (
[Parameter(ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
[Alias('PSPath', 'FullName')]
[string[]] $Path
)
# Split-Path and Join-Path will replace any AltDirectorySeparatorChar instances with the DirectorySeparatorChar
# (Even if it's not the one that the split / join happens on.) So splitting / rejoining a path will give us
# consistent separators for later string comparison.
process
{
if ($null -ne $Path)
{
foreach ($p in $Path)
{
$normalizedPath = & $SafeCommands['Split-Path'] $p -Leaf
if ($normalizedPath -ne $p)
{
$parent = & $SafeCommands['Split-Path'] $p -Parent
$normalizedPath = & $SafeCommands['Join-Path'] $parent $normalizedPath
}
$normalizedPath
}
}
}
}
================================================
FILE: DbgShell/x64/DbgShellTest/Pester/Functions/Describe.Tests.ps1
================================================
Set-StrictMode -Version Latest
Describe 'Testing Describe' {
It 'Has a non-mandatory fixture parameter which throws the proper error message if missing' {
$command = Get-Command Describe -Module Pester
$command | Should Not Be $null
$parameter = $command.Parameters['Fixture']
$parameter | Should Not Be $null
# Some environments (Nano/CoreClr) don't have all the type extensions
$attribute = $parameter.Attributes | Where-Object { $_ -is [System.Management.Automation.ParameterAttribute] }
$isMandatory = $null -ne $attribute -and $attribute.Mandatory
$isMandatory | Should Be $false
{ Describe Bogus } | Should Throw 'No test script block is provided'
}
}
================================================
FILE: DbgShell/x64/DbgShellTest/Pester/Functions/Describe.ps1
================================================
function Describe {
<#
.SYNOPSIS
Creates a logical group of tests.
.DESCRIPTION
Creates a logical group of tests. All Mocks and TestDrive 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.
.PARAMETER Name
The name of the test group. This is often an expressive phrase describing
the scenario being tested.
.PARAMETER 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.
.PARAMETER 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.
.EXAMPLE
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"
}
}
.LINK
It
Context
Invoke-Pester
about_Should
about_Mocking
about_TestDrive
#>
param(
[Parameter(Mandatory = $true, Position = 0)]
[string] $Name,
[Alias('Tags')]
[string[]] $Tag=@(),
[Parameter(Position = 1)]
[ValidateNotNull()]
[ScriptBlock] $Fixture = $(Throw "No test script block is provided. (Have you put the open curly brace on the next line?)")
)
if ($null -eq (& $SafeCommands['Get-Variable'] -Name Pester -ValueOnly -ErrorAction $script:IgnoreErrorPreference))
{
# User has executed a test script directly instead of calling Invoke-Pester
$Pester = New-PesterState -Path (& $SafeCommands['Resolve-Path'] .) -TestNameFilter $null -TagFilter @() -SessionState $PSCmdlet.SessionState
$script:mockTable = @{}
}
if($Pester.TestNameFilter-and -not ($Pester.TestNameFilter | & $SafeCommands['Where-Object'] { $Name -like $_ }))
{
#skip this test
return
}
#TODO add test to test tags functionality
if($Pester.TagFilter -and @(& $SafeCommands['Compare-Object'] $Tag $Pester.TagFilter -IncludeEqual -ExcludeDifferent).count -eq 0) {return}
if($Pester.ExcludeTagFilter -and @(& $SafeCommands['Compare-Object'] $Tag $Pester.ExcludeTagFilter -IncludeEqual -ExcludeDifferent).count -gt 0) {return}
$Pester.EnterDescribe($Name)
$Pester.CurrentDescribe | Write-Describe
$testDriveAdded = $false
try
{
New-TestDrive
$testDriveAdded = $true
Add-SetupAndTeardown -ScriptBlock $Fixture
Invoke-TestGroupSetupBlocks -Scope $pester.Scope
do
{
$null = & $Fixture
} until ($true)
}
catch
{
$firstStackTraceLine = $_.InvocationInfo.PositionMessage.Trim() -split '\r?\n' | & $SafeCommands['Select-Object'] -First 1
$Pester.AddTestResult('Error occurred in Describe block', "Failed", $null, $_.Exception.Message, $firstStackTraceLine, $null, $null, $_)
$Pester.TestResult[-1] | Write-PesterResult
}
finally
{
Invoke-TestGroupTeardownBlocks -Scope $pester.Scope
if ($testDriveAdded) { Remove-TestDrive }
Clear-SetupAndTeardown
Exit-MockScope
$Pester.LeaveDescribe()
}
}
function Assert-DescribeInProgress
{
param ($CommandName)
if ($null -eq $Pester -or [string]::IsNullOrEmpty($Pester.CurrentDescribe))
{
throw "The $CommandName command may only be used inside a Describe block."
}
}
================================================
FILE: DbgShell/x64/DbgShellTest/Pester/Functions/GlobalMock-A.Tests.ps1
================================================
# This script exists to create and mock a global function, then exit. The actual behavior
# that we need to test is covered in GlobalMock-B.Tests.ps1, where we make sure that the
# global function was properly restored in its scope.
$functionName = '01c1a57716fe4005ac1a7bf216f38ad0'
if (Test-Path Function:\$functionName)
{
Remove-Item Function:\$functionName -Force -ErrorAction Stop
}
function global:01c1a57716fe4005ac1a7bf216f38ad0
{
return 'Original Function'
}
function script:Testing
{
return 'Script scope'
}
Describe 'Mocking Global Functions - Part One' {
Mock $functionName {
return 'Mocked'
}
It 'Mocks the global function' {
& $functionName | Should Be 'Mocked'
}
}
================================================
FILE: DbgShell/x64/DbgShellTest/Pester/Functions/GlobalMock-B.Tests.ps1
================================================
# This test depends on some state set up in GlobalMock-A.Tests.ps1. The behavior we're verifying
# is that global functions that have been mocked are still properly set up even after the test
# script exits its scope.
$functionName = '01c1a57716fe4005ac1a7bf216f38ad0'
try
{
Describe 'Mocking Global Functions - Part Two' {
It 'Restored the global function properly' {
$globalFunctionExists = Test-Path Function:\global:$functionName
$globalFunctionExists | Should Be $true
& $functionName | Should Be 'Original Function'
}
}
}
finally
{
if (Test-Path Function:\$functionName)
{
Remove-Item Function:\$functionName -Force
}
}
================================================
FILE: DbgShell/x64/DbgShellTest/Pester/Functions/In.Tests.ps1
================================================
Set-StrictMode -Version Latest
InModuleScope Pester {
Describe "the In statement" {
Setup -Dir "test_path"
It "executes a command in that directory" {
In "$TestDrive" -Execute { "" | Out-File "test_file" }
"$TestDrive\test_file" | Should Exist
}
It "updates the `$pwd variable when executed" {
In "$TestDrive\test_path" -Execute { $env:Pester_Test=$pwd }
$env:Pester_Test | Should Match "test_path"
$env:Pester_Test=""
}
}
}
================================================
FILE: DbgShell/x64/DbgShellTest/Pester/Functions/In.ps1
================================================
function In {
<#
.SYNOPSIS
A convenience function that executes a script from a specified path.
.DESCRIPTION
Before the script block passed to the execute parameter is invoked,
the current location is set to the path specified. Once the script
block has been executed, the location will be reset to the location
the script was in prior to calling In.
.PARAMETER Path
The path that the execute block will be executed in.
.PARAMETER execute
The script to be executed in the path provided.
#>
param(
$path,
[ScriptBlock] $execute
)
Assert-DescribeInProgress -CommandName In
$old_pwd = $pwd
& $SafeCommands['Push-Location'] $path
$pwd = $path
try {
& $execute
} finally {
& $SafeCommands['Pop-Location']
$pwd = $old_pwd
}
}
================================================
FILE: DbgShell/x64/DbgShellTest/Pester/Functions/InModuleScope.Tests.ps1
================================================
Set-StrictMode -Version Latest
Describe "Module scope separation" {
Context "When users define variables with the same name as Pester parameters" {
$test = "This is a test."
It "does not hide user variables" {
$test | Should Be 'This is a test.'
}
}
It "Does not expose Pester implementation details to the SUT" {
# Changing the Get-PesterResult function's name would cause this test to pass artificially.
# TODO : come up with a better way of verifying that only the desired commands from the Pester
# module are visible to the SUT.
(Get-Item function:\Get-PesterResult -ErrorAction SilentlyContinue) | Should Be $null
}
}
Describe "Executing test code inside a module" {
New-Module -Name TestModule {
function InternalFunction { 'I am the internal function' }
function PublicFunction { InternalFunction }
Export-ModuleMember -Function PublicFunction
} | Import-Module -Force
It "Cannot call module internal functions, by default" {
{ InternalFunction } | Should Throw
}
InModuleScope TestModule {
It "Can call module internal functions using InModuleScope" {
InternalFunction | Should Be 'I am the internal function'
}
It "Can mock functions inside the module without using Mock -ModuleName" {
Mock InternalFunction { 'I am the mock function.' }
InternalFunction | Should Be 'I am the mock function.'
}
}
Remove-Module TestModule -Force
}
================================================
FILE: DbgShell/x64/DbgShellTest/Pester/Functions/InModuleScope.ps1
================================================
function InModuleScope
{
<#
.SYNOPSIS
Allows you to execute parts of a test script within the
scope of a PowerShell script module.
.DESCRIPTION
By injecting some test code into the scope of a PowerShell
script 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.
.PARAMETER 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.
.PARAMETER ScriptBlock
The code to be executed within the script module.
.EXAMPLE
# 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.
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string]
$ModuleName,
[Parameter(Mandatory = $true)]
[scriptblock]
$ScriptBlock
)
if ($null -eq (& $SafeCommands['Get-Variable'] -Name Pester -ValueOnly -ErrorAction $script:IgnoreErrorPreference))
{
# User has executed a test script directly instead of calling Invoke-Pester
$Pester = New-PesterState -Path (& $SafeCommands['Resolve-Path'] .) -TestNameFilter $null -TagFilter @() -ExcludeTagFilter @() -SessionState $PSCmdlet.SessionState
$script:mockTable = @{}
}
$module = Get-ScriptModule -ModuleName $ModuleName -ErrorAction Stop
$originalState = $Pester.SessionState
$originalScriptBlockScope = Get-ScriptBlockScope -ScriptBlock $ScriptBlock
try
{
$Pester.SessionState = $module.SessionState
Set-ScriptBlockScope -ScriptBlock $ScriptBlock -SessionState $module.SessionState
do
{
& $ScriptBlock
} until ($true)
}
finally
{
$Pester.SessionState = $originalState
Set-ScriptBlockScope -ScriptBlock $ScriptBlock -SessionStateInternal $originalScriptBlockScope
}
}
function Get-ScriptModule
{
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string] $ModuleName
)
try
{
$modules = @(& $SafeCommands['Get-Module'] -Name $ModuleName -All -ErrorAction Stop)
}
catch
{
throw "No module named '$ModuleName' is currently loaded."
}
$scriptModules = @($modules | & $SafeCommands['Where-Object'] { $_.ModuleType -eq 'Script' })
if ($scriptModules.Count -gt 1)
{
throw "Multiple Script modules named '$ModuleName' are currently loaded. Make sure to remove any extra copies of the module from your session before testing."
}
if ($scriptModules.Count -eq 0)
{
$actualTypes = @(
$modules |
& $SafeCommands['Where-Object'] { $_.ModuleType -ne 'Script' } |
& $SafeCommands['Select-Object'] -ExpandProperty ModuleType -Unique
)
$actualTypes = $actualTypes -join ', '
throw "Module '$ModuleName' is not a Script module. Detected modules of the following types: '$actualTypes'"
}
return $scriptModules[0]
}
================================================
FILE: DbgShell/x64/DbgShellTest/Pester/Functions/It.Tests.ps1
================================================
Set-StrictMode -Version Latest
InModuleScope Pester {
Describe 'Get-PesterResult' {
}
Describe 'It - Implementation' {
$testState = New-PesterState -Path $TestDrive
It 'Throws an error if It is called outside of Describe' {
$scriptBlock = { ItImpl -Pester $testState 'Tries to enter a test without entering a Describe first' { } }
$scriptBlock | Should Throw 'The It command may only be used inside a Describe block.'
}
$testState.EnterDescribe('Mocked Describe')
# We call EnterTest() directly here because if we actually nest calls to ItImpl, the outer call will catch the error we're trying to
# verify with Should Throw. (Another option would be to nest the ItImpl calls, and look for a failed test result in $testState.)
$testState.EnterTest('Outer Test')
It 'Throws an error if you try to enter It from inside another It' {
$scriptBlock = {
ItImpl -Pester $testState 'Enters the second It' { }
}
$scriptBlock | Should Throw 'You already are in It, you cannot enter It twice'
}
$testState.LeaveTest()
It 'Throws an error if you fail to pass in a test block' {
$scriptBlock = { ItImpl -Pester $testState 'Some Name' }
$scriptBlock | Should Throw 'No test script block is provided. (Have you put the open curly brace on the next line?)'
}
It 'Does not throw an error if It is called inside a Describe, and adds a successful test result.' {
$scriptBlock = { ItImpl -Pester $testState 'Enters an It block inside a Describe' { } }
$scriptBlock | Should Not Throw
$testState.TestResult[-1].Passed | Should Be $true
$testState.TestResult[-1].ParameterizedSuiteName | Should BeNullOrEmpty
}
It 'Does not throw an error if the -Pending switch is used, and no script block is passed' {
$scriptBlock = { ItImpl -Pester $testState 'Some Name' -Pending }
$scriptBlock | Should Not Throw
}
It 'Does not throw an error if the -Skip switch is used, and no script block is passed' {
$scriptBlock = { ItImpl -Pester $testState 'Some Name' -Skip }
$scriptBlock | Should Not Throw
}
It 'Does not throw an error if the -Ignore switch is used, and no script block is passed' {
$scriptBlock = { ItImpl -Pester $testState 'Some Name' -Ignore }
$scriptBlock | Should Not Throw
}
It 'Creates a pending test for an empty (whitespace and comments only) script block' {
$scriptBlock = {
# Single-Line comment
<#
Multi-
Line-
Comment
#>
}
{ ItImpl -Pester $testState 'Some Name' $scriptBlock } | Should Not Throw
$testState.TestResult[-1].Result | Should Be 'Pending'
}
It 'Adds a failed test if the script block throws an exception' {
$scriptBlock = {
ItImpl -Pester $testState 'Enters an It block inside a Describe' {
throw 'I am a failed test'
}
}
$scriptBlock | Should Not Throw
$testState.TestResult[-1].Passed | Should Be $false
$testState.TestResult[-1].ParameterizedSuiteName | Should BeNullOrEmpty
$testState.TestResult[-1].FailureMessage | Should Be 'I am a failed test'
}
$script:counterNameThatIsReallyUnlikelyToConflictWithAnything = 0
It 'Calls the output script block for each test' {
$outputBlock = { $script:counterNameThatIsReallyUnlikelyToConflictWithAnything++ }
ItImpl -Pester $testState 'Does something' -OutputScriptBlock $outputBlock { }
ItImpl -Pester $testState 'Does something' -OutputScriptBlock $outputBlock { }
ItImpl -Pester $testState 'Does something' -OutputScriptBlock $outputBlock { }
$script:counterNameThatIsReallyUnlikelyToConflictWithAnything | Should Be 3
}
Remove-Variable -Scope Script -Name counterNameThatIsReallyUnlikelyToConflictWithAnything
Context 'Parameterized Tests' {
# be careful about variable naming here; with InModuleScope Pester, we can create the same types of bugs that the v3
# scope isolation fixed for everyone else. (Naming this variable $testCases gets hidden later by parameters of the
# same name in It.)
$cases = @(
@{ a = 1; b = 1; expectedResult = 2}
@{ a = 1; b = 2; expectedResult = 3}
@{ a = 5; b = 4; expectedResult = 9}
@{ a = 1; b = 1; expectedResult = 'Intentionally failed' }
)
$suiteName = 'Adds <a> and <b> to get <expectedResult>. <Bogus> is not a parameter.'
ItImpl -Pester $testState -Name $suiteName -TestCases $cases {
param ($a, $b, $expectedResult)
($a + $b) | Should Be $expectedResult
}
It 'Creates test result records with the ParameterizedSuiteName property set' {
for ($i = -1; $i -ge -4; $i--)
{
$testState.TestResult[$i].ParameterizedSuiteName | Should Be $suiteName
}
}
It 'Expands parameters in parameterized test suite names' {
for ($i = -1; $i -ge -4; $i--)
{
$expectedName = "Adds $($cases[$i]['a']) and $($cases[$i]['b']) to get $($cases[$i]['expectedResult']). <Bogus> is not a parameter."
$testState.TestResult[$i].Name | Should Be $expectedName
}
}
It 'Logs the proper successes and failures' {
$testState.TestResult[-1].Passed | Should Be $false
for ($i = -2; $i -ge -4; $i--)
{
$testState.TestResult[$i].Passed | Should Be $true
}
}
}
}
Describe 'Get-OrderedParameterDictionary' {
$_testScriptBlock = {
param (
$1, $c, $0, $z, $a, ${Something.Really/Weird }
)
}
$hashtable = @{
'1' = 'One'
'0' = 'Zero'
z = 'Z'
a = 'A'
c = 'C'
'Something.Really/Weird ' = 'Weird'
}
$dictionary = Get-OrderedParameterDictionary -ScriptBlock $_testScriptBlock -Dictionary $hashtable
It 'Reports keys and values in the same order as the param block' {
($dictionary.Keys -join ',') |
Should Be '1,c,0,z,a,Something.Really/Weird '
($dictionary.Values -join ',') |
Should Be 'One,C,Zero,Z,A,Weird'
}
}
Describe 'Remove-Comments' {
It 'Removes single line comments' {
Remove-Comments -Text 'code #comment' | Should Be 'code '
}
It 'Removes multi line comments' {
Remove-Comments -Text 'code <#comment
comment#> code' | Should Be 'code code'
}
}
}
$thisScriptRegex = [regex]::Escape($MyInvocation.MyCommand.Path)
Describe 'Get-PesterResult' {
$getPesterResult = InModuleScope Pester { ${function:Get-PesterResult} }
Context 'failed tests in Tests file' {
#the $script scriptblock below is used as a position marker to determine
#on which line the test failed.
$errorRecord = $null
try{'something' | should be 'nothing'}catch{ $errorRecord=$_} ; $script={}
$result = & $getPesterResult 0 $errorRecord
It 'records the correct stack line number' {
$result.Stacktrace | should match "at line: $($script.startPosition.StartLine) in $thisScriptRegex"
}
It 'records the correct error record' {
$result.ErrorRecord -is [System.Management.Automation.ErrorRecord] | Should be $true
$result.ErrorRecord.Exception.Message | Should match 'Expected: {nothing}'
}
}
It 'Does not modify the error message from the original exception' {
$object = New-Object psobject
$message = 'I am an error.'
Add-Member -InputObject $object -MemberType ScriptMethod -Name ThrowSomething -Value { throw $message }
$errorRecord = $null
try { $object.ThrowSomething() } catch { $errorRecord = $_ }
$pesterResult = & $getPesterResult 0 $errorRecord
$pesterResult.FailureMessage | Should Be $errorRecord.Exception.Message
}
Context 'failed tests in another file' {
$errorRecord = $null
$testPath = Join-Path $TestDrive test.ps1
$escapedTestPath = [regex]::Escape($testPath)
Set-Content -Path $testPath -Value "`r`n'One' | Should Be 'Two'"
try
{
& $testPath
}
catch
{
$errorRecord = $_
}
$result = & $getPesterResult 0 $errorRecord
It 'records the correct stack line number' {
$result.Stacktrace | should match "at line: 2 in $escapedTestPath"
}
It 'records the correct error record' {
$result.ErrorRecord -is [System.Management.Automation.ErrorRecord] | Should be $true
$result.ErrorRecord.Exception.Message | Should match 'Expected: {Two}'
}
}
}
================================================
FILE: DbgShell/x64/DbgShellTest/Pester/Functions/It.ps1
================================================
function It {
<#
.SYNOPSIS
Validates the results of a test inside of a Describe block.
.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.
.PARAMETER Name
An expressive phrase describing the expected test outcome.
.PARAMETER 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.
.PARAMETER 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.
.PARAMETER 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. Use the Strict parameter
of Invoke-Pester to force all skipped tests to fail.
.PARAMETER 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 TestCases 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 TestCases hashtables.)
.EXAMPLE
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
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 <a> and <b> to get <expectedResult>' -TestCases $testCases {
param ($a, $b, $expectedResult)
$sum = Add-Numbers $a $b
$sum | Should Be $expectedResult
}
}
.LINK
Describe
Context
about_should
#>
[CmdletBinding(DefaultParameterSetName = 'Normal')]
param(
[Parameter(Mandatory = $true, Position = 0)]
[string]$name,
[Parameter(Position = 1)]
[ScriptBlock] $test = {},
[System.Collections.IDictionary[]] $TestCases,
[Parameter(ParameterSetName = 'Pending')]
[Switch] $Pending,
[Parameter(ParameterSetName = 'Skip')]
[Alias('Ignore')]
[Switch] $Skip
)
ItImpl -Pester $pester -OutputScriptBlock ${function:Write-PesterResult} @PSBoundParameters
}
function ItImpl
{
[CmdletBinding(DefaultParameterSetName = 'Normal')]
param(
[Parameter(Mandatory = $true, Position=0)]
[string]$name,
[Parameter(Position = 1)]
[ScriptBlock] $test,
[System.Collections.IDictionary[]] $TestCases,
[Parameter(ParameterSetName = 'Pending')]
[Switch] $Pending,
[Parameter(ParameterSetName = 'Skip')]
[Alias('Ignore')]
[Switch] $Skip,
$Pester,
[scriptblock] $OutputScriptBlock
)
Assert-DescribeInProgress -CommandName It
# Jumping through hoops to make strict mode happy.
if ($PSCmdlet.ParameterSetName -ne 'Skip') { $Skip = $false }
if ($PSCmdlet.ParameterSetName -ne 'Pending') { $Pending = $false }
#unless Skip or Pending is specified you must specify a ScriptBlock to the Test parameter
if (-not ($PSBoundParameters.ContainsKey('test') -or $Skip -or $Pending))
{
throw 'No test script block is provided. (Have you put the open curly brace on the next line?)'
}
#the function is called with Pending or Skipped set the script block if needed
if ($null -eq $test) { $test = {} }
#mark empty Its as Pending
#[String]::IsNullOrWhitespace is not available in .NET version used with PowerShell 2
if ($PSCmdlet.ParameterSetName -eq 'Normal' -and
[String]::IsNullOrEmpty((Remove-Comments $test.ToString()) -replace "\s"))
{
$Pending = $true
}
$pendingSkip = @{}
if ($PSCmdlet.ParameterSetName -eq 'Skip')
{
$pendingSkip['Skip'] = $Skip
}
else
{
$pendingSkip['Pending'] = $Pending
}
if ($null -ne $TestCases -and $TestCases.Count -gt 0)
{
foreach ($testCase in $TestCases)
{
$expandedName = [regex]::Replace($name, '<([^>]+)>', {
$capture = $args[0].Groups[1].Value
if ($testCase.Contains($capture))
{
$testCase[$capture]
}
else
{
"<$capture>"
}
})
$splat = @{
Name = $expandedName
Scriptblock = $test
Parameters = $testCase
ParameterizedSuiteName = $name
OutputScriptBlock = $OutputScriptBlock
}
Invoke-Test @splat @pendingSkip
}
}
else
{
Invoke-Test -Name $name -ScriptBlock $test @pendingSkip -OutputScriptBlock $OutputScriptBlock
}
}
function Invoke-Test
{
[CmdletBinding(DefaultParameterSetName = 'Normal')]
param (
[Parameter(Mandatory = $true)]
[string] $Name,
[Parameter(Mandatory = $true)]
[ScriptBlock] $ScriptBlock,
[scriptblock] $OutputScriptBlock,
[System.Collections.IDictionary] $Parameters,
[string] $ParameterizedSuiteName,
[Parameter(ParameterSetName = 'Pending')]
[Switch] $Pending,
[Parameter(ParameterSetName = 'Skip')]
[Alias('Ignore')]
[Switch] $Skip
)
if ($null -eq $Parameters) { $Parameters = @{} }
$Pester.EnterTest($Name)
try
{
if ($Skip)
{
$Pester.AddTestResult($Name, "Skipped", $null)
}
elseif ($Pending)
{
$Pester.AddTestResult($Name, "Pending", $null)
}
else
{
& $SafeCommands['Write-Progress'] -Activity "Running test '$Name'" -Status Processing
$errorRecord = $null
try
{
Invoke-TestCaseSetupBlocks
do
{
$null = & $ScriptBlock @Parameters
} until ($true)
}
catch
{
$errorRecord = $_
}
finally
{
#guarantee that the teardown action will run and prevent it from failing the whole suite
try
{
if (-not ($Skip -or $Pending))
{
Invoke-TestCaseTeardownBlocks
}
}
catch
{
$errorRecord = $_
}
}
$result = Get-PesterResult -ErrorRecord $errorRecord
$orderedParameters = Get-OrderedParameterDictionary -ScriptBlock $ScriptBlock -Dictionary $Parameters
$Pester.AddTestResult( $result.name, $result.Result, $null, $result.FailureMessage, $result.StackTrace, $ParameterizedSuiteName, $orderedParameters, $result.ErrorRecord )
& $SafeCommands['Write-Progress'] -Activity "Running test '$Name'" -Completed -Status Processing
}
}
finally
{
Exit-MockScope
$Pester.LeaveTest()
}
if ($null -ne $OutputScriptBlock)
{
$Pester.testresult[-1] | & $OutputScriptBlock
}
}
function Get-PesterResult {
param(
[Nullable[TimeSpan]] $Time,
[System.Management.Automation.ErrorRecord] $ErrorRecord
)
$testResult = @{
name = $name
time = $time
failureMessage = ""
stackTrace = ""
ErrorRecord = $null
success = $false
result = "Failed"
};
if(-not $ErrorRecord)
{
$testResult.Result = "Passed"
$testResult.success = $true
return $testResult
}
if ($ErrorRecord.FullyQualifiedErrorID -eq 'PesterAssertionFailed')
{
# we use TargetObject to pass structured information about the error.
$details = $ErrorRecord.TargetObject
$failureMessage = $details.Message
$file = $details.File
$line = $details.Line
$lineText = "`n$line`: $($details.LineText)"
}
elseif ($ErrorRecord.FullyQualifiedErrorId -eq 'PesterTestInconclusive')
{
# we use TargetObject to pass structured information about the error.
$details = $ErrorRecord.TargetObject
$failureMessage = $details.Message
$file = $details.File
$line = $details.Line
$lineText = "`n$line`: $($details.LineText)"
$testResult.Result = 'Inconclusive'
}
else
{
$failureMessage = $ErrorRecord.ToString()
$file = $ErrorRecord.InvocationInfo.ScriptName
$line = $ErrorRecord.InvocationInfo.ScriptLineNumber
$lineText = ''
}
$testResult.failureMessage = $failureMessage
$testResult.stackTrace = "at line: $line in ${file}${lineText}"
$testResult.ErrorRecord = $ErrorRecord
return $testResult
}
function Remove-Comments ($Text)
{
$text -replace "(?s)(<#.*#>)" -replace "\#.*"
}
function Get-OrderedParameterDictionary
{
[OutputType([System.Collections.IDictionary])]
param (
[scriptblock] $ScriptBlock,
[System.Collections.IDictionary] $Dictionary
)
$parameters = Get-ParameterDictionary -ScriptBlock $ScriptBlock
$orderedDictionary = & $SafeCommands['New-Object'] System.Collections.Specialized.OrderedDictionary
foreach ($parameterName in $parameters.Keys)
{
$value = $null
if ($Dictionary.ContainsKey($parameterName))
{
$value = $Dictionary[$parameterName]
}
$orderedDictionary[$parameterName] = $value
}
return $orderedDictionary
}
function Get-ParameterDictionary
{
param (
[scriptblock] $ScriptBlock
)
$guid = [guid]::NewGuid().Guid
try
{
& $SafeCommands['Set-Content'] function:\$guid $ScriptBlock
$metadata = [System.Management.Automation.CommandMetadata](& $SafeCommands['Get-Command'] -Name $guid -CommandType Function)
return $metadata.Parameters
}
finally
{
if (& $SafeCommands['Test-Path'] function:\$guid) { & $SafeCommands['Remove-Item'] function:\$guid }
}
}
================================================
FILE: DbgShell/x64/DbgShellTest/Pester/Functions/Mock.Tests.ps1
================================================
Set-StrictMode -Version Latest
function FunctionUnderTest
{
[CmdletBinding()]
param (
[Parameter(Mandatory=$false)]
[string]
$param1
)
return "I am a real world test"
}
function FunctionUnderTestWithoutParams([string]$param1) {
return "I am a real world test with no params"
}
filter FilterUnderTest { $_ }
function CommonParamFunction (
[string] ${Uncommon},
[switch]
${Verbose},
[switch]
${Debug},
[System.Management.Automation.ActionPreference]
${ErrorAction},
[System.Management.Automation.ActionPreference]
${WarningAction},
[System.String]
${ErrorVariable},
[System.String]
${WarningVariable},
[System.String]
${OutVariable},
[System.Int32]
${OutBuffer} ){
return "Please strip me of my common parameters. They are far too common."
}
function PipelineInputFunction {
param(
[Parameter(ValueFromPipeline=$True)]
[int]$PipeInt1,
[Parameter(ValueFromPipeline=$True)]
[int[]]$PipeInt2,
[Parameter(ValueFromPipeline=$True)]
[string]$PipeStr,
[Parameter(ValueFromPipelineByPropertyName=$True)]
[int]$PipeIntProp,
[Parameter(ValueFromPipelineByPropertyName=$True)]
[int[]]$PipeArrayProp,
[Parameter(ValueFromPipelineByPropertyName=$True)]
[string]$PipeStringProp
)
begin{
$p = 0
}
process {
foreach($i in $input)
{
$p += 1
write-output @{
index=$p;
val=$i;
PipeInt1=$PipeInt1;
PipeInt2=$PipeInt2;
PipeStr=$PipeStr;
PipeIntProp=$PipeIntProp;
PipeArrayProp=$PipeArrayProp;
PipeStringProp=$PipeStringProp;
}
}
}
}
Describe "When calling Mock on existing function" {
Mock FunctionUnderTest { return "I am the mock test that was passed $param1"}
$result = FunctionUnderTest "boundArg"
It "Should rename function under test" {
$renamed = (Test-Path function:PesterIsMocking_FunctionUnderTest)
$renamed | Should Be $true
}
It "Should Invoke the mocked script" {
$result | Should Be "I am the mock test that was passed boundArg"
}
}
Describe "When the caller mocks a command Pester uses internally" {
Mock Write-Host { }
Context "Context run when Write-Host is mocked" {
It "does not make extra calls to the mocked command" {
Write-Host 'Some String'
Assert-MockCalled 'Write-Host' -Exactly 1
}
It "retains the correct mock count after the first test completes" {
Assert-MockCalled 'Write-Host' -Exactly 1
}
}
}
Describe "When calling Mock on existing cmdlet" {
Mock Get-Process {return "I am not Get-Process"}
$result=Get-Process
It "Should Invoke the mocked script" {
$result | Should Be "I am not Get-Process"
}
It 'Should not resolve $args to the parent scope' {
{ $args = 'From', 'Parent', 'Scope'; Get-Process SomeName } | Should Not Throw
}
}
Describe 'When calling Mock on an alias' {
$originalPath = $env:path
try
{
# Our TeamCity server has a dir.exe on the system path, and PowerShell v2 apparently finds that instead of the PowerShell alias first.
# This annoying bit of code makes sure our test works as intended even when this is the case.
$dirExe = Get-Command dir -CommandType Application -ErrorAction SilentlyContinue
if ($null -ne $dirExe)
{
foreach ($app in $dirExe)
{
$parent = (Split-Path $app.Path -Parent).TrimEnd('\')
$pattern = "^$([regex]::Escape($parent))\\?"
$env:path = $env:path -split ';' -notmatch $pattern -join ';'
}
}
Mock dir {return 'I am not dir'}
$result = dir
It 'Should Invoke the mocked script' {
$result | Should Be 'I am not dir'
}
}
finally
{
$env:path = $originalPath
}
}
Describe 'When calling Mock on an alias that refers to a function Pester can''t see' {
It 'Mocks the aliased command successfully' {
# This function is defined in a non-global scope; code inside the Pester module can't see it directly.
function orig {'orig'}
New-Alias 'ali' orig
ali | Should Be 'orig'
{ mock ali {'mck'} } | Should Not Throw
ali | Should Be 'mck'
}
}
Describe 'When calling Mock on a filter' {
Mock FilterUnderTest {return 'I am not FilterUnderTest'}
$result = 'Yes I am' | FilterUnderTest
It 'Should Invoke the mocked script' {
$result | Should Be 'I am not FilterUnderTest'
}
}
Describe 'When calling Mock on an external script' {
$ps1File = New-Item 'TestDrive:\tempExternalScript.ps1' -ItemType File -Force
$ps1File | Set-Content -Value "'I am tempExternalScript.ps1'"
Mock 'TestDrive:\tempExternalScript.ps1' {return 'I am not tempExternalScript.ps1'}
<#
# Invoking the script using its absolute path is not supported
$result = TestDrive:\tempExternalScript.ps1
It 'Should Invoke the absolute-path-qualified mocked script using just the script name' {
$result | Should Be 'I am not tempExternalScript.ps1'
}
$result = & TestDrive:\tempExternalScript.ps1
It 'Should Invoke the absolute-path-qualified mocked script using the command-invocation operator (&)' {
$result | Should Be 'I am not tempExternalScript.ps1'
}
$result = . TestDrive:\tempExternalScript.ps1
It 'Should Invoke the absolute-path-qualified mocked script using dot source notation' {
$result | Should Be 'I am not tempExternalScript.ps1'
}
#>
Push-Location TestDrive:\
try
{
$result = tempExternalScript.ps1
It 'Should Invoke the mocked script using just the script name' {
$result | Should Be 'I am not tempExternalScript.ps1'
}
$result = & tempExternalScript.ps1
It 'Should Invoke the mocked script using the command-invocation operator' {
#the command invocation operator is (&). Moved this to comment because it breaks the continuous builds.
#there is issue for this on GH
$result | Should Be 'I am not tempExternalScript.ps1'
}
$result = . tempExternalScript.ps1
It 'Should Invoke the mocked script using dot source notation' {
$result | Should Be 'I am not tempExternalScript.ps1'
}
<#
# Invoking the script using only its relative path is not supported
$result = .\tempExternalScript.ps1
It 'Should Invoke the relative-path-qualified mocked script' {
$result | Should Be 'I am not tempExternalScript.ps1'
}
#>
}
finally
{
Pop-Location
}
Remove-Item $ps1File -Force -ErrorAction SilentlyContinue
}
Describe 'When calling Mock on an application command' {
Mock schtasks.exe {return 'I am not schtasks.exe'}
$result = schtasks.exe
It 'Should Invoke the mocked script' {
$result | Should Be 'I am not schtasks.exe'
}
}
Describe "When calling Mock in the Describe block" {
Mock Out-File {return "I am not Out-File"}
It "Should mock Out-File successfully" {
$outfile = "test" | Out-File "TestDrive:\testfile.txt"
$outfile | Should Be "I am not Out-File"
}
}
Describe "When calling Mock on existing cmdlet to handle pipelined input" {
Mock Get-ChildItem {
if($_ -eq 'a'){
return "AA"
}
if($_ -eq 'b'){
return "BB"
}
}
$result = ''
"a", "b" | Get-ChildItem | % { $result += $_ }
It "Should process the pipeline in the mocked script" {
$result | Should Be "AABB"
}
}
Describe "When calling Mock on existing cmdlet with Common params" {
Mock CommonParamFunction
$result=[string](Get-Content function:\CommonParamFunction)
It "Should strip verbose" {
$result.contains("`${Verbose}") | Should Be $false
}
It "Should strip Debug" {
$result.contains("`${Debug}") | Should Be $false
}
It "Should strip ErrorAction" {
$result.contains("`${ErrorAction}") | Should Be $false
}
It "Should strip WarningAction" {
$result.contains("`${WarningAction}") | Should Be $false
}
It "Should strip ErrorVariable" {
$result.contains("`${ErrorVariable}") | Should Be $false
}
It "Should strip WarningVariable" {
$result.contains("`${WarningVariable}") | Should Be $false
}
It "Should strip OutVariable" {
$result.contains("`${OutVariable}") | Should Be $false
}
It "Should strip OutBuffer" {
$result.contains("`${OutBuffer}") | Should Be $false
}
It "Should not strip an Uncommon param" {
$result.contains("`${Uncommon}") | Should Be $true
}
}
Describe "When calling Mock on non-existing function" {
try{
Mock NotFunctionUnderTest {return}
} Catch {
$result=$_
}
It "Should throw correct error" {
$result.Exception.Message | Should Be "Could not find command NotFunctionUnderTest"
}
}
Describe 'When calling Mock, StrictMode is enabled, and variables are used in the ParameterFilter' {
Set-StrictMode -Version Latest
$result = $null
$testValue = 'test'
try
{
Mock FunctionUnderTest { 'I am the mock' } -ParameterFilter { $param1 -eq $testValue }
}
catch
{
$result = $_
}
It 'Does not throw an error when testing the parameter filter' {
$result | Should Be $null
}
It 'Calls the mock properly' {
FunctionUnderTest $testValue | Should Be 'I am the mock'
}
It 'Properly asserts the mock was called when there is a variable in the parameter filter' {
Assert-MockCalled FunctionUnderTest -Exactly 1 -ParameterFilter { $param1 -eq $testValue }
}
}
Describe "When calling Mock on existing function without matching bound params" {
Mock FunctionUnderTest {return "fake results"} -parameterFilter {$param1 -eq "test"}
$result=FunctionUnderTest "badTest"
It "Should redirect to real function" {
$result | Should Be "I am a real world test"
}
}
Describe "When calling Mock on existing function with matching bound params" {
Mock FunctionUnderTest {return "fake results"} -parameterFilter {$param1 -eq "badTest"}
$result=FunctionUnderTest "badTest"
It "Should return mocked result" {
$result | Should Be "fake results"
}
}
Describe "When calling Mock on existing function without matching unbound arguments" {
Mock FunctionUnderTestWithoutParams {return "fake results"} -parameterFilter {$param1 -eq "test" -and $args[0] -eq 'notArg0'}
$result=FunctionUnderTestWithoutParams -param1 "test" "arg0"
It "Should redirect to real function" {
$result | Should Be "I am a real world test with no params"
}
}
Describe "When calling Mock on existing function with matching unbound arguments" {
Mock FunctionUnderTestWithoutParams {return "fake results"} -parameterFilter {$param1 -eq "badTest" -and $args[0] -eq 'arg0'}
$result=FunctionUnderTestWithoutParams "badTest" "arg0"
It "Should return mocked result" {
$result | Should Be "fake results"
}
}
Describe 'When calling Mock on a function that has no parameters' {
function Test-Function { }
Mock Test-Function { return $args.Count }
It 'Sends the $args variable properly with 2+ elements' {
Test-Function 1 2 3 4 5 | Should Be 5
}
It 'Sends the $args variable properly with 1 element' {
Test-Function 1 | Should Be 1
}
It 'Sends the $args variable properly with 0 elements' {
Test-Function | Should Be 0
}
}
Describe "When calling Mock on cmdlet Used by Mock" {
Mock Set-Item {return "I am not Set-Item"}
Mock Set-Item {return "I am not Set-Item"}
$result = Set-Item "mypath" -value "value"
It "Should Invoke the mocked script" {
$result | Should Be "I am not Set-Item"
}
}
Describe "When calling Mock on More than one command" {
Mock Invoke-Command {return "I am not Invoke-Command"}
Mock FunctionUnderTest {return "I am the mock test"}
$result = Invoke-Command {return "yes I am"}
$result2 = FunctionUnderTest
It "Should Invoke the mocked script for the first Mock" {
$result | Should Be "I am not Invoke-Command"
}
It "Should Invoke the mocked script for the second Mock" {
$result2 | Should Be "I am the mock test"
}
}
Describe 'When calling Mock on a module-internal function.' {
New-Module -Name TestModule {
function InternalFunction { 'I am the internal function' }
function PublicFunction { InternalFunction }
function PublicFunctionThatCallsExternalCommand { Start-Sleep 0 }
function FuncThatOverwritesExecutionContext {
param ($ExecutionContext)
InternalFunction
}
Export-ModuleMember -Function PublicFunction, PublicFunctionThatCallsExternalCommand, FuncThatOverwritesExecutionContext
} | Import-Module -Force
New-Module -Name TestModule2 {
function InternalFunction { 'I am the second module internal function' }
function InternalFunction2 { 'I am the second module, second function' }
function PublicFunction { InternalFunction }
function PublicFunction2 { InternalFunction2 }
function FuncThatOverwritesExecutionContext {
param ($ExecutionContext)
InternalFunction
}
function ScopeTest {
return Get-CallerModuleName
}
function Get-CallerModuleName {
[CmdletBinding()]
param ( )
return $PSCmdlet.SessionState.Module.Name
}
Export-ModuleMember -Function PublicFunction, PublicFunction2, FuncThatOverwritesExecutionContext, ScopeTest
} | Import-Module -Force
It 'Should fail to call the internal module function' {
{ TestModule\InternalFunction } | Should Throw
}
It 'Should call the actual internal module function from the public function' {
TestModule\PublicFunction | Should Be 'I am the internal function'
}
Context 'Using Mock -ModuleName "ModuleName" "CommandName" syntax' {
Mock -ModuleName TestModule InternalFunction { 'I am the mock test' }
It 'Should call the mocked function' {
TestModule\PublicFunction | Should Be 'I am the mock test'
}
Mock -ModuleName TestModule Start-Sleep { }
It 'Should mock calls to external functions from inside the module' {
PublicFunctionThatCallsExternalCommand
Assert-MockCalled -ModuleName TestModule Start-Sleep -Exactly 1
}
Mock -ModuleName TestModule2 InternalFunction -ParameterFilter { $args[0] -eq 'Test' } {
"I'm the mock who's been passed parameter Test"
}
It 'Should only call mocks within the same module' {
TestModule2\PublicFunction | Should Be 'I am the second module internal function'
}
Mock -ModuleName TestModule2 InternalFunction2 {
InternalFunction 'Test'
}
It 'Should call mocks from inside another mock' {
TestModule2\PublicFunction2 | Should Be "I'm the mock who's been passed parameter Test"
}
It 'Should work even if the function is weird and steps on the automatic $ExecutionContext variable.' {
TestModule2\FuncThatOverwritesExecutionContext | Should Be 'I am the second module internal function'
TestModule\FuncThatOverwritesExecutionContext | Should Be 'I am the mock test'
}
Mock -ModuleName TestModule2 Get-CallerModuleName -ParameterFilter { $false }
It 'Should call the original command from the proper scope if no parameter filters match' {
TestModule2\ScopeTest | Should Be 'TestModule2'
}
Mock -ModuleName TestModule2 Get-Content { }
It 'Does not trigger the mocked Get-Content from Pester internals' {
Mock -ModuleName TestModule2 Get-CallerModuleName -ParameterFilter { $false }
Assert-MockCalled -ModuleName TestModule2 Get-Content -Times 0 -Scope It
}
}
AfterAll {
Remove-Module TestModule -Force
Remove-Module TestModule2 -Force
}
}
Describe "When Applying multiple Mocks on a single command" {
Mock FunctionUnderTest {return "I am the first mock test"} -parameterFilter {$param1 -eq "one"}
Mock FunctionUnderTest {return "I am the Second mock test"} -parameterFilter {$param1 -eq "two"}
$result = FunctionUnderTest "one"
$result2= FunctionUnderTest "two"
It "Should Invoke the mocked script for the first Mock" {
$result | Should Be "I am the first mock test"
}
It "Should Invoke the mocked script for the second Mock" {
$result2 | Should Be "I am the Second mock test"
}
}
Describe "When Applying multiple Mocks with filters on a single command where both qualify" {
Mock FunctionUnderTest {return "I am the first mock test"} -parameterFilter {$param1.Length -gt 0 }
Mock FunctionUnderTest {return "I am the Second mock test"} -parameterFilter {$param1 -gt 1 }
$result = FunctionUnderTest "one"
It "The last Mock should win" {
$result | Should Be "I am the Second mock test"
}
}
Describe "When Applying multiple Mocks on a single command where one has no filter" {
Mock FunctionUnderTest {return "I am the first mock test"} -parameterFilter {$param1 -eq "one"}
Mock FunctionUnderTest {return "I am the paramless mock test"}
Mock FunctionUnderTest {return "I am the Second mock test"} -parameterFilter {$param1 -eq "two"}
$result = FunctionUnderTest "one"
$result2= FunctionUnderTest "three"
It "The parameterless mock is evaluated last" {
$result | Should Be "I am the first mock test"
}
It "The parameterless mock will be applied if no other wins" {
$result2 | Should Be "I am the paramless mock test"
}
}
Describe "When Creating a Verifiable Mock that is not called" {
Context "In the test script's scope" {
Mock FunctionUnderTest {return "I am a verifiable test"} -Verifiable -parameterFilter {$param1 -eq "one"}
FunctionUnderTest "three" | Out-Null
try {
Assert-VerifiableMocks
} Catch {
$result=$_
}
It "Should throw" {
$result.Exception.Message | Should Be "`r`n Expected FunctionUnderTest to be called with `$param1 -eq `"one`""
}
}
Context "In a module's scope" {
New-Module -Name TestModule -ScriptBlock {
function ModuleFunctionUnderTest { return 'I am the function under test in a module' }
} | Import-Module -Force
Mock -ModuleName TestModule ModuleFunctionUnderTest {return "I am a verifiable test"} -Verifiable -parameterFilter {$param1 -eq "one"}
TestModule\ModuleFunctionUnderTest "three" | Out-Null
try {
Assert-VerifiableMocks
} Catch {
$result=$_
}
It "Should throw" {
$result.Exception.Message | Should Be "`r`n Expected ModuleFunctionUnderTest in module TestModule to be called with `$param1 -eq `"one`""
}
AfterAll {
Remove-Module TestModule -Force
}
}
}
Describe "When Creating a Verifiable Mock that is called" {
Mock FunctionUnderTest -Verifiable -parameterFilter {$param1 -eq "one"}
FunctionUnderTest "one"
It "Assert-VerifiableMocks Should not throw" {
{ Assert-VerifiableMocks } | Should Not Throw
}
}
Describe "When Calling Assert-MockCalled 0 without exactly" {
Mock FunctionUnderTest {}
FunctionUnderTest "one"
try {
Assert-MockCalled FunctionUnderTest 0
} Catch {
$result=$_
}
It "Should throw if mock was called" {
$result.Exception.Message | Should Be "Expected FunctionUnderTest to be called 0 times exactly but was called 1 times"
}
It "Should not throw if mock was not called" {
Assert-MockCalled FunctionUnderTest 0 { $param1 -eq "stupid" }
}
}
Describe "When Calling Assert-MockCalled with exactly" {
Mock FunctionUnderTest {}
FunctionUnderTest "one"
FunctionUnderTest "one"
try {
Assert-MockCalled FunctionUnderTest -exactly 3
} Catch {
$result=$_
}
It "Should throw if mock was not called the number of times specified" {
$result.Exception.Message | Should Be "Expected FunctionUnderTest to be called 3 times exactly but was called 2 times"
}
It "Should not throw if mock was called the number of times specified" {
Assert-MockCalled FunctionUnderTest -exactly 2 { $param1 -eq "one" }
}
}
Describe "When Calling Assert-MockCalled without exactly" {
Mock FunctionUnderTest {}
FunctionUnderTest "one"
FunctionUnderTest "one"
FunctionUnderTest "two"
It "Should throw if mock was not called at least the number of times specified" {
$scriptBlock = { Assert-MockCalled FunctionUnderTest 4 }
$scriptBlock | Should Throw "Expected FunctionUnderTest to be called at least 4 times but was called 3 times"
}
It "Should not throw if mock was called at least the number of times specified" {
Assert-MockCalled FunctionUnderTest
}
It "Should not throw if mock was called at exactly the number of times specified" {
Assert-MockCalled FunctionUnderTest 2 { $param1 -eq "one" }
}
It "Should throw an error if any non-matching calls to the mock are made, and the -ExclusiveFilter parameter is used" {
$scriptBlock = { Assert-MockCalled FunctionUnderTest -ExclusiveFilter { $param1 -eq 'one' } }
$scriptBlock | Should Throw '1 non-matching calls were made'
}
}
Describe "Using Pester Scopes (Describe,Context,It)" {
Mock FunctionUnderTest {return "I am the first mock test"} -parameterFilter {$param1 -eq "one"}
Mock FunctionUnderTest {return "I am the paramless mock test"}
Context "When in the first context" {
It "should mock Describe scoped paramles mock" {
FunctionUnderTest | should be "I am the paramless mock test"
}
It "should mock Describe scoped single param mock" {
FunctionUnderTest "one" | should be "I am the first mock test"
}
}
Context "When in the second context" {
It "should mock Describe scoped paramles mock again" {
FunctionUnderTest | should be "I am the paramless mock test"
}
It "should mock Describe scoped single param mock again" {
FunctionUnderTest "one" | should be "I am the first mock test"
}
}
Context "When using mocks in both scopes" {
Mock FunctionUnderTestWithoutParams {return "I am the other function"}
It "should mock Describe scoped mock." {
FunctionUnderTest | should be "I am the paramless mock test"
}
It "should mock Context scoped mock." {
FunctionUnderTestWithoutParams | should be "I am the other function"
}
}
Context "When context hides a describe mock" {
Mock FunctionUnderTest {return "I am the context mock"}
Mock FunctionUnderTest {return "I am the parameterized context mock"} -parameterFilter {$param1 -eq "one"}
It "should use the context paramles mock" {
FunctionUnderTest | should be "I am the context mock"
}
It "should use the context parameterized mock" {
FunctionUnderTest "one" | should be "I am the parameterized context mock"
}
}
Context "When context no longer hides a describe mock" {
It "should use the describe mock" {
FunctionUnderTest | should be "I am the paramless mock test"
}
It "should use the describe parameterized mock" {
FunctionUnderTest "one" | should be "I am the first mock test"
}
}
Context 'When someone calls Mock from inside an It block' {
Mock FunctionUnderTest { return 'I am the context mock' }
It 'Sets the mock' {
Mock FunctionUnderTest { return 'I am the It mock' }
}
It 'Leaves the mock active in the parent scope' {
FunctionUnderTest | Should Be 'I am the It mock'
}
}
}
Describe 'Testing mock history behavior from each scope' {
function MockHistoryChecker { }
Mock MockHistoryChecker { 'I am the describe mock.' }
Context 'Without overriding the mock in lower scopes' {
It "Reports that zero calls have been made to in the describe scope" {
Assert-MockCalled MockHistoryChecker -Exactly 0 -Scope Describe
}
It 'Calls the describe mock' {
MockHistoryChecker | Should Be 'I am the describe mock.'
}
It "Reports that zero calls have been made in an It block, after a context-scoped call" {
Assert-MockCalled MockHistoryChecker -Exactly 0 -Scope It
}
It "Reports one Context-scoped call" {
Assert-MockCalled MockHistoryChecker -Exactly 1
}
It "Reports one Describe-scoped call" {
Assert-MockCalled MockHistoryChecker -Exactly 1 -Scope Describe
}
}
Context 'After exiting the previous context' {
It 'Reports zero context-scoped calls in the new context.' {
Assert-MockCalled MockHistoryChecker -Exactly 0
}
It 'Reports one describe-scoped call from the previous context' {
Assert-MockCalled MockHistoryChecker -Exactly 1 -Scope Describe
}
}
Context 'While overriding mocks in lower scopes' {
Mock MockHistoryChecker { 'I am the context mock.' }
It 'Calls the context mock' {
MockHistoryChecker | Should Be 'I am the context mock.'
}
It 'Reports one context-scoped call' {
Assert-MockCalled MockHistoryChecker -Exactly 1
}
It 'Reports two describe-scoped calls, even when one is an override mock in a lower scope' {
Assert-MockCalled MockHistoryChecker -Exactly 2 -Scope Describe
}
It 'Calls an It-scoped mock' {
Mock MockHistoryChecker { 'I am the It mock.' }
MockHistoryChecker | Should Be 'I am the It mock.'
}
It 'Reports 2 context-scoped calls' {
Assert-MockCalled MockHistoryChecker -Exactly 2
}
It 'Reports 3 describe-scoped calls' {
Assert-MockCalled MockHistoryChecker -Exactly 3 -Scope Describe
}
}
It 'Reports 3 describe-scoped calls using the default scope in a Describe block' {
Assert-MockCalled MockHistoryChecker -Exactly 3
}
}
Describe "Using a single no param Describe" {
Mock FunctionUnderTest {return "I am the describe mock test"}
Context "With a context mocking the same function with no params"{
Mock FunctionUnderTest {return "I am the context mock test"}
It "Should use the context mock" {
FunctionUnderTest | should be "I am the context mock test"
}
}
}
Describe 'Dot Source Test' {
# This test is only meaningful if this test file is dot-sourced in the global scope. If it's executed without
# dot-sourcing or run by Invoke-Pester, there's no problem.
function TestFunction { Test-Path -Path 'Test' }
Mock Test-Path { }
$null = TestFunction
It "Calls the mock with parameter 'Test'" {
Assert-MockCalled Test-Path -Exactly 1 -ParameterFilter { $Path -eq 'Test' }
}
It "Doesn't call the mock with any other parameters" {
InModuleScope Pester {
$global:calls = $mockTable['||Test-Path'].CallHistory
}
Assert-MockCalled Test-Path -Exactly 0 -ParameterFilter { $Path -ne 'Test' }
}
}
Describe 'Mocking Cmdlets with dynamic parameters' {
$mockWith = { if (-not $CodeSigningCert) { throw 'CodeSigningCert variable not found, or set to false!' } }
Mock Get-ChildItem -MockWith $mockWith -ParameterFilter { [bool]$CodeSigningCert }
It 'Allows calls to be made with dynamic parameters (including parameter filters)' {
{ Get-ChildItem -Path Cert:\ -CodeSigningCert } | Should Not Throw
Assert-MockCalled Get-ChildItem
}
}
Describe 'Mocking functions with dynamic parameters' {
Context 'Dynamicparam block that uses the variables of static parameters in its logic' {
# Get-Greeting sample function borrowed and modified from Bartek Bielawski's
# blog at http://becomelotr.wordpress.com/2012/05/10/using-and-abusing-dynamic-parameters/
function Get-Greeting {
[CmdletBinding()]
param (
[string] $Name
)
DynamicParam {
if ($Name -cmatch '\b[a-z]') {
$Attributes = New-Object Management.Automation.ParameterAttribute
$Attributes.ParameterSetName = "__AllParameterSets"
$Attributes.Mandatory = $false
$AttributeCollection = New-Object Collections.ObjectModel.Collection[Attribute]
$AttributeCollection.Add($Attributes)
$Dynamic = New-Object System.Management.Automation.RuntimeDefinedParameter('Capitalize', [switch], $AttributeCollection)
$ParamDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary
$ParamDictionary.Add("Capitalize", $Dynamic)
$ParamDictionary
}
}
end
{
if($PSBoundParameters.Capitalize) {
$Name = [regex]::Replace(
$Name,
'\b\w',
{ $args[0].Value.ToUpper() }
)
}
"Welcome $Name!"
}
}
$mockWith = { if (-not $Capitalize) { throw 'Capitalize variable not found, or set to false!' } }
Mock Get-Greeting -MockWith $mockWith -ParameterFilter { [bool]$Capitalize }
It 'Allows calls to be made with dynamic parameters (including parameter filters)' {
{ Get-Greeting -Name lowercase -Capitalize } | Should Not Throw
Assert-MockCalled Get-Greeting
}
$Capitalize = $false
It 'Sets the dynamic parameter variable properly' {
{ Get-Greeting -Name lowercase -Capitalize } | Should Not Throw
Assert-MockCalled Get-Greeting -Scope It
}
}
Context 'When the mocked command is in a module' {
New-Module -Name TestModule {
function PublicFunction { Get-Greeting -Name lowercase -Capitalize }
$script:DoDynamicParam = $true
# Get-Greeting sample function borrowed and modified from Bartek Bielawski's
# blog at http://becomelotr.wordpress.com/2012/05/10/using-and-abusing-dynamic-parameters/
function script:Get-Greeting {
[CmdletBinding()]
param (
[string] $Name
)
DynamicParam {
# This check is here to make sure the mocked version can still work if the
# original function's dynamicparam block relied on script-scope variables.
if (-not $script:DoDynamicParam) { return }
if ($Name -cmatch '\b[a-z]') {
$Attributes = New-Object Management.Automation.ParameterAttribute
$Attributes.ParameterSetName = "__AllParameterSets"
$Attributes.Mandatory = $false
$AttributeCollection = New-Object Collections.ObjectModel.Collection[Attribute]
$AttributeCollection.Add($Attributes)
$Dynamic = New-Object System.Management.Automation.RuntimeDefinedParameter('Capitalize', [switch], $AttributeCollection)
$ParamDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary
$ParamDictionary.Add("Capitalize", $Dynamic)
$ParamDictionary
}
}
end
{
if($PSBoundParameters.Capitalize) {
$Name = [regex]::Replace(
$Name,
'\b\w',
{ $args[0].Value.ToUpper() }
)
}
"Welcome $Name!"
}
}
} | Import-Module -Force
$mockWith = { if (-not $Capitalize) { throw 'Capitalize variable not found, or set to false!' } }
Mock Get-Greeting -MockWith $mockWith -ModuleName TestModule -ParameterFilter { [bool]$Capitalize }
It 'Allows calls to be made with dynamic parameters (including parameter filters)' {
{ TestModule\PublicFunction } | Should Not Throw
Assert-MockCalled Get-Greeting -ModuleName TestModule
}
AfterAll {
Remove-Module TestModule -Force
}
}
Context 'When the mocked command has mandatory parameters that are passed in via the pipeline' {
# Get-Greeting sample function borrowed and modified from Bartek Bielawski's
# blog at http://becomelotr.wordpress.com/2012/05/10/using-and-abusing-dynamic-parameters/
function Get-Greeting2 {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[string] $MandatoryParam,
[string] $Name
)
DynamicParam {
if ($Name -cmatch '\b[a-z]') {
$Attributes = New-Object Management.Automation.ParameterAttribute
$Attributes.ParameterSetName = "__AllParameterSets"
$Attributes.Mandatory = $false
$AttributeCollection = New-Object Collections.ObjectModel.Collection[Attribute]
$AttributeCollection.Add($Attributes)
$Dynamic = New-Object System.Management.Automation.RuntimeDefinedParameter('Capitalize', [switch], $AttributeCollection)
$ParamDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary
$ParamDictionary.Add("Capitalize", $Dynamic)
$ParamDictionary
}
}
end
{
if($PSBoundParameters.Capitalize) {
$Name = [regex]::Replace(
$Name,
'\b\w',
{ $args[0].Value.ToUpper() }
)
}
"Welcome $Name!"
}
}
Mock Get-Greeting2 { 'Mocked' } -ParameterFilter { [bool]$Capitalize }
$hash = @{ Result = $null }
$scriptBlock = { $hash.Result = 'Mandatory' | Get-Greeting2 -Name test -Capitalize }
It 'Should successfully call the mock and generate the dynamic parameters' {
$scriptBlock | Should Not Throw
$hash.Result | Should Be 'Mocked'
}
}
Context 'When the mocked command has parameter sets that are ambiguous at the time the dynamic param block is executed' {
# Get-Greeting sample function borrowed and modified from Bartek Bielawski's
# blog at http://becomelotr.wordpress.com/2012/05/10/using-and-abusing-dynamic-parameters/
function Get-Greeting3 {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true, ParameterSetName = 'One')]
[string] $One,
[Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true, ParameterSetName = 'Two')]
[string] $Two,
[string] $Name
)
DynamicParam {
if ($Name -cmatch '\b[a-z]') {
$Attributes = New-Object Management.Automation.ParameterAttribute
$Attributes.ParameterSetName = "__AllParameterSets"
$Attributes.Mandatory = $false
$AttributeCollection = New-Object Collections.ObjectModel.Collection[Attribute]
$AttributeCollection.Add($Attributes)
$Dynamic = New-Object System.Management.Automation.RuntimeDefinedParameter('Capitalize', [switch], $AttributeCollection)
$ParamDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary
$ParamDictionary.Add("Capitalize", $Dynamic)
$ParamDictionary
}
}
end
{
if($PSBoundParameters.Capitalize) {
$Name = [regex]::Replace(
$Name,
'\b\w',
{ $args[0].Value.ToUpper() }
)
}
"Welcome $Name!"
}
}
Mock Get-Greeting3 { 'Mocked' } -ParameterFilter { [bool]$Capitalize }
$hash = @{ Result = $null }
$scriptBlock = { $hash.Result = New-Object psobject -Property @{ One = 'One' } | Get-Greeting3 -Name test -Capitalize }
It 'Should successfully call the mock and generate the dynamic parameters' {
$scriptBlock | Should Not Throw
$hash.Result | Should Be 'Mocked'
}
}
Context 'When the mocked command''s dynamicparam block depends on the contents of $PSBoundParameters' {
# Get-Greeting sample function borrowed and modified from Bartek Bielawski's
# blog at http://becomelotr.wordpress.com/2012/05/10/using-and-abusing-dynamic-parameters/
function Get-Greeting4 {
[CmdletBinding()]
param (
[string] $Name
)
DynamicParam {
if ($PSBoundParameters['Name'] -cmatch '\b[a-z]') {
$Attributes = New-Object Management.Automation.ParameterAttribute
$Attributes.ParameterSetName = "__AllParameterSets"
$Attributes.Mandatory = $false
$AttributeCollection = New-Object Collections.ObjectModel.Collection[Attribute]
$AttributeCollection.Add($Attributes)
$Dynamic = New-Object System.Management.Automation.RuntimeDefinedParameter('Capitalize', [switch], $AttributeCollection)
$ParamDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary
$ParamDictionary.Add("Capitalize", $Dynamic)
$ParamDictionary
}
}
end
{
if($PSBoundParameters.Capitalize) {
$Name = [regex]::Replace(
$Name,
'\b\w',
{ $args[0].Value.ToUpper() }
)
}
"Welcome $Name!"
}
}
Mock Get-Greeting4 { 'Mocked' } -ParameterFilter { [bool]$Capitalize }
$hash = @{ Result = $null }
$scriptBlock = { $hash.Result = Get-Greeting4 -Name test -Capitalize }
It 'Should successfully call the mock and generate the dynamic parameters' {
$scriptBlock | Should Not Throw
$hash.Result | Should Be 'Mocked'
}
}
Context 'When the mocked command''s dynamicparam block depends on the contents of $PSCmdlet.ParameterSetName' {
# Get-Greeting sample function borrowed and modified from Bartek Bielawski's
# blog at http://becomelotr.wordpress.com/2012/05/10/using-and-abusing-dynamic-parameters/
function Get-Greeting5 {
[CmdletBinding(DefaultParameterSetName = 'One')]
param (
[string] $Name,
[Parameter(ParameterSetName = 'Two')]
[string] $Two
)
DynamicParam {
if ($PSCmdlet.ParameterSetName -eq 'Two' -and $Name -cmatch '\b[a-z]') {
$Attributes = New-Object Management.Automation.ParameterAttribute
$Attributes.ParameterSetName = "__AllParameterSets"
$Attributes.Mandatory = $false
$AttributeCollection = New-Object Collections.ObjectModel.Collection[Attribute]
$AttributeCollection.Add($Attributes)
$Dynamic = New-Object System.Management.Automation.RuntimeDefinedParameter('Capitalize', [switch], $AttributeCollection)
$ParamDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary
$ParamDictionary.Add("Capitalize", $Dynamic)
$ParamDictionary
}
}
end
{
if($PSBoundParameters.Capitalize) {
$Name = [regex]::Replace(
$Name,
'\b\w',
{ $args[0].Value.ToUpper() }
)
}
"Welcome $Name!"
}
}
Mock Get-Greeting5 { 'Mocked' } -ParameterFilter { [bool]$Capitalize }
$hash = @{ Result = $null }
$scriptBlock = { $hash.Result = Get-Greeting5 -Two 'Two' -Name test -Capitalize }
It 'Should successfully call the mock and generate the dynamic parameters' {
$scriptBlock | Should Not Throw
$hash.Result | Should Be 'Mocked'
}
}
}
Describe 'Mocking Cmdlets with dynamic parameters in a module' {
New-Module -Name TestModule {
function PublicFunction { Get-ChildItem -Path Cert:\ -CodeSigningCert }
} | Import-Module -Force
$mockWith = { if (-not $CodeSigningCert) { throw 'CodeSigningCert variable not found, or set to false!' } }
Mock Get-ChildItem -MockWith $mockWith -ModuleName TestModule -ParameterFilter { [bool]$CodeSigningCert }
It 'Allows calls to be made with dynamic parameters (including parameter filters)' {
{ TestModule\PublicFunction } | Should Not Throw
Assert-MockCalled Get-ChildItem -ModuleName TestModule
}
AfterAll {
Remove-Module TestModule -Force
}
}
Describe 'DynamicParam blocks in other scopes' {
New-Module -Name TestModule1 {
$script:DoDynamicParam = $true
function DynamicParamFunction {
[CmdletBinding()]
param ( )
DynamicParam {
if ($script:DoDynamicParam)
{
if ($PSVersionTable.PSVersion.Major -ge 3)
{
# -Parameters needs to be a PSBoundParametersDictionary object to work properly, due to internal
# details of the PS engine in v5. Naturally, this is an internal type and we need to use reflection
# to make a new one.
$flags = [System.Reflection.BindingFlags]'Instance,NonPublic'
$params = $PSBoundParameters.GetType().GetConstructor($flags, $null, @(), $null).Invoke(@())
}
else
{
$params = @{}
}
$params['Path'] = [string[]]'Cert:\'
Get-MockDynamicParameters -CmdletName Get-ChildItem -Parameters $params
}
}
end
{
'I am the original function'
}
}
} | Import-Module -Force
New-Module -Name TestModule2 {
function CallingFunction
{
DynamicParamFunction -CodeSigningCert
}
function CallingFunction2 {
[CmdletBinding()]
param (
[ValidateScript({ [bool](DynamicParamFunction -CodeSigningCert) })]
[string]
$Whatever
)
}
} | Import-Module -Force
Mock DynamicParamFunction { if ($CodeSigningCert) { 'I am the mocked function' } } -ModuleName TestModule2
It 'Properly evaluates dynamic parameters when called from another scope' {
CallingFunction | Should Be 'I am the mocked function'
}
It 'Properly evaluates dynamic parameters when called from another scope when the call is from a ValidateScript block' {
CallingFunction2 -Whatever 'Whatever'
}
AfterAll {
Remove-Module TestModule1 -Force
Remove-Module TestModule2 -Force
}
}
Describe 'Parameter Filters and Common Parameters' {
function Test-Function { [CmdletBinding()] param ( ) }
Mock Test-Function { } -ParameterFilter { $VerbosePreference -eq 'Continue' }
It 'Applies common parameters correctly when testing the parameter filter' {
{ Test-Function -Verbose } | Should Not Throw
Assert-MockCalled Test-Function
Assert-MockCalled Test-Function -ParameterFilter { $VerbosePreference -eq 'Continue' }
}
}
Describe "Mocking Get-ItemProperty" {
Mock Get-ItemProperty { New-Object -typename psobject -property @{ Name = "fakeName" } }
It "Does not fail with NotImplementedException" {
Get-ItemProperty -Path "HKLM:\Software\Key\" -Name "Property" | Select -ExpandProperty Name | Should Be fakeName
}
}
Describe 'When mocking a command with parameters that match internal variable names' {
function Test-Function
{
[CmdletBinding()]
param (
[string] $ArgumentList,
[int] $FunctionName,
[double] $ModuleName
)
}
Mock Test-Function { return 'Mocked!' }
It 'Should execute the mocked command successfully' {
{ Test-Function } | Should Not Throw
Test-Function | Should Be 'Mocked!'
}
}
Describe 'Mocking commands with potentially ambiguous parameter sets' {
function SomeFunction
{
[CmdletBinding()]
param
(
[parameter(ParameterSetName = 'ps1',
ValueFromPipelineByPropertyName = $true)]
[string]
$p1,
[parameter(ParameterSetName = 'ps2',
ValueFromPipelineByPropertyName = $true)]
[string]
$p2
)
process
{
return $true
}
}
Mock SomeFunction { }
It 'Should call the function successfully, even with delayed parameter binding' {
$object = New-Object psobject -Property @{ p1 = 'Whatever' }
{ $object | SomeFunction } | Should Not Throw
Assert-MockCalled SomeFunction -ParameterFilter { $p1 -eq 'Whatever' }
}
}
Describe 'When mocking a command that has an ArgumentList parameter with validation' {
Mock Start-Process { return 'mocked' }
It 'Calls the mock properly' {
$hash = @{ Result = $null }
$scriptBlock = { $hash.Result = Start-Process -FilePath cmd.exe -ArgumentList '/c dir c:\' }
$scriptBlock | Should Not Throw
$hash.Result | Should Be 'mocked'
}
}
# These assertions won't actually "fail"; we had an infinite recursion bug in Get-DynamicParametersForCmdlet
# if the caller mocked New-Object. It should be fixed by making that call to New-Object module-qualified,
# and this test will make sure it's working properly. If this test fails, it'll take a really long time
# to execute, and then will throw a stack overflow error.
Describe 'Mocking New-Object' {
It 'Works properly' {
Mock New-Object
$result = New-Object -TypeName Object
$result | Should Be $null
Assert-MockCalled New-Object
}
}
Describe 'Mocking a function taking input from pipeline' {
$psobj = New-Object -TypeName psobject -Property @{'PipeIntProp'='1';'PipeArrayProp'=1;'PipeStringProp'=1}
$psArrayobj = New-Object -TypeName psobject -Property @{'PipeArrayProp'=@(1)}
$noMockArrayResult = @(1,2) | PipelineInputFunction
$noMockIntResult = 1 | PipelineInputFunction
$noMockStringResult = '1' | PipelineInputFunction
$noMockResultByProperty = $psobj | PipelineInputFunction -PipeStr 'val'
$noMockArrayResultByProperty = $psArrayobj | PipelineInputFunction -PipeStr 'val'
Mock PipelineInputFunction { write-output 'mocked' } -ParameterFilter { $PipeStr -eq 'blah' }
context 'when calling original function with an array' {
$result = @(1,2) | PipelineInputFunction
it 'Returns actual implementation' {
$result[0].keys | % {
$result[0][$_] | Should Be $noMockArrayResult[0][$_]
$result[1][$_] | Should Be $noMockArrayResult[1][$_]
}
}
}
context 'when calling original function with an int' {
$result = 1 | PipelineInputFunction
it 'Returns actual implementation' {
$result.keys | % {
$result[$_] | Should Be $noMockIntResult[$_]
}
}
}
context 'when calling original function with a string' {
$result = '1' | PipelineInputFunction
it 'Returns actual implementation' {
$result.keys | % {
$result[$_] | Should Be $noMockStringResult[$_]
}
}
}
context 'when calling original function and pipeline is bound by property name' {
$result = $psobj | PipelineInputFunction -PipeStr 'val'
it 'Returns actual implementation' {
$result.keys | % {
$result[$_] | Should Be $noMockResultByProperty[$_]
}
}
}
context 'when calling original function and forcing a parameter binding exception' {
Mock PipelineInputFunction {
if($MyInvocation.ExpectingInput) {
throw New-Object -TypeName System.Management.Automation.ParameterBindingException
}
write-output $MyInvocation.ExpectingInput
}
$result = $psobj | PipelineInputFunction
it 'falls back to no pipeline input' {
$result | Should Be $false
}
}
context 'when calling original function and pipeline is bound by property name with array values' {
$result = $psArrayobj | PipelineInputFunction -PipeStr 'val'
it 'Returns actual implementation' {
$result.keys | % {
$result[$_] | Should Be $noMockArrayResultByProperty[$_]
}
}
}
context 'when calling the mocked function' {
$result = 'blah' | PipelineInputFunction
it 'Returns mocked implementation' {
$result | Should Be 'mocked'
}
}
}
Describe 'Mocking module-qualified calls' {
It 'Mock alias should not exist before the mock is defined' {
$alias = Get-Alias -Name 'Microsoft.PowerShell.Management\Get-Content' -ErrorAction SilentlyContinue
$alias | Should Be $null
}
$mockFile = 'TestDrive:\TestFile'
$mockResult = 'Mocked'
Mock Get-Content { return $mockResult } -ParameterFilter { $Path -eq $mockFile }
Setup -File TestFile -Content 'The actual file'
It 'Creates the alias while the mock is in effect' {
$alias = Get-Alias -Name 'Microsoft.PowerShell.Management\Get-Content' -ErrorAction SilentlyContinue
$alias | Should Not Be $null
}
It 'Calls the mock properly even if the call is module-qualified' {
$result = Microsoft.PowerShell.Management\Get-Content -Path $mockFile
$result | Should Be $mockResult
}
}
Describe 'After a mock goes out of scope' {
It 'Removes the alias after the mock goes out of scope' {
$alias = Get-Alias -Name 'Microsoft.PowerShell.Management\Get-Content' -ErrorAction SilentlyContinue
$alias | Should Be $null
}
}
Describe 'Assert-MockCalled with Aliases' {
AfterEach {
if (Test-Path alias:PesterTF) { Remove-Item Alias:PesterTF }
}
It 'Allows calls to Assert-MockCalled to use both aliases and the original command name' {
function TestFunction { }
Set-Alias -Name PesterTF -Value TestFunction
Mock PesterTF
$null = PesterTF
{ Assert-MockCalled PesterTF } | Should Not Throw
{ Assert-MockCalled TestFunction } | Should Not Throw
}
}
Describe 'Mocking Get-Command' {
# This was reported as a bug in 3.3.12; we were relying on Get-Command to safely invoke other commands.
# Mocking Get-Command, though, would result in infinite recursion.
It 'Does not break when Get-Command is mocked' {
{ Mock Get-Command } | Should Not Throw
}
}
Describe 'Mocks with closures' {
$closureVariable = 'from closure'
$scriptBlock = { "Variable resolved $closureVariable" }
$closure = $scriptBlock.GetNewClosure()
$closureVariable = 'from script'
function TestClosure([switch] $Closure) { 'Not mocked' }
Mock TestClosure $closure -ParameterFilter { $Closure }
Mock TestClosure $scriptBlock
It 'Resolves variables in the closure rather than Pester''s current scope' {
TestClosure | Should Be 'Variable resolved from script'
TestClosure -Closure | Should Be 'Variable re
gitextract_imkf2kq6/ ├── .gitattributes ├── .gitignore ├── DbgShell/ │ ├── x64/ │ │ ├── DbgShell.exe.config │ │ ├── DbgShell.pdb │ │ ├── DbgShellExt.iobj │ │ ├── DbgShellExt.ipdb │ │ ├── DbgShellExt.pdb │ │ ├── DbgShellTest/ │ │ │ ├── CoCreateShim.iobj │ │ │ ├── CoCreateShim.ipdb │ │ │ ├── CoCreateShim.pdb │ │ │ ├── DbgShellTest.psd1 │ │ │ ├── DbgShellTest.psm1 │ │ │ ├── Pester/ │ │ │ │ ├── CHANGELOG.md │ │ │ │ ├── Functions/ │ │ │ │ │ ├── Assertions/ │ │ │ │ │ │ ├── Be.Tests.ps1 │ │ │ │ │ │ ├── Be.ps1 │ │ │ │ │ │ ├── BeGreaterThan.Tests.ps1 │ │ │ │ │ │ ├── BeGreaterThan.ps1 │ │ │ │ │ │ ├── BeLessThan.Tests.ps1 │ │ │ │ │ │ ├── BeLessThan.ps1 │ │ │ │ │ │ ├── BeNullOrEmpty.Tests.ps1 │ │ │ │ │ │ ├── BeNullOrEmpty.ps1 │ │ │ │ │ │ ├── BeOfType.Tests.ps1 │ │ │ │ │ │ ├── BeOfType.ps1 │ │ │ │ │ │ ├── Contain.Tests.ps1 │ │ │ │ │ │ ├── Contain.ps1 │ │ │ │ │ │ ├── ContainExactly.Tests.ps1 │ │ │ │ │ │ ├── ContainExactly.ps1 │ │ │ │ │ │ ├── Exist.Tests.ps1 │ │ │ │ │ │ ├── Exist.ps1 │ │ │ │ │ │ ├── Match.Tests.ps1 │ │ │ │ │ │ ├── Match.ps1 │ │ │ │ │ │ ├── MatchExactly.Tests.ps1 │ │ │ │ │ │ ├── MatchExactly.ps1 │ │ │ │ │ │ ├── PesterThrow.Tests.ps1 │ │ │ │ │ │ ├── PesterThrow.ps1 │ │ │ │ │ │ ├── Set-TestInconclusive.ps1 │ │ │ │ │ │ ├── Should.Tests.ps1 │ │ │ │ │ │ ├── Should.ps1 │ │ │ │ │ │ └── Test-Assertion.ps1 │ │ │ │ │ ├── BreakAndContinue.Tests.ps1 │ │ │ │ │ ├── Context.Tests.ps1 │ │ │ │ │ ├── Context.ps1 │ │ │ │ │ ├── Coverage.Tests.ps1 │ │ │ │ │ ├── Coverage.ps1 │ │ │ │ │ ├── Describe.Tests.ps1 │ │ │ │ │ ├── Describe.ps1 │ │ │ │ │ ├── GlobalMock-A.Tests.ps1 │ │ │ │ │ ├── GlobalMock-B.Tests.ps1 │ │ │ │ │ ├── In.Tests.ps1 │ │ │ │ │ ├── In.ps1 │ │ │ │ │ ├── InModuleScope.Tests.ps1 │ │ │ │ │ ├── InModuleScope.ps1 │ │ │ │ │ ├── It.Tests.ps1 │ │ │ │ │ ├── It.ps1 │ │ │ │ │ ├── Mock.Tests.ps1 │ │ │ │ │ ├── Mock.ps1 │ │ │ │ │ ├── New-Fixture.Tests.ps1 │ │ │ │ │ ├── New-Fixture.ps1 │ │ │ │ │ ├── PesterState.Tests.ps1 │ │ │ │ │ ├── PesterState.ps1 │ │ │ │ │ ├── SetupTeardown.Tests.ps1 │ │ │ │ │ ├── SetupTeardown.ps1 │ │ │ │ │ ├── TestDrive.Tests.ps1 │ │ │ │ │ ├── TestDrive.ps1 │ │ │ │ │ ├── TestResults.Tests.ps1 │ │ │ │ │ ├── TestResults.ps1 │ │ │ │ │ └── TestsRunningInCleanRunspace.Tests.ps1 │ │ │ │ ├── LICENSE │ │ │ │ ├── Pester.Tests.ps1 │ │ │ │ ├── Pester.psd1 │ │ │ │ ├── Pester.psm1 │ │ │ │ ├── README.md │ │ │ │ ├── Snippets/ │ │ │ │ │ ├── Context.snippets.ps1xml │ │ │ │ │ ├── Describe.snippets.ps1xml │ │ │ │ │ ├── It.snippets.ps1xml │ │ │ │ │ ├── ShouldBe.snippets.ps1xml │ │ │ │ │ ├── ShouldBeGreaterThan.snippets.ps1xml │ │ │ │ │ ├── ShouldBeLessThan.snippets.ps1xml │ │ │ │ │ ├── ShouldBeNullOrEmpty.snippets.ps1xml │ │ │ │ │ ├── ShouldContain.snippets.ps1xml │ │ │ │ │ ├── ShouldExist.snippets.ps1xml │ │ │ │ │ ├── ShouldMatch.snippets.ps1xml │ │ │ │ │ ├── ShouldNotBe.snippets.ps1xml │ │ │ │ │ ├── ShouldNotBeNullOrEmpty.snippets.ps1xml │ │ │ │ │ ├── ShouldNotContain.snippets.ps1xml │ │ │ │ │ ├── ShouldNotExist.snippets.ps1xml │ │ │ │ │ ├── ShouldNotMatch.snippets.ps1xml │ │ │ │ │ ├── ShouldNotThrow.snippets.ps1xml │ │ │ │ │ └── ShouldThrow.snippets.ps1xml │ │ │ │ ├── en-US/ │ │ │ │ │ ├── about_BeforeEach_AfterEach.help.txt │ │ │ │ │ ├── about_Mocking.help.txt │ │ │ │ │ ├── about_Pester.help.txt │ │ │ │ │ ├── about_TestDrive.help.txt │ │ │ │ │ └── about_should.help.txt │ │ │ │ └── nunit_schema_2.5.xsd │ │ │ ├── TestManagedCommon.pdb │ │ │ ├── TestManagedConsoleApp.exe.config │ │ │ ├── TestManagedConsoleApp.pdb │ │ │ ├── TestNativeConsoleApp.exp │ │ │ ├── TestNativeConsoleApp.iobj │ │ │ ├── TestNativeConsoleApp.ipdb │ │ │ ├── TestNativeConsoleApp.lib │ │ │ ├── TestNativeConsoleApp.pdb │ │ │ ├── Tests/ │ │ │ │ ├── Disasm.Tests.ps1 │ │ │ │ ├── Dumps.Tests.ps1 │ │ │ │ ├── Gu.Tests.ps1 │ │ │ │ ├── Kill.Tests.ps1 │ │ │ │ ├── MultiProcDetachAttach.Tests.ps1 │ │ │ │ ├── NamespaceTests/ │ │ │ │ │ ├── ContentTests.ps1 │ │ │ │ │ ├── CopyItem.ps1 │ │ │ │ │ ├── DriveTests.ps1 │ │ │ │ │ ├── Globbing.ps1 │ │ │ │ │ ├── MoveItem.ps1 │ │ │ │ │ ├── ProviderTests.metadata │ │ │ │ │ └── RenameItem.ps1 │ │ │ │ ├── ReentrantConversion.Tests.ps1 │ │ │ │ ├── StlTypeConversion.Tests.ps1 │ │ │ │ ├── TemplateMatching.Tests.ps1 │ │ │ │ ├── TrickySymbolValueConversions.Tests.ps1 │ │ │ │ ├── ValueConverterQueries.Tests.ps1 │ │ │ │ ├── VariantConversion.Tests.ps1 │ │ │ │ └── WriteMem.Tests.ps1 │ │ │ ├── v2Lib.pdb │ │ │ └── v4Lib.pdb │ │ ├── Debugger/ │ │ │ ├── DbgEngWrapper.dll.metagen │ │ │ ├── DbgEngWrapper.pdb │ │ │ ├── DbgNativeUtil.iobj │ │ │ ├── DbgNativeUtil.ipdb │ │ │ ├── DbgNativeUtil.pdb │ │ │ ├── DbgProvider.pdb │ │ │ ├── Debugger.ArgumentCompleters.ps1 │ │ │ ├── Debugger.ArgumentCompleters.shared.ps1 │ │ │ ├── Debugger.Converters.COM.ps1 │ │ │ ├── Debugger.Converters.NT.ps1 │ │ │ ├── Debugger.Converters.WinRT.ps1 │ │ │ ├── Debugger.Converters.stl.ps1 │ │ │ ├── Debugger.Converters.win32.ps1 │ │ │ ├── Debugger.Converters.wrl.ps1 │ │ │ ├── Debugger.Converters.xaml.ps1 │ │ │ ├── Debugger.DebuggeeTypes.NT.psfmt │ │ │ ├── Debugger.DebuggeeTypes.Win32.psfmt │ │ │ ├── Debugger.DebuggeeTypes.atl.psfmt │ │ │ ├── Debugger.DebuggeeTypes.clr.psfmt │ │ │ ├── Debugger.DebuggeeTypes.psfmt │ │ │ ├── Debugger.DebuggeeTypes.wrl.psfmt │ │ │ ├── Debugger.DebuggeeTypes.xaml.psfmt │ │ │ ├── Debugger.Format.Color.ps1xml │ │ │ ├── Debugger.Format.ps1xml │ │ │ ├── Debugger.Formatting.psm1 │ │ │ ├── Debugger.psd1 │ │ │ ├── Debugger.psfmt │ │ │ ├── Debugger.psm1 │ │ │ ├── FmtUtils.ps1 │ │ │ ├── GetPsContextFunc.ps1 │ │ │ ├── KernelMode.ps1 │ │ │ ├── Microsoft.Diagnostics.Runtime.pdb │ │ │ ├── Microsoft.Diagnostics.Runtime.xml │ │ │ ├── OtherUtils.ps1 │ │ │ ├── Types.ps1xml │ │ │ └── en-us/ │ │ │ ├── DbgProvider.dll-Help.xml │ │ │ ├── about_Color.help.txt │ │ │ ├── about_CustomFormatting.help.txt │ │ │ ├── about_CustomSymbolValueConversion.help.txt │ │ │ ├── about_DbgShell.help.txt │ │ │ ├── about_DbgShell_GettingStarted.help.txt │ │ │ ├── about_DerivedTypeDetection.help.txt │ │ │ ├── about_HowTo_Write_a_Symbol_Value_Converter.help.txt │ │ │ └── about_MemoryCommands.help.txt │ │ ├── TypeInfoDebugging/ │ │ │ └── TypeInfoDebugging.psm1 │ │ └── doc/ │ │ ├── Color.md │ │ ├── CustomFormattingEngine.md │ │ ├── DbgEngWrapper.md │ │ ├── DerivedTypeDetection.md │ │ ├── GettingStarted.md │ │ └── SymbolValueConversion.md │ └── x86/ │ ├── DbgShell.exe.config │ ├── DbgShell.pdb │ ├── DbgShellExt.iobj │ ├── DbgShellExt.ipdb │ ├── DbgShellExt.pdb │ ├── DbgShellTest/ │ │ ├── CoCreateShim.iobj │ │ ├── CoCreateShim.ipdb │ │ ├── CoCreateShim.pdb │ │ ├── DbgShellTest.psd1 │ │ ├── DbgShellTest.psm1 │ │ ├── Pester/ │ │ │ ├── CHANGELOG.md │ │ │ ├── Functions/ │ │ │ │ ├── Assertions/ │ │ │ │ │ ├── Be.Tests.ps1 │ │ │ │ │ ├── Be.ps1 │ │ │ │ │ ├── BeGreaterThan.Tests.ps1 │ │ │ │ │ ├── BeGreaterThan.ps1 │ │ │ │ │ ├── BeLessThan.Tests.ps1 │ │ │ │ │ ├── BeLessThan.ps1 │ │ │ │ │ ├── BeNullOrEmpty.Tests.ps1 │ │ │ │ │ ├── BeNullOrEmpty.ps1 │ │ │ │ │ ├── BeOfType.Tests.ps1 │ │ │ │ │ ├── BeOfType.ps1 │ │ │ │ │ ├── Contain.Tests.ps1 │ │ │ │ │ ├── Contain.ps1 │ │ │ │ │ ├── ContainExactly.Tests.ps1 │ │ │ │ │ ├── ContainExactly.ps1 │ │ │ │ │ ├── Exist.Tests.ps1 │ │ │ │ │ ├── Exist.ps1 │ │ │ │ │ ├── Match.Tests.ps1 │ │ │ │ │ ├── Match.ps1 │ │ │ │ │ ├── MatchExactly.Tests.ps1 │ │ │ │ │ ├── MatchExactly.ps1 │ │ │ │ │ ├── PesterThrow.Tests.ps1 │ │ │ │ │ ├── PesterThrow.ps1 │ │ │ │ │ ├── Set-TestInconclusive.ps1 │ │ │ │ │ ├── Should.Tests.ps1 │ │ │ │ │ ├── Should.ps1 │ │ │ │ │ └── Test-Assertion.ps1 │ │ │ │ ├── BreakAndContinue.Tests.ps1 │ │ │ │ ├── Context.Tests.ps1 │ │ │ │ ├── Context.ps1 │ │ │ │ ├── Coverage.Tests.ps1 │ │ │ │ ├── Coverage.ps1 │ │ │ │ ├── Describe.Tests.ps1 │ │ │ │ ├── Describe.ps1 │ │ │ │ ├── GlobalMock-A.Tests.ps1 │ │ │ │ ├── GlobalMock-B.Tests.ps1 │ │ │ │ ├── In.Tests.ps1 │ │ │ │ ├── In.ps1 │ │ │ │ ├── InModuleScope.Tests.ps1 │ │ │ │ ├── InModuleScope.ps1 │ │ │ │ ├── It.Tests.ps1 │ │ │ │ ├── It.ps1 │ │ │ │ ├── Mock.Tests.ps1 │ │ │ │ ├── Mock.ps1 │ │ │ │ ├── New-Fixture.Tests.ps1 │ │ │ │ ├── New-Fixture.ps1 │ │ │ │ ├── PesterState.Tests.ps1 │ │ │ │ ├── PesterState.ps1 │ │ │ │ ├── SetupTeardown.Tests.ps1 │ │ │ │ ├── SetupTeardown.ps1 │ │ │ │ ├── TestDrive.Tests.ps1 │ │ │ │ ├── TestDrive.ps1 │ │ │ │ ├── TestResults.Tests.ps1 │ │ │ │ ├── TestResults.ps1 │ │ │ │ └── TestsRunningInCleanRunspace.Tests.ps1 │ │ │ ├── LICENSE │ │ │ ├── Pester.Tests.ps1 │ │ │ ├── Pester.psd1 │ │ │ ├── Pester.psm1 │ │ │ ├── README.md │ │ │ ├── Snippets/ │ │ │ │ ├── Context.snippets.ps1xml │ │ │ │ ├── Describe.snippets.ps1xml │ │ │ │ ├── It.snippets.ps1xml │ │ │ │ ├── ShouldBe.snippets.ps1xml │ │ │ │ ├── ShouldBeGreaterThan.snippets.ps1xml │ │ │ │ ├── ShouldBeLessThan.snippets.ps1xml │ │ │ │ ├── ShouldBeNullOrEmpty.snippets.ps1xml │ │ │ │ ├── ShouldContain.snippets.ps1xml │ │ │ │ ├── ShouldExist.snippets.ps1xml │ │ │ │ ├── ShouldMatch.snippets.ps1xml │ │ │ │ ├── ShouldNotBe.snippets.ps1xml │ │ │ │ ├── ShouldNotBeNullOrEmpty.snippets.ps1xml │ │ │ │ ├── ShouldNotContain.snippets.ps1xml │ │ │ │ ├── ShouldNotExist.snippets.ps1xml │ │ │ │ ├── ShouldNotMatch.snippets.ps1xml │ │ │ │ ├── ShouldNotThrow.snippets.ps1xml │ │ │ │ └── ShouldThrow.snippets.ps1xml │ │ │ ├── en-US/ │ │ │ │ ├── about_BeforeEach_AfterEach.help.txt │ │ │ │ ├── about_Mocking.help.txt │ │ │ │ ├── about_Pester.help.txt │ │ │ │ ├── about_TestDrive.help.txt │ │ │ │ └── about_should.help.txt │ │ │ └── nunit_schema_2.5.xsd │ │ ├── TestManagedCommon.pdb │ │ ├── TestManagedConsoleApp.exe.config │ │ ├── TestManagedConsoleApp.pdb │ │ ├── TestNativeConsoleApp.exp │ │ ├── TestNativeConsoleApp.iobj │ │ ├── TestNativeConsoleApp.ipdb │ │ ├── TestNativeConsoleApp.lib │ │ ├── TestNativeConsoleApp.pdb │ │ ├── Tests/ │ │ │ ├── Disasm.Tests.ps1 │ │ │ ├── Dumps.Tests.ps1 │ │ │ ├── Gu.Tests.ps1 │ │ │ ├── Kill.Tests.ps1 │ │ │ ├── MultiProcDetachAttach.Tests.ps1 │ │ │ ├── NamespaceTests/ │ │ │ │ ├── ContentTests.ps1 │ │ │ │ ├── CopyItem.ps1 │ │ │ │ ├── DriveTests.ps1 │ │ │ │ ├── Globbing.ps1 │ │ │ │ ├── MoveItem.ps1 │ │ │ │ ├── ProviderTests.metadata │ │ │ │ └── RenameItem.ps1 │ │ │ ├── ReentrantConversion.Tests.ps1 │ │ │ ├── StlTypeConversion.Tests.ps1 │ │ │ ├── TemplateMatching.Tests.ps1 │ │ │ ├── TrickySymbolValueConversions.Tests.ps1 │ │ │ ├── ValueConverterQueries.Tests.ps1 │ │ │ ├── VariantConversion.Tests.ps1 │ │ │ └── WriteMem.Tests.ps1 │ │ ├── v2Lib.pdb │ │ └── v4Lib.pdb │ ├── Debugger/ │ │ ├── DbgEngWrapper.dll.metagen │ │ ├── DbgEngWrapper.pdb │ │ ├── DbgNativeUtil.iobj │ │ ├── DbgNativeUtil.ipdb │ │ ├── DbgNativeUtil.pdb │ │ ├── DbgProvider.pdb │ │ ├── Debugger.ArgumentCompleters.ps1 │ │ ├── Debugger.ArgumentCompleters.shared.ps1 │ │ ├── Debugger.Converters.COM.ps1 │ │ ├── Debugger.Converters.NT.ps1 │ │ ├── Debugger.Converters.WinRT.ps1 │ │ ├── Debugger.Converters.stl.ps1 │ │ ├── Debugger.Converters.win32.ps1 │ │ ├── Debugger.Converters.wrl.ps1 │ │ ├── Debugger.Converters.xaml.ps1 │ │ ├── Debugger.DebuggeeTypes.NT.psfmt │ │ ├── Debugger.DebuggeeTypes.Win32.psfmt │ │ ├── Debugger.DebuggeeTypes.atl.psfmt │ │ ├── Debugger.DebuggeeTypes.clr.psfmt │ │ ├── Debugger.DebuggeeTypes.psfmt │ │ ├── Debugger.DebuggeeTypes.wrl.psfmt │ │ ├── Debugger.DebuggeeTypes.xaml.psfmt │ │ ├── Debugger.Format.Color.ps1xml │ │ ├── Debugger.Format.ps1xml │ │ ├── Debugger.Formatting.psm1 │ │ ├── Debugger.psd1 │ │ ├── Debugger.psfmt │ │ ├── Debugger.psm1 │ │ ├── FmtUtils.ps1 │ │ ├── GetPsContextFunc.ps1 │ │ ├── KernelMode.ps1 │ │ ├── Microsoft.Diagnostics.Runtime.pdb │ │ ├── Microsoft.Diagnostics.Runtime.xml │ │ ├── OtherUtils.ps1 │ │ ├── Types.ps1xml │ │ └── en-us/ │ │ ├── DbgProvider.dll-Help.xml │ │ ├── about_Color.help.txt │ │ ├── about_CustomFormatting.help.txt │ │ ├── about_CustomSymbolValueConversion.help.txt │ │ ├── about_DbgShell.help.txt │ │ ├── about_DbgShell_GettingStarted.help.txt │ │ ├── about_DerivedTypeDetection.help.txt │ │ ├── about_HowTo_Write_a_Symbol_Value_Converter.help.txt │ │ └── about_MemoryCommands.help.txt │ ├── TypeInfoDebugging/ │ │ └── TypeInfoDebugging.psm1 │ └── doc/ │ ├── Color.md │ ├── CustomFormattingEngine.md │ ├── DbgEngWrapper.md │ ├── DerivedTypeDetection.md │ ├── GettingStarted.md │ └── SymbolValueConversion.md └── Readme.md
Condensed preview — 349 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (3,341K chars).
[
{
"path": ".gitattributes",
"chars": 378,
"preview": "# Auto detect text files and perform LF normalization\n* text=auto\n\n# Custom for Visual Studio\n*.cs diff=csharp\n\n# St"
},
{
"path": ".gitignore",
"chars": 649,
"preview": "# Windows image file caches\nThumbs.db\nehthumbs.db\n\n# Folder config file\nDesktop.ini\n\n# Recycle Bin used on file shares\n$"
},
{
"path": "DbgShell/x64/DbgShell.exe.config",
"chars": 362,
"preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<configuration>\n <startup useLegacyV2RuntimeActivationPolicy=\"true\">\n <suppor"
},
{
"path": "DbgShell/x64/DbgShellTest/DbgShellTest.psd1",
"chars": 2626,
"preview": "#\n# Module manifest for module 'DbgShellTest'\n#\n\n@{\n\n# Script module or binary module file associated with this manifes"
},
{
"path": "DbgShell/x64/DbgShellTest/DbgShellTest.psm1",
"chars": 13993,
"preview": "Set-StrictMode -Version Latest\n\n[void] (New-PSDrive Tests FileSystem \"$PSScriptRoot\\Tests\" -Scope Global)\n\n$script:dumps"
},
{
"path": "DbgShell/x64/DbgShellTest/Pester/CHANGELOG.md",
"chars": 15942,
"preview": "## 3.4.6 (January 13, 2017)\n - Fix bug with -Show parameter on PowerShell v4 and older [GH-677]\n - Add commas to test "
},
{
"path": "DbgShell/x64/DbgShellTest/Pester/Functions/Assertions/Be.Tests.ps1",
"chars": 3379,
"preview": "Set-StrictMode -Version Latest\n\nInModuleScope Pester {\n Describe \"PesterBe\" {\n It \"returns true if the 2 argum"
},
{
"path": "DbgShell/x64/DbgShellTest/Pester/Functions/Assertions/Be.ps1",
"chars": 4014,
"preview": "#Be\nfunction PesterBe($value, $expected) {\n return ($expected -eq $value)\n}\n\nfunction PesterBeFailureMessage($value, "
},
{
"path": "DbgShell/x64/DbgShellTest/Pester/Functions/Assertions/BeGreaterThan.Tests.ps1",
"chars": 493,
"preview": "Set-StrictMode -Version Latest\n\nInModuleScope Pester {\n Describe \"PesterBeGreaterThan\" {\n It \"passes if value "
},
{
"path": "DbgShell/x64/DbgShellTest/Pester/Functions/Assertions/BeGreaterThan.ps1",
"chars": 360,
"preview": "function PesterBeGreaterThan($value, $expected)\n{\n return [bool]($value -gt $expected)\n}\n\nfunction PesterBeGreaterTha"
},
{
"path": "DbgShell/x64/DbgShellTest/Pester/Functions/Assertions/BeLessThan.Tests.ps1",
"chars": 477,
"preview": "Set-StrictMode -Version Latest\n\nInModuleScope Pester {\n Describe \"PesterBeLessThan\" {\n It \"passes if value Les"
},
{
"path": "DbgShell/x64/DbgShellTest/Pester/Functions/Assertions/BeLessThan.ps1",
"chars": 351,
"preview": "function PesterBeLessThan($value, $expected)\n{\n return [bool]($value -lt $expected)\n}\n\nfunction PesterBeLessThanFailu"
},
{
"path": "DbgShell/x64/DbgShellTest/Pester/Functions/Assertions/BeNullOrEmpty.Tests.ps1",
"chars": 457,
"preview": "Set-StrictMode -Version Latest\n\nInModuleScope Pester {\n Describe \"PesterBeNullOrEmpty\" {\n It \"should return tr"
},
{
"path": "DbgShell/x64/DbgShellTest/Pester/Functions/Assertions/BeNullOrEmpty.ps1",
"chars": 556,
"preview": "\nfunction PesterBeNullOrEmpty($value) {\n if ($null -eq $value) {\n return $true\n }\n if ([String] -eq $val"
},
{
"path": "DbgShell/x64/DbgShellTest/Pester/Functions/Assertions/BeOfType.Tests.ps1",
"chars": 671,
"preview": "Set-StrictMode -Version Latest\n\nInModuleScope Pester {\n Describe \"PesterBeOfType\" {\n It \"passes if value is of"
},
{
"path": "DbgShell/x64/DbgShellTest/Pester/Functions/Assertions/BeOfType.ps1",
"chars": 1365,
"preview": "\nfunction PesterBeOfType($value, $expectedType) {\n trap [System.Management.Automation.PSInvalidCastException] { retur"
},
{
"path": "DbgShell/x64/DbgShellTest/Pester/Functions/Assertions/Contain.Tests.ps1",
"chars": 973,
"preview": "Set-StrictMode -Version Latest\n\nInModuleScope Pester {\n Describe \"PesterContain\" {\n Context \"when testing fil"
},
{
"path": "DbgShell/x64/DbgShellTest/Pester/Functions/Assertions/Contain.ps1",
"chars": 447,
"preview": "\nfunction PesterContain($file, $contentExpectation) {\n return ((& $SafeCommands['Get-Content'] -Encoding UTF8 $file) "
},
{
"path": "DbgShell/x64/DbgShellTest/Pester/Functions/Assertions/ContainExactly.Tests.ps1",
"chars": 838,
"preview": "Set-StrictMode -Version Latest\n\nInModuleScope Pester {\n Describe \"PesterContainExactly\" {\n Context \"when test"
},
{
"path": "DbgShell/x64/DbgShellTest/Pester/Functions/Assertions/ContainExactly.ps1",
"chars": 484,
"preview": "function PesterContainExactly($file, $contentExpectation) {\n return ((& $SafeCommands['Get-Content'] -Encoding UTF8 $"
},
{
"path": "DbgShell/x64/DbgShellTest/Pester/Functions/Assertions/Exist.Tests.ps1",
"chars": 825,
"preview": "Set-StrictMode -Version Latest\n\nInModuleScope Pester {\n Describe \"PesterExist\" {\n It \"returns true for paths t"
},
{
"path": "DbgShell/x64/DbgShellTest/Pester/Functions/Assertions/Exist.ps1",
"chars": 277,
"preview": "\nfunction PesterExist($value) {\n & $SafeCommands['Test-Path'] $value\n}\n\nfunction PesterExistFailureMessage($value) {\n"
},
{
"path": "DbgShell/x64/DbgShellTest/Pester/Functions/Assertions/Match.Tests.ps1",
"chars": 566,
"preview": "Set-StrictMode -Version Latest\n\nInModuleScope Pester {\n Describe \"Match\" {\n It \"returns true for things that m"
},
{
"path": "DbgShell/x64/DbgShellTest/Pester/Functions/Assertions/Match.ps1",
"chars": 374,
"preview": "\nfunction PesterMatch($value, $expectedMatch) {\n return ($value -match $expectedMatch)\n}\n\nfunction PesterMatchFailure"
},
{
"path": "DbgShell/x64/DbgShellTest/Pester/Functions/Assertions/MatchExactly.Tests.ps1",
"chars": 486,
"preview": "Set-StrictMode -Version Latest\n\nInModuleScope Pester {\n Describe \"MatchExactly\" {\n It \"returns true for things"
},
{
"path": "DbgShell/x64/DbgShellTest/Pester/Functions/Assertions/MatchExactly.ps1",
"chars": 412,
"preview": "\nfunction PesterMatchExactly($value, $expectedMatch) {\n return ($value -cmatch $expectedMatch)\n}\n\nfunction PesterMatc"
},
{
"path": "DbgShell/x64/DbgShellTest/Pester/Functions/Assertions/PesterThrow.Tests.ps1",
"chars": 5210,
"preview": "Set-StrictMode -Version Latest\n\nInModuleScope Pester {\n Describe \"PesterThrow\" {\n It \"returns true if the stat"
},
{
"path": "DbgShell/x64/DbgShellTest/Pester/Functions/Assertions/PesterThrow.ps1",
"chars": 2449,
"preview": "\n$ActualExceptionMessage = \"\"\n$ActualExceptionWasThrown = $false\n\n# because this is a script block, the user will have t"
},
{
"path": "DbgShell/x64/DbgShellTest/Pester/Functions/Assertions/Set-TestInconclusive.ps1",
"chars": 991,
"preview": "function New-InconclusiveErrorRecord ([string] $Message, [string] $File, [string] $Line, [string] $LineText) {\n $exce"
},
{
"path": "DbgShell/x64/DbgShellTest/Pester/Functions/Assertions/Should.Tests.ps1",
"chars": 6166,
"preview": "Set-StrictMode -Version Latest\n\nInModuleScope Pester {\n Describe \"Parse-ShouldArgs\" {\n It \"sanitizes assertion"
},
{
"path": "DbgShell/x64/DbgShellTest/Pester/Functions/Assertions/Should.ps1",
"chars": 3786,
"preview": "function Parse-ShouldArgs([array] $shouldArgs) {\n if ($null -eq $shouldArgs) { $shouldArgs = @() }\n\n $parsedArgs ="
},
{
"path": "DbgShell/x64/DbgShellTest/Pester/Functions/Assertions/Test-Assertion.ps1",
"chars": 268,
"preview": "\nfunction Test-PositiveAssertion($result) {\n if (-not $result) {\n throw \"Expecting expression to pass, but it "
},
{
"path": "DbgShell/x64/DbgShellTest/Pester/Functions/BreakAndContinue.Tests.ps1",
"chars": 443,
"preview": "Describe 'Clean handling of break and continue' {\n # If this test 'fails', it'll just cause most of the rest of the t"
},
{
"path": "DbgShell/x64/DbgShellTest/Pester/Functions/Context.Tests.ps1",
"chars": 740,
"preview": "Set-StrictMode -Version Latest\n\nDescribe 'Testing Context' {\n It 'Has a non-mandatory fixture parameter which throws "
},
{
"path": "DbgShell/x64/DbgShellTest/Pester/Functions/Context.ps1",
"chars": 2357,
"preview": "function Context {\n<#\n.SYNOPSIS\nProvides logical grouping of It blocks within a single Describe block.\n\n.DESCRIPTION\nPro"
},
{
"path": "DbgShell/x64/DbgShellTest/Pester/Functions/Coverage.Tests.ps1",
"chars": 11337,
"preview": "if ($PSVersionTable.PSVersion.Major -le 2) { return }\n\nInModuleScope Pester {\n Describe 'Code Coverage Analysis' {\n "
},
{
"path": "DbgShell/x64/DbgShellTest/Pester/Functions/Coverage.ps1",
"chars": 18257,
"preview": "if ($PSVersionTable.PSVersion.Major -le 2)\n{\n function Exit-CoverageAnalysis { }\n function Get-CoverageReport { }\n"
},
{
"path": "DbgShell/x64/DbgShellTest/Pester/Functions/Describe.Tests.ps1",
"chars": 743,
"preview": "Set-StrictMode -Version Latest\n\nDescribe 'Testing Describe' {\n It 'Has a non-mandatory fixture parameter which throws"
},
{
"path": "DbgShell/x64/DbgShellTest/Pester/Functions/Describe.ps1",
"chars": 4053,
"preview": "function Describe {\n<#\n.SYNOPSIS\nCreates a logical group of tests.\n\n.DESCRIPTION\nCreates a logical group of tests. All M"
},
{
"path": "DbgShell/x64/DbgShellTest/Pester/Functions/GlobalMock-A.Tests.ps1",
"chars": 731,
"preview": "# This script exists to create and mock a global function, then exit. The actual behavior\n# that we need to test is cov"
},
{
"path": "DbgShell/x64/DbgShellTest/Pester/Functions/GlobalMock-B.Tests.ps1",
"chars": 709,
"preview": "# This test depends on some state set up in GlobalMock-A.Tests.ps1. The behavior we're verifying\n# is that global funct"
},
{
"path": "DbgShell/x64/DbgShellTest/Pester/Functions/In.Tests.ps1",
"chars": 536,
"preview": "Set-StrictMode -Version Latest\n\nInModuleScope Pester {\n Describe \"the In statement\" {\n Setup -Dir \"test_path\"\n"
},
{
"path": "DbgShell/x64/DbgShellTest/Pester/Functions/In.ps1",
"chars": 786,
"preview": "function In {\n<#\n.SYNOPSIS\nA convenience function that executes a script from a specified path.\n\n.DESCRIPTION\nBefore the"
},
{
"path": "DbgShell/x64/DbgShellTest/Pester/Functions/InModuleScope.Tests.ps1",
"chars": 1564,
"preview": "Set-StrictMode -Version Latest\n\nDescribe \"Module scope separation\" {\n Context \"When users define variables with the s"
},
{
"path": "DbgShell/x64/DbgShellTest/Pester/Functions/InModuleScope.ps1",
"chars": 3773,
"preview": "function InModuleScope\n{\n<#\n.SYNOPSIS\n Allows you to execute parts of a test script within the\n scope of a PowerShel"
},
{
"path": "DbgShell/x64/DbgShellTest/Pester/Functions/It.Tests.ps1",
"chars": 9512,
"preview": "Set-StrictMode -Version Latest\n\nInModuleScope Pester {\n Describe 'Get-PesterResult' {\n }\n\n Describe 'It - Imple"
},
{
"path": "DbgShell/x64/DbgShellTest/Pester/Functions/It.ps1",
"chars": 11769,
"preview": "function It {\n<#\n.SYNOPSIS\nValidates the results of a test inside of a Describe block.\n\n.DESCRIPTION\nThe It command is i"
},
{
"path": "DbgShell/x64/DbgShellTest/Pester/Functions/Mock.Tests.ps1",
"chars": 59873,
"preview": "Set-StrictMode -Version Latest\n\nfunction FunctionUnderTest\n{\n [CmdletBinding()]\n param (\n [Parameter(Manda"
},
{
"path": "DbgShell/x64/DbgShellTest/Pester/Functions/Mock.ps1",
"chars": 49179,
"preview": "function Mock {\n\n<#\n.SYNOPSIS\nMocks the behavior of an existing command with an alternate\nimplementation.\n\n.DESCRIPTION"
},
{
"path": "DbgShell/x64/DbgShellTest/Pester/Functions/New-Fixture.Tests.ps1",
"chars": 3115,
"preview": "Set-StrictMode -Version Latest\n\nDescribe \"New-Fixture\" {\n It \"Name parameter is mandatory:\" {\n (get-command Ne"
},
{
"path": "DbgShell/x64/DbgShellTest/Pester/Functions/New-Fixture.ps1",
"chars": 3206,
"preview": "function New-Fixture {\n <#\n .SYNOPSIS\n This function generates two scripts, one that defines a function\n and"
},
{
"path": "DbgShell/x64/DbgShellTest/Pester/Functions/PesterState.Tests.ps1",
"chars": 14039,
"preview": "Set-StrictMode -Version Latest\n\nInModuleScope Pester {\n Describe \"New-PesterState\" {\n Context \"TestNameFilter "
},
{
"path": "DbgShell/x64/DbgShellTest/Pester/Functions/PesterState.ps1",
"chars": 19437,
"preview": "function New-PesterState\n{\n param (\n [String[]]$TagFilter,\n [String[]]$ExcludeTagFilter,\n [Strin"
},
{
"path": "DbgShell/x64/DbgShellTest/Pester/Functions/SetupTeardown.Tests.ps1",
"chars": 5385,
"preview": "Describe 'Describe-Scoped Test Case setup' {\n BeforeEach {\n $testVariable = 'From BeforeEach'\n }\n\n $test"
},
{
"path": "DbgShell/x64/DbgShellTest/Pester/Functions/SetupTeardown.ps1",
"chars": 13622,
"preview": "function BeforeEach\n{\n<#\n.SYNOPSIS\n Defines a series of steps to perform at the beginning of every It block within\n "
},
{
"path": "DbgShell/x64/DbgShellTest/Pester/Functions/TestDrive.Tests.ps1",
"chars": 4095,
"preview": "Set-StrictMode -Version Latest\n\nif ($PSVersionTable.PSVersion.Major -lt 6 -or $IsWindows)\n{\n $tempPath = $env:TEMP\n}\n"
},
{
"path": "DbgShell/x64/DbgShellTest/Pester/Functions/TestDrive.ps1",
"chars": 4621,
"preview": "function New-TestDrive ([Switch]$PassThru) {\n $Path = New-RandomTempDirectory\n $DriveName = \"TestDrive\"\n\n if (-"
},
{
"path": "DbgShell/x64/DbgShellTest/Pester/Functions/TestResults.Tests.ps1",
"chars": 27048,
"preview": "Set-StrictMode -Version Latest\n\nInModuleScope Pester {\n Describe \"Write nunit test results (Legacy)\" {\n Setup "
},
{
"path": "DbgShell/x64/DbgShellTest/Pester/Functions/TestResults.ps1",
"chars": 15973,
"preview": "function Get-HumanTime($Seconds) {\n if($Seconds -gt 0.99) {\n $time = [math]::Round($Seconds, 2)\n $unit "
},
{
"path": "DbgShell/x64/DbgShellTest/Pester/Functions/TestsRunningInCleanRunspace.Tests.ps1",
"chars": 6521,
"preview": "function Invoke-PesterInJob ($ScriptBlock, [switch] $GenerateNUnitReport)\n{\n $PesterPath = Get-Module Pester | Selec"
},
{
"path": "DbgShell/x64/DbgShellTest/Pester/LICENSE",
"chars": 598,
"preview": "Copyright 2011 Scott Muc and Manoj Mahalingam\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you"
},
{
"path": "DbgShell/x64/DbgShellTest/Pester/Pester.Tests.ps1",
"chars": 12537,
"preview": "$here = Split-Path -Parent $MyInvocation.MyCommand.Path\n\n$manifestPath = \"$here\\Pester.psd1\"\n$changeLogPath = \"$here\\"
},
{
"path": "DbgShell/x64/DbgShellTest/Pester/Pester.psd1",
"chars": 4013,
"preview": "@{\n\n# Script module or binary module file associated with this manifest.\nRootModule = 'Pester.psm1'\n\n# Version number of"
},
{
"path": "DbgShell/x64/DbgShellTest/Pester/Pester.psm1",
"chars": 34892,
"preview": "# Pester\n# Version: $version$\n# Changeset: $sha$\n\nif ($PSVersionTable.PSVersion.Major -ge 3)\n{\n $script:IgnoreErrorPr"
},
{
"path": "DbgShell/x64/DbgShellTest/Pester/README.md",
"chars": 6235,
"preview": "__Build Status:__ [\n\n$TestContext = Get-TestContext\n\n$a = New-Item a\n[string] $content1 = \"hi\"\n\nSet-Content a $conten"
},
{
"path": "DbgShell/x64/DbgShellTest/Tests/NamespaceTests/CopyItem.ps1",
"chars": 1526,
"preview": "\n$global:error.Clear()\n\n$TestContext = Get-TestContext\n\n$aDir = mkdir a\n[void] (New-Item a\\i1)\n[void] (New-Item a\\i2)\n[v"
},
{
"path": "DbgShell/x64/DbgShellTest/Tests/NamespaceTests/DriveTests.ps1",
"chars": 1243,
"preview": "\n$global:error.Clear()\n\n$TestContext = Get-TestContext\n\n[int] $initialDriveCount = (Get-PSDrive -PSProvider Debugger).Co"
},
{
"path": "DbgShell/x64/DbgShellTest/Tests/NamespaceTests/Globbing.ps1",
"chars": 4890,
"preview": "\n$global:error.Clear()\n\n$TestContext = Get-TestContext\n\n$oldPathBugginessStyle = Get-PathBugginessStyle\nPush-Location Db"
},
{
"path": "DbgShell/x64/DbgShellTest/Tests/NamespaceTests/MoveItem.ps1",
"chars": 940,
"preview": "\n$global:error.Clear()\n\n$TestContext = Get-TestContext\n\n$a = New-Item a\n[string] $content1 = \"hi\"\nSet-Content a $content"
},
{
"path": "DbgShell/x64/DbgShellTest/Tests/NamespaceTests/ProviderTests.metadata",
"chars": 1254,
"preview": "\nSet-StrictMode -Version Latest\n\nfunction PrepareForTest()\n{\n # Prepares a fresh virtual namespace for us to party on"
},
{
"path": "DbgShell/x64/DbgShellTest/Tests/NamespaceTests/RenameItem.ps1",
"chars": 952,
"preview": "\n$global:error.Clear()\n\n$TestContext = Get-TestContext\n\n$a = New-Item a\n[string] $content1 = \"hi\"\nSet-Content a $content"
},
{
"path": "DbgShell/x64/DbgShellTest/Tests/ReentrantConversion.Tests.ps1",
"chars": 4253,
"preview": "\nDescribe \"ReentrantConversion\" {\n\n Register-DbgValueConverterInfo {\n New-DbgValueConverterInfo -TypeName 'Tes"
},
{
"path": "DbgShell/x64/DbgShellTest/Tests/StlTypeConversion.Tests.ps1",
"chars": 11224,
"preview": "\nDescribe \"StlTypeConversion\" {\n\n pushd\n New-TestApp -TestApp TestNativeConsoleApp -Attach -TargetName testApp -Hi"
},
{
"path": "DbgShell/x64/DbgShellTest/Tests/TemplateMatching.Tests.ps1",
"chars": 11907,
"preview": "\nDescribe \"TemplateMatching\" {\n It \"can crack string templates\" {\n\n $typeName1 = \"std::basic_string<unsigned "
},
{
"path": "DbgShell/x64/DbgShellTest/Tests/TrickySymbolValueConversions.Tests.ps1",
"chars": 6947,
"preview": "\nDescribe \"TrickySymbolValueConversions\" {\n\n Register-DbgValueConverterInfo {\n\n # First we're going to define "
},
{
"path": "DbgShell/x64/DbgShellTest/Tests/ValueConverterQueries.Tests.ps1",
"chars": 1397,
"preview": "\nDescribe \"ValueConverterQueries\" {\n\n pushd\n\n It \"can query for symbol value converters\" {\n\n $converterInfo"
},
{
"path": "DbgShell/x64/DbgShellTest/Tests/VariantConversion.Tests.ps1",
"chars": 1047,
"preview": "\nDescribe \"VariantConversion\" {\n\n pushd\n\n It \"can convert VARIANTs\" {\n New-TestApp -TestApp TestNativeConso"
},
{
"path": "DbgShell/x64/DbgShellTest/Tests/WriteMem.Tests.ps1",
"chars": 2457,
"preview": "\nDescribe \"WriteMem\" {\n\n pushd\n New-TestApp -TestApp TestNativeConsoleApp -Attach -TargetName testApp -HiddenTarge"
},
{
"path": "DbgShell/x64/Debugger/DbgEngWrapper.dll.metagen",
"chars": 52299,
"preview": "ImageRuntimeVersion: v4.0.30319\nAssembly DbgEngWrapper, Version=1.0.*, Culture=Invariant Language (Invariant Country): \n"
},
{
"path": "DbgShell/x64/Debugger/Debugger.ArgumentCompleters.ps1",
"chars": 11512,
"preview": "\n\nif (!(Get-Command -ea Ignore Register-ArgumentCompleter))\n{\n return\n}\n\n###########################################"
},
{
"path": "DbgShell/x64/Debugger/Debugger.ArgumentCompleters.shared.ps1",
"chars": 1595,
"preview": "# This file is intended to be dot-sourced by functions in Debugger.ArgumentCompleters.ps1.\n\nfunction New-WildcardPattern"
},
{
"path": "DbgShell/x64/Debugger/Debugger.Converters.COM.ps1",
"chars": 15507,
"preview": "\nRegister-DbgValueConverterInfo {\n\n Set-StrictMode -Version Latest\n\n New-DbgValueConverterInfo -TypeName '!tagVARI"
},
{
"path": "DbgShell/x64/Debugger/Debugger.Converters.NT.ps1",
"chars": 10972,
"preview": "Register-DbgValueConverterInfo {\n Set-StrictMode -Version Latest\n\n\n New-DbgValueConverterInfo -TypeName '!_EXCEPTI"
},
{
"path": "DbgShell/x64/Debugger/Debugger.Converters.WinRT.ps1",
"chars": 321,
"preview": "\nRegister-DbgValueConverterInfo {\n\n Set-StrictMode -Version Latest\n\n\n New-DbgValueConverterInfo -TypeName @( '!Pla"
},
{
"path": "DbgShell/x64/Debugger/Debugger.Converters.stl.ps1",
"chars": 15412,
"preview": "\nRegister-DbgValueConverterInfo {\n\n Set-StrictMode -Version Latest\n\n New-DbgValueConverterInfo -TypeName '!std::ba"
},
{
"path": "DbgShell/x64/Debugger/Debugger.Converters.win32.ps1",
"chars": 2497,
"preview": "Register-DbgValueConverterInfo {\n Set-StrictMode -Version Latest\n\n New-DbgValueConverterInfo -TypeName '!_RTL_CRIT"
},
{
"path": "DbgShell/x64/Debugger/Debugger.Converters.wrl.ps1",
"chars": 2856,
"preview": "\nRegister-DbgValueConverterInfo {\n\n Set-StrictMode -Version Latest\n\n\n # We will use this \"module\" as a place to st"
},
{
"path": "DbgShell/x64/Debugger/Debugger.Converters.xaml.ps1",
"chars": 2928,
"preview": "\nRegister-DbgValueConverterInfo {\n\n Set-StrictMode -Version Latest\n\n\n New-DbgValueConverterInfo -TypeName '!CXStri"
},
{
"path": "DbgShell/x64/Debugger/Debugger.DebuggeeTypes.NT.psfmt",
"chars": 8702,
"preview": "\n#\n# Format definitions: these are analogous to the <view> entries in a .ps1xml,\n# except they are consumed by our alter"
},
{
"path": "DbgShell/x64/Debugger/Debugger.DebuggeeTypes.Win32.psfmt",
"chars": 8989,
"preview": "\n#\n# Format definitions: these are analogous to the <view> entries in a .ps1xml,\n# except they are consumed by our alter"
},
{
"path": "DbgShell/x64/Debugger/Debugger.DebuggeeTypes.atl.psfmt",
"chars": 1289,
"preview": "\n#\n# Format definitions: these are analogous to the <view> entries in a .ps1xml,\n# except they are consumed by our alter"
},
{
"path": "DbgShell/x64/Debugger/Debugger.DebuggeeTypes.clr.psfmt",
"chars": 41458,
"preview": "\n#\n# Format definitions: these are analogous to the <view> entries in a .ps1xml,\n# except they are consumed by our alter"
},
{
"path": "DbgShell/x64/Debugger/Debugger.DebuggeeTypes.psfmt",
"chars": 12868,
"preview": "\n#\n# Format definitions: these are analogous to the <view> entries in a .ps1xml,\n# except they are consumed by our alter"
},
{
"path": "DbgShell/x64/Debugger/Debugger.DebuggeeTypes.wrl.psfmt",
"chars": 1396,
"preview": "\n#\n# Format definitions: these are analogous to the <view> entries in a .ps1xml,\n# except they are consumed by our alter"
},
{
"path": "DbgShell/x64/Debugger/Debugger.DebuggeeTypes.xaml.psfmt",
"chars": 7967,
"preview": "\n#\n# Format definitions: these are analogous to the <view> entries in a .ps1xml,\n# except they are consumed by our alter"
},
{
"path": "DbgShell/x64/Debugger/Debugger.Format.Color.ps1xml",
"chars": 34422,
"preview": "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<!--\n\n WARNING: This is generated code; do not edit directly\n\n-->\n<!--\nT4 in"
},
{
"path": "DbgShell/x64/Debugger/Debugger.Format.ps1xml",
"chars": 34122,
"preview": "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<!--\n\n WARNING: This is generated code; do not edit directly\n\n-->\n<!--\nT4 in"
},
{
"path": "DbgShell/x64/Debugger/Debugger.Formatting.psm1",
"chars": 91474,
"preview": "\nSet-StrictMode -Version Latest\n\n<#\n This module defines the functions necessary to create, register, and use the\n v"
},
{
"path": "DbgShell/x64/Debugger/Debugger.psd1",
"chars": 2772,
"preview": "#\n# Module manifest for module 'Debugger'\n#\n\n@{\n\n# Script module or binary module file associated with this manifest\nRo"
},
{
"path": "DbgShell/x64/Debugger/Debugger.psfmt",
"chars": 108772,
"preview": "\n#\n# This file defines format view definitions for various types used by the\n# Debugger module, for use by the alternate"
},
{
"path": "DbgShell/x64/Debugger/Debugger.psm1",
"chars": 144627,
"preview": "Set-StrictMode -Version Latest\n\n<#\n.Synopsis\n Turns on debug tracing of the Debugger provider and select PowerShell t"
},
{
"path": "DbgShell/x64/Debugger/FmtUtils.ps1",
"chars": 5587,
"preview": "\n#\n# The following functions are common code shared by multiple format\n# definitions (in .psfmt files).\n#\n\n$script:Value"
},
{
"path": "DbgShell/x64/Debugger/GetPsContextFunc.ps1",
"chars": 4051,
"preview": "\n<#\n.SYNOPSIS\n Gets an object that represents a set of functions and variables, which can be used with ScriptBlock.In"
},
{
"path": "DbgShell/x64/Debugger/KernelMode.ps1",
"chars": 2341,
"preview": "\n#\n# We can put functions in here that are specific to kernel-mode debugging.\n#\n\n<#\n.SYNOPSIS\n Throws if you are not "
},
{
"path": "DbgShell/x64/Debugger/Microsoft.Diagnostics.Runtime.xml",
"chars": 345977,
"preview": "<?xml version=\"1.0\"?>\n<doc>\n <assembly>\n <name>Microsoft.Diagnostics.Runtime</name>\n </assembly>\n <membe"
},
{
"path": "DbgShell/x64/Debugger/OtherUtils.ps1",
"chars": 7739,
"preview": "\n#\n# We can put functions in here that are not necessarily debugger-related, like\n# type-specific utilities.\n#\n# This so"
},
{
"path": "DbgShell/x64/Debugger/Types.ps1xml",
"chars": 1628,
"preview": "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<Types>\n <!--\n ClrMd objects get their data by using our IDataReader impleme"
},
{
"path": "DbgShell/x64/Debugger/en-us/DbgProvider.dll-Help.xml",
"chars": 4662,
"preview": "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n\n<helpItems schema=\"maml\">\n\n<!-- v 1.0.0.0 -->\n<command:command xmlns:maml=\"htt"
},
{
"path": "DbgShell/x64/Debugger/en-us/about_Color.help.txt",
"chars": 4144,
"preview": "\nTOPIC\n about_Color\n\nSHORT DESCRIPTION\n\n DbgShell supports text colorization using ANSI escape codes (a la ISO/IEC"
},
{
"path": "DbgShell/x64/Debugger/en-us/about_CustomFormatting.help.txt",
"chars": 362,
"preview": "\nTOPIC\n about_CustomFormatting\n\nSHORT DESCRIPTION\n\n DbgShell includes a custom Formatting+Output (F+O) engine.\n\nLO"
},
{
"path": "DbgShell/x64/Debugger/en-us/about_CustomSymbolValueConversion.help.txt",
"chars": 1624,
"preview": "\nTOPIC\n about_CustomSymbolValueConversion\n\nSHORT DESCRIPTION\n\n DbgShell lets you get symbol values as nice objects"
},
{
"path": "DbgShell/x64/Debugger/en-us/about_DbgShell.help.txt",
"chars": 600,
"preview": "\nTOPIC\n about_DbgShell\n\nSHORT DESCRIPTION\n\n DbgShell is a PowerShell front-end for the Windows debuggers.\n\n For"
},
{
"path": "DbgShell/x64/Debugger/en-us/about_DbgShell_GettingStarted.help.txt",
"chars": 611,
"preview": "\nTOPIC\n about_DbgShell_GettingStarted\n\nSHORT DESCRIPTION\n\n DbgShell is a PowerShell front-end for the Windows debu"
},
{
"path": "DbgShell/x64/Debugger/en-us/about_DerivedTypeDetection.help.txt",
"chars": 1002,
"preview": "\nTOPIC\n about_DerivedTypeDetection\n\nSHORT DESCRIPTION\n\n DbgShell lets you see symbol values as they are, not just "
},
{
"path": "DbgShell/x64/Debugger/en-us/about_HowTo_Write_a_Symbol_Value_Converter.help.txt",
"chars": 19890,
"preview": "TOPIC\n about_HowTo_Write_a_Symbol_Value_Converter\n\nSHORT DESCRIPTION\n\n \"Symbol Value Converters\" allow DbgShell to"
},
{
"path": "DbgShell/x64/Debugger/en-us/about_MemoryCommands.help.txt",
"chars": 4005,
"preview": "TOPIC\n about_MemoryCommands\n\nSHORT DESCRIPTION\n\n With so many different commands to display and edit memory, it's "
},
{
"path": "DbgShell/x64/TypeInfoDebugging/TypeInfoDebugging.psm1",
"chars": 15564,
"preview": "Set-StrictMode -Version Latest\n\n#\n# This is just hacky stuff intended for helping debug type stuff; you shouldn't use it"
},
{
"path": "DbgShell/x64/doc/Color.md",
"chars": 3951,
"preview": "# Color\n\n### ANSI escape codes\nDbgShell.exe supports text colorization using ANSI escape codes (a la [ISO/IEC\n6429](http"
},
{
"path": "DbgShell/x64/doc/CustomFormattingEngine.md",
"chars": 13962,
"preview": "# Custom Formatting+Output Engine\n\nPowerShell is not a text-based shell; it's an object-based shell. Commands write full"
},
{
"path": "DbgShell/x64/doc/DbgEngWrapper.md",
"chars": 2081,
"preview": "# DbgEngWrapper\n\nThe dbgeng.dll API (`IDebugClient`, `IDebugEtc.`) implements a subset of COM: each\n`IDebug*` interface "
},
{
"path": "DbgShell/x64/doc/DerivedTypeDetection.md",
"chars": 648,
"preview": "# Derived Type Detection\nDbgShell lets you see symbol values as they are, not just as they are declared.\n\nFor instance, "
},
{
"path": "DbgShell/x64/doc/GettingStarted.md",
"chars": 10371,
"preview": "# Getting Started with DbgShell\n\n_DbgShell is a PowerShell front-end for the Windows debuggers. For more background see "
},
{
"path": "DbgShell/x64/doc/SymbolValueConversion.md",
"chars": 6790,
"preview": "# Custom Symbol Value Conversion\nDbgShell lets you get symbol values as nice objects. This is extremely powerful for\nscr"
},
{
"path": "DbgShell/x86/DbgShell.exe.config",
"chars": 362,
"preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<configuration>\n <startup useLegacyV2RuntimeActivationPolicy=\"true\">\n <suppor"
},
{
"path": "DbgShell/x86/DbgShellTest/DbgShellTest.psd1",
"chars": 2626,
"preview": "#\n# Module manifest for module 'DbgShellTest'\n#\n\n@{\n\n# Script module or binary module file associated with this manifes"
},
{
"path": "DbgShell/x86/DbgShellTest/DbgShellTest.psm1",
"chars": 13993,
"preview": "Set-StrictMode -Version Latest\n\n[void] (New-PSDrive Tests FileSystem \"$PSScriptRoot\\Tests\" -Scope Global)\n\n$script:dumps"
},
{
"path": "DbgShell/x86/DbgShellTest/Pester/CHANGELOG.md",
"chars": 15942,
"preview": "## 3.4.6 (January 13, 2017)\n - Fix bug with -Show parameter on PowerShell v4 and older [GH-677]\n - Add commas to test "
},
{
"path": "DbgShell/x86/DbgShellTest/Pester/Functions/Assertions/Be.Tests.ps1",
"chars": 3379,
"preview": "Set-StrictMode -Version Latest\n\nInModuleScope Pester {\n Describe \"PesterBe\" {\n It \"returns true if the 2 argum"
},
{
"path": "DbgShell/x86/DbgShellTest/Pester/Functions/Assertions/Be.ps1",
"chars": 4014,
"preview": "#Be\nfunction PesterBe($value, $expected) {\n return ($expected -eq $value)\n}\n\nfunction PesterBeFailureMessage($value, "
},
{
"path": "DbgShell/x86/DbgShellTest/Pester/Functions/Assertions/BeGreaterThan.Tests.ps1",
"chars": 493,
"preview": "Set-StrictMode -Version Latest\n\nInModuleScope Pester {\n Describe \"PesterBeGreaterThan\" {\n It \"passes if value "
},
{
"path": "DbgShell/x86/DbgShellTest/Pester/Functions/Assertions/BeGreaterThan.ps1",
"chars": 360,
"preview": "function PesterBeGreaterThan($value, $expected)\n{\n return [bool]($value -gt $expected)\n}\n\nfunction PesterBeGreaterTha"
},
{
"path": "DbgShell/x86/DbgShellTest/Pester/Functions/Assertions/BeLessThan.Tests.ps1",
"chars": 477,
"preview": "Set-StrictMode -Version Latest\n\nInModuleScope Pester {\n Describe \"PesterBeLessThan\" {\n It \"passes if value Les"
},
{
"path": "DbgShell/x86/DbgShellTest/Pester/Functions/Assertions/BeLessThan.ps1",
"chars": 351,
"preview": "function PesterBeLessThan($value, $expected)\n{\n return [bool]($value -lt $expected)\n}\n\nfunction PesterBeLessThanFailu"
},
{
"path": "DbgShell/x86/DbgShellTest/Pester/Functions/Assertions/BeNullOrEmpty.Tests.ps1",
"chars": 457,
"preview": "Set-StrictMode -Version Latest\n\nInModuleScope Pester {\n Describe \"PesterBeNullOrEmpty\" {\n It \"should return tr"
},
{
"path": "DbgShell/x86/DbgShellTest/Pester/Functions/Assertions/BeNullOrEmpty.ps1",
"chars": 556,
"preview": "\nfunction PesterBeNullOrEmpty($value) {\n if ($null -eq $value) {\n return $true\n }\n if ([String] -eq $val"
},
{
"path": "DbgShell/x86/DbgShellTest/Pester/Functions/Assertions/BeOfType.Tests.ps1",
"chars": 671,
"preview": "Set-StrictMode -Version Latest\n\nInModuleScope Pester {\n Describe \"PesterBeOfType\" {\n It \"passes if value is of"
},
{
"path": "DbgShell/x86/DbgShellTest/Pester/Functions/Assertions/BeOfType.ps1",
"chars": 1365,
"preview": "\nfunction PesterBeOfType($value, $expectedType) {\n trap [System.Management.Automation.PSInvalidCastException] { retur"
},
{
"path": "DbgShell/x86/DbgShellTest/Pester/Functions/Assertions/Contain.Tests.ps1",
"chars": 973,
"preview": "Set-StrictMode -Version Latest\n\nInModuleScope Pester {\n Describe \"PesterContain\" {\n Context \"when testing fil"
},
{
"path": "DbgShell/x86/DbgShellTest/Pester/Functions/Assertions/Contain.ps1",
"chars": 447,
"preview": "\nfunction PesterContain($file, $contentExpectation) {\n return ((& $SafeCommands['Get-Content'] -Encoding UTF8 $file) "
},
{
"path": "DbgShell/x86/DbgShellTest/Pester/Functions/Assertions/ContainExactly.Tests.ps1",
"chars": 838,
"preview": "Set-StrictMode -Version Latest\n\nInModuleScope Pester {\n Describe \"PesterContainExactly\" {\n Context \"when test"
},
{
"path": "DbgShell/x86/DbgShellTest/Pester/Functions/Assertions/ContainExactly.ps1",
"chars": 484,
"preview": "function PesterContainExactly($file, $contentExpectation) {\n return ((& $SafeCommands['Get-Content'] -Encoding UTF8 $"
},
{
"path": "DbgShell/x86/DbgShellTest/Pester/Functions/Assertions/Exist.Tests.ps1",
"chars": 825,
"preview": "Set-StrictMode -Version Latest\n\nInModuleScope Pester {\n Describe \"PesterExist\" {\n It \"returns true for paths t"
},
{
"path": "DbgShell/x86/DbgShellTest/Pester/Functions/Assertions/Exist.ps1",
"chars": 277,
"preview": "\nfunction PesterExist($value) {\n & $SafeCommands['Test-Path'] $value\n}\n\nfunction PesterExistFailureMessage($value) {\n"
},
{
"path": "DbgShell/x86/DbgShellTest/Pester/Functions/Assertions/Match.Tests.ps1",
"chars": 566,
"preview": "Set-StrictMode -Version Latest\n\nInModuleScope Pester {\n Describe \"Match\" {\n It \"returns true for things that m"
},
{
"path": "DbgShell/x86/DbgShellTest/Pester/Functions/Assertions/Match.ps1",
"chars": 374,
"preview": "\nfunction PesterMatch($value, $expectedMatch) {\n return ($value -match $expectedMatch)\n}\n\nfunction PesterMatchFailure"
},
{
"path": "DbgShell/x86/DbgShellTest/Pester/Functions/Assertions/MatchExactly.Tests.ps1",
"chars": 486,
"preview": "Set-StrictMode -Version Latest\n\nInModuleScope Pester {\n Describe \"MatchExactly\" {\n It \"returns true for things"
},
{
"path": "DbgShell/x86/DbgShellTest/Pester/Functions/Assertions/MatchExactly.ps1",
"chars": 412,
"preview": "\nfunction PesterMatchExactly($value, $expectedMatch) {\n return ($value -cmatch $expectedMatch)\n}\n\nfunction PesterMatc"
},
{
"path": "DbgShell/x86/DbgShellTest/Pester/Functions/Assertions/PesterThrow.Tests.ps1",
"chars": 5210,
"preview": "Set-StrictMode -Version Latest\n\nInModuleScope Pester {\n Describe \"PesterThrow\" {\n It \"returns true if the stat"
},
{
"path": "DbgShell/x86/DbgShellTest/Pester/Functions/Assertions/PesterThrow.ps1",
"chars": 2449,
"preview": "\n$ActualExceptionMessage = \"\"\n$ActualExceptionWasThrown = $false\n\n# because this is a script block, the user will have t"
},
{
"path": "DbgShell/x86/DbgShellTest/Pester/Functions/Assertions/Set-TestInconclusive.ps1",
"chars": 991,
"preview": "function New-InconclusiveErrorRecord ([string] $Message, [string] $File, [string] $Line, [string] $LineText) {\n $exce"
},
{
"path": "DbgShell/x86/DbgShellTest/Pester/Functions/Assertions/Should.Tests.ps1",
"chars": 6166,
"preview": "Set-StrictMode -Version Latest\n\nInModuleScope Pester {\n Describe \"Parse-ShouldArgs\" {\n It \"sanitizes assertion"
},
{
"path": "DbgShell/x86/DbgShellTest/Pester/Functions/Assertions/Should.ps1",
"chars": 3786,
"preview": "function Parse-ShouldArgs([array] $shouldArgs) {\n if ($null -eq $shouldArgs) { $shouldArgs = @() }\n\n $parsedArgs ="
},
{
"path": "DbgShell/x86/DbgShellTest/Pester/Functions/Assertions/Test-Assertion.ps1",
"chars": 268,
"preview": "\nfunction Test-PositiveAssertion($result) {\n if (-not $result) {\n throw \"Expecting expression to pass, but it "
},
{
"path": "DbgShell/x86/DbgShellTest/Pester/Functions/BreakAndContinue.Tests.ps1",
"chars": 443,
"preview": "Describe 'Clean handling of break and continue' {\n # If this test 'fails', it'll just cause most of the rest of the t"
},
{
"path": "DbgShell/x86/DbgShellTest/Pester/Functions/Context.Tests.ps1",
"chars": 740,
"preview": "Set-StrictMode -Version Latest\n\nDescribe 'Testing Context' {\n It 'Has a non-mandatory fixture parameter which throws "
},
{
"path": "DbgShell/x86/DbgShellTest/Pester/Functions/Context.ps1",
"chars": 2357,
"preview": "function Context {\n<#\n.SYNOPSIS\nProvides logical grouping of It blocks within a single Describe block.\n\n.DESCRIPTION\nPro"
},
{
"path": "DbgShell/x86/DbgShellTest/Pester/Functions/Coverage.Tests.ps1",
"chars": 11337,
"preview": "if ($PSVersionTable.PSVersion.Major -le 2) { return }\n\nInModuleScope Pester {\n Describe 'Code Coverage Analysis' {\n "
},
{
"path": "DbgShell/x86/DbgShellTest/Pester/Functions/Coverage.ps1",
"chars": 18257,
"preview": "if ($PSVersionTable.PSVersion.Major -le 2)\n{\n function Exit-CoverageAnalysis { }\n function Get-CoverageReport { }\n"
},
{
"path": "DbgShell/x86/DbgShellTest/Pester/Functions/Describe.Tests.ps1",
"chars": 743,
"preview": "Set-StrictMode -Version Latest\n\nDescribe 'Testing Describe' {\n It 'Has a non-mandatory fixture parameter which throws"
},
{
"path": "DbgShell/x86/DbgShellTest/Pester/Functions/Describe.ps1",
"chars": 4053,
"preview": "function Describe {\n<#\n.SYNOPSIS\nCreates a logical group of tests.\n\n.DESCRIPTION\nCreates a logical group of tests. All M"
},
{
"path": "DbgShell/x86/DbgShellTest/Pester/Functions/GlobalMock-A.Tests.ps1",
"chars": 731,
"preview": "# This script exists to create and mock a global function, then exit. The actual behavior\n# that we need to test is cov"
},
{
"path": "DbgShell/x86/DbgShellTest/Pester/Functions/GlobalMock-B.Tests.ps1",
"chars": 709,
"preview": "# This test depends on some state set up in GlobalMock-A.Tests.ps1. The behavior we're verifying\n# is that global funct"
},
{
"path": "DbgShell/x86/DbgShellTest/Pester/Functions/In.Tests.ps1",
"chars": 536,
"preview": "Set-StrictMode -Version Latest\n\nInModuleScope Pester {\n Describe \"the In statement\" {\n Setup -Dir \"test_path\"\n"
},
{
"path": "DbgShell/x86/DbgShellTest/Pester/Functions/In.ps1",
"chars": 786,
"preview": "function In {\n<#\n.SYNOPSIS\nA convenience function that executes a script from a specified path.\n\n.DESCRIPTION\nBefore the"
},
{
"path": "DbgShell/x86/DbgShellTest/Pester/Functions/InModuleScope.Tests.ps1",
"chars": 1564,
"preview": "Set-StrictMode -Version Latest\n\nDescribe \"Module scope separation\" {\n Context \"When users define variables with the s"
},
{
"path": "DbgShell/x86/DbgShellTest/Pester/Functions/InModuleScope.ps1",
"chars": 3773,
"preview": "function InModuleScope\n{\n<#\n.SYNOPSIS\n Allows you to execute parts of a test script within the\n scope of a PowerShel"
},
{
"path": "DbgShell/x86/DbgShellTest/Pester/Functions/It.Tests.ps1",
"chars": 9512,
"preview": "Set-StrictMode -Version Latest\n\nInModuleScope Pester {\n Describe 'Get-PesterResult' {\n }\n\n Describe 'It - Imple"
},
{
"path": "DbgShell/x86/DbgShellTest/Pester/Functions/It.ps1",
"chars": 11769,
"preview": "function It {\n<#\n.SYNOPSIS\nValidates the results of a test inside of a Describe block.\n\n.DESCRIPTION\nThe It command is i"
},
{
"path": "DbgShell/x86/DbgShellTest/Pester/Functions/Mock.Tests.ps1",
"chars": 59873,
"preview": "Set-StrictMode -Version Latest\n\nfunction FunctionUnderTest\n{\n [CmdletBinding()]\n param (\n [Parameter(Manda"
},
{
"path": "DbgShell/x86/DbgShellTest/Pester/Functions/Mock.ps1",
"chars": 49179,
"preview": "function Mock {\n\n<#\n.SYNOPSIS\nMocks the behavior of an existing command with an alternate\nimplementation.\n\n.DESCRIPTION"
}
]
// ... and 149 more files (download for full content)
About this extraction
This page contains the full source code of the giMini/mimiDbg GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 349 files (3.1 MB), approximately 822.6k tokens. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.