Skip to content

Commit ec9745f

Browse files
committed
Update tests for Pester 5.x
1 parent 0ade8f4 commit ec9745f

27 files changed

+1244
-960
lines changed

Build.build.ps1

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,15 @@ param(
1919
# Collect code coverage when tests are run
2020
[switch]$CollectCoverage,
2121

22+
# The PesterFilter from New-PesterConfiguration.
23+
# Supports specifying any of:
24+
# Tag: Tags of Describe, Context or It to be run.
25+
# ExcludeTag: Tags of Describe, Context or It to be excluded from the run.
26+
# Line: Filter by file and scriptblock start line, useful to run parsed tests programmatically to avoid problems with expanded names. Example: 'C:\tests\file1.Tests.ps1:37'
27+
# ExcludeLine: Exclude by file and scriptblock start line, takes precedence over Line.
28+
# FullName: Full name of test with -like wildcards, joined by dot. Example: '*.describe Get-Item.test1'
29+
[hashtable]$PesterFilter,
30+
2231
# Which projects to build
2332
[Alias("Projects")]
2433
$dotnetProjects = @(),
@@ -39,6 +48,7 @@ $ErrorView = 'DetailedView'
3948

4049
# The name of the module to publish
4150
$script:PSModuleName = "TerminalBlocks"
51+
$script:RequiredCodeCoverage = 0.85
4252
# Use Env because Earthly can override it
4353
$Env:OUTPUT_ROOT ??= Join-Path $BuildRoot Modules
4454

RequiredModules.psd1

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
@{
33
Configuration = "[1.5.0, 2.0)"
44
Metadata = "[1.5.1, 2.0)"
5-
Pester = "[4.10.1,5.0)"
5+
Pester = "[5.6.1, 6.0)"
66
ModuleBuilder = "[3.0.0, 4.0)"
77
PSScriptAnalyzer = "[1.21.0,2.0)"
88
PowerShellGet = "2.0.4"

Source/Private/CompressToBase64.ps1

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
function CompressToBase64 {
2+
<#
3+
.SYNOPSIS
4+
Compresses and encodes a module file for embedding into a script
5+
.DESCRIPTION
6+
Reads the raw bytes and then compress (gzip) them, before base64 encoding the result
7+
.EXAMPLE
8+
Get-ChildItem *.dll, *.psm1 | CompressToBase64 -ExpandScript ImportBase64Module > Script.ps1
9+
10+
Script.ps1 will contain the base64 encoded (and compressed) contents of the files, piped to the ImportBase64Module function
11+
.LINK
12+
ImportBase64Module
13+
#>
14+
[CmdletBinding(DefaultParameterSetName = "Base64")]
15+
[OutputType([string])]
16+
param(
17+
# The path to the dll or script file to compress
18+
[Parameter(Mandatory, Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName)]
19+
[Alias("PSPath")]
20+
[string[]]$Path,
21+
22+
# If set, wraps the Base64 encoded content in the specified command
23+
[Parameter(Mandatory, Position = 1, ParameterSetName = "ExpandScriptName")]
24+
[string]$ExpandScriptName,
25+
26+
# If set, wraps the Base64 encoded content in the specified command
27+
[Parameter(Mandatory, Position = 1, ParameterSetName = "ExpandScript")]
28+
[ScriptBlock]$ExpandScript
29+
)
30+
begin {
31+
$Result = @()
32+
if ($ExpandScriptName -and !$ExpandScript) {
33+
$ExpandScript = (Get-Command $ExpandScriptName).ScriptBlock
34+
}
35+
}
36+
process {
37+
foreach ($File in $Path | Convert-Path) {
38+
$Source = [System.IO.MemoryStream][System.IO.File]::ReadAllBytes($File)
39+
$OutputStream = [System.IO.Compression.DeflateStream]::new(
40+
[System.IO.MemoryStream]::new(),
41+
[System.IO.Compression.CompressionMode]::Compress)
42+
$Source.CopyTo($OutputStream)
43+
$OutputStream.Flush()
44+
$ByteArray = $OutputStream.BaseStream.ToArray()
45+
if (!$ExpandScript) {
46+
[Convert]::ToBase64String($ByteArray)
47+
} else {
48+
$Result += [Convert]::ToBase64String($ByteArray)
49+
}
50+
}
51+
}
52+
end {
53+
if ($ExpandScript) {
54+
[ScriptBlock]::Create("@(`n'$($Result -join "'`n'")'`n)|.{`n${ExpandScript}`n}").ToString()
55+
}
56+
}
57+
}

Source/Private/CopyReadMe.ps1

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
11
function CopyReadMe {
2+
<#
3+
.SYNOPSIS
4+
Copy the readme file as an about_ help file
5+
#>
26
[CmdletBinding()]
37
param(
48
# The path to the ReadMe document to copy
@@ -22,19 +26,18 @@ function CopyReadMe {
2226
[Switch]$Force
2327
)
2428
process {
25-
# Copy the readme file as an about_ help file
26-
Write-Verbose "Test for ReadMe: $Pwd/$($ReadMe)"
29+
Write-Verbose "Test for ReadMe: $ReadMe"
2730
if ($ReadMe -and (Test-Path $ReadMe -PathType Leaf)) {
2831
# Make sure there's a language path
2932
$LanguagePath = Join-Path $OutputDirectory $Culture
3033
if (!(Test-Path $LanguagePath -PathType Container)) {
34+
Write-Verbose "Create language path: $LanguagePath"
3135
$null = New-Item $LanguagePath -Type Directory -Force
3236
}
33-
Write-Verbose "Copy ReadMe to: $LanguagePath"
3437

3538
$about_module = Join-Path $LanguagePath "about_$($ModuleName).help.txt"
3639
if (!(Test-Path $about_module)) {
37-
Write-Verbose "Turn readme into about_module"
40+
Write-Verbose "Copy $ReadMe to: $about_module"
3841
Copy-Item -LiteralPath $ReadMe -Destination $about_module -Force:$Force
3942
}
4043
}

Source/Private/ImportBase64Module.ps1

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# The comment-based help for this function is outside the function to avoid packing it
2+
# Normally, I put it inside, but I do not want this in packed scripts
3+
4+
<#
5+
.SYNOPSIS
6+
Expands Base64+GZip strings and loads the result as an assembly or module
7+
.DESCRIPTION
8+
Converts Base64 encoded string to bytes and decompresses (gzip) it.
9+
If the result is a valid assembly, it is loaded.
10+
Otherwise, it is imported as a module.
11+
.PARAMETER Base64Content
12+
A Base64 encoded and deflated assembly or script
13+
.LINK
14+
CompressToBase64
15+
#>
16+
function ImportBase64Module {
17+
[CmdletBinding(DefaultParameterSetName = "ByteArray")]
18+
param(
19+
[Parameter(Mandatory, ValueFromPipeline)]
20+
[string]$Base64Content
21+
)
22+
process {
23+
$Out = [System.IO.MemoryStream]::new()
24+
$In = [System.IO.MemoryStream][System.Convert]::FromBase64String($Base64Content)
25+
$zip = [System.IO.Compression.DeflateStream]::new($In, [System.IO.Compression.CompressionMode]::Decompress)
26+
$zip.CopyTo($Out)
27+
trap [System.IO.InvalidDataException] {
28+
Write-Debug "Base64Content not Compressed. Skipping Deflate."
29+
$In.CopyTo($Out)
30+
continue
31+
}
32+
$null = $Out.Seek(0, "Begin")
33+
$null = [System.Reflection.Assembly]::Load($Out.ToArray())
34+
trap [BadImageFormatException] {
35+
Write-Debug "Base64Content not an Assembly. Trying New-Module and ScriptBlock.Create."
36+
$null = $Out.Seek(0, "Begin")
37+
# Use StreamReader to handle possible BOM
38+
$Source = [System.IO.StreamReader]::new($Out, $true).ReadToEnd()
39+
$null = New-Module ([ScriptBlock]::Create($Source)) -Verbose:$false | Import-Module -Scope Global -Verbose:$false
40+
continue
41+
}
42+
}
43+
}

Source/Private/MoveUsingStatements.ps1

Lines changed: 0 additions & 77 deletions
This file was deleted.

Source/Public/Move-UsingStatement.ps1

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
using namespace System.Management.Automation.Language
2+
3+
function Move-UsingStatement {
4+
<#
5+
.SYNOPSIS
6+
A Script Generator that commetnts out using statements and copies them to the top of the file
7+
.DESCRIPTION
8+
Move-UsingStatement supports having using statements repeated in multiple files that are merged by ModuleBuilder.
9+
When all the files are merged together, the using statements from individual files
10+
don't necessarily end up at the beginning of the PSM1, which creates Parsing Errors.
11+
12+
This function uses the AST to generate TextReplacements to:
13+
1. Comment out the original using statements (to preserve line numbering)
14+
2. Insert the using statements (conserving order, but removing duplicates) at the top of the script
15+
#>
16+
[CmdletBinding()]
17+
[OutputType([TextReplacement])]
18+
param(
19+
# The AST of the original script module to refactor
20+
[Parameter(Mandatory, ValueFromPipelineByPropertyName)]
21+
[Alias("Ast")]
22+
[Ast]$InputObject,
23+
24+
# Parser Errors from parsing the original script module
25+
[Parameter(ValueFromPipelineByPropertyName)]
26+
[AllowNull()]
27+
[ParseError[]]$ParseErrors
28+
)
29+
process {
30+
# Avoid modifying the file if there's no Parsing Error caused by Using Statements or other errors
31+
if (!$ParseErrors.Where{ $_.ErrorId -eq 'UsingMustBeAtStartOfScript' }) {
32+
Write-Debug "No using statement errors found."
33+
return
34+
} else {
35+
# as decided https://github.com/PoshCode/ModuleBuilder/issues/96
36+
Write-Debug "Parsing errors found. We'll still attempt to Move using statements."
37+
}
38+
39+
# Find all Using statements including those non erroring (to conserve their order)
40+
$UsingStatementExtents = $InputObject.FindAll(
41+
{ $Args[0] -is [System.Management.Automation.Language.UsingStatementAst] },
42+
$false
43+
).Extent
44+
45+
# Edit the Script content by commenting out existing statements (conserving line numbering)
46+
$StatementsToCopy = [System.Collections.Generic.HashSet[string]]::new([StringComparer]::OrdinalIgnoreCase)
47+
48+
foreach ($UsingSatement in $UsingStatementExtents) {
49+
[TextReplacement]@{
50+
StartOffset = $UsingSatement.StartOffset
51+
EndOffset = $UsingSatement.EndOffset
52+
Text = '# ' + $UsingSatement.Text
53+
}
54+
# Keep track of unique statements we'll need to insert at the top
55+
$null = $StatementsToCopy.Add($UsingSatement.Text)
56+
}
57+
if ($StatementsToCopy.Count -gt 0) {
58+
[TextReplacement]@{
59+
StartOffset = 0
60+
EndOffset = 0
61+
Text = ($StatementsToCopy -join "`r`n")+ "`r`n"
62+
}
63+
}
64+
}
65+
}
Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,31 @@
1-
#requires -Module ModuleBuilder
21
. $PSScriptRoot\..\Convert-FolderSeparator.ps1
32

43
Describe "Parameters.Set in build manifest" -Tag Integration {
54
BeforeAll {
5+
# This file should not be deleted by the build, because VersionedOutput defaults true now
6+
# So the actual Build output will be ../Result3/Parameters/3.0.0
67
New-Item $PSScriptRoot\Result3\Parameters\ReadMe.md -ItemType File -Force
8+
79
$Output = Build-Module $PSScriptRoot\Parameters\build.psd1
810
if ($Output) {
911
$Module = [IO.Path]::ChangeExtension($Output.Path, "psm1")
1012
$Metadata = Import-Metadata $Output.Path
1113
}
1214
}
1315

14-
It "Passthru works" {
16+
It "Passthru can be set from build.psd1" {
1517
$Output | Should -Not -BeNullOrEmpty
1618
}
1719

18-
It "The Target is Build" {
19-
"$PSScriptRoot\Result3\Parameters\ReadMe.md" | Should -Exist
20+
It "The version can be set from build.psd1" {
21+
$Metadata.ModuleVersion | Should -Be "3.0.0"
2022
}
2123

22-
It "The version is set" {
23-
$Metadata.ModuleVersion | Should -Be "3.0.0"
24+
It "Files outside the Output should not be cleaned up or overwritten" {
25+
"$PSScriptRoot\Result3\Parameters\ReadMe.md" | Should -Exist
2426
}
2527

26-
It "The PreRelease is set" {
28+
It "The PreRelease is set properly even when set from build.psd1" {
2729
$Metadata.PrivateData.PSData.Prerelease | Should -Be 'alpha001'
2830
}
2931
}

0 commit comments

Comments
 (0)