Skip to content

Commit

Permalink
Standardize container name and type validation (#2379)
Browse files Browse the repository at this point in the history
* Add Name-property to Container

* Validate Container Type in setter

* Remove redundant container type validation

* Cleanup unused code

* Remove merge conflict artifacts

* Refactor
  • Loading branch information
fflaten committed Apr 29, 2024
1 parent 7889a88 commit 1a316c3
Show file tree
Hide file tree
Showing 9 changed files with 84 additions and 142 deletions.
19 changes: 17 additions & 2 deletions src/csharp/Pester/Container.cs
@@ -1,5 +1,4 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;

Expand Down Expand Up @@ -48,7 +47,13 @@ public static Container CreateFromFile(FileInfo file)
};
}

public string Type { get; set; }
public string Name { get => ToStringConverter.ContainerItemToString(Type, Item); }
private string _type = Constants.File;
public string Type
{
get => _type;
set => SetContainerType(ref _type, value);
}
public object Item { get; set; }
public object Data { get; set; }
public List<Block> Blocks { get; set; } = new List<Block>();
Expand Down Expand Up @@ -77,5 +82,15 @@ public override string ToString()
{
return ToStringConverter.ContainerToString(this);
}

internal static void SetContainerType(ref string property, string value)
{
property = value.ToLower() switch
{
"file" => Constants.File,
"scriptblock" => Constants.ScriptBlock,
_ => throw new ArgumentOutOfRangeException("value", $"Type must be '{Constants.File}' or '{Constants.ScriptBlock}'"),
};
}
}
}
12 changes: 11 additions & 1 deletion src/csharp/Pester/ContainerInfo.cs
Expand Up @@ -11,8 +11,18 @@ public static ContainerInfo Create()
return new ContainerInfo();
}

public string Type { get; set; } = "File";
private string _type = Constants.File;
public string Type
{
get => _type;
set => Container.SetContainerType(ref _type, value);
}
public object Item { get; set; }
public object Data { get; set; }

public override string ToString()
{
return ToStringConverter.ContainerInfoToString(this);
}
}
}
39 changes: 18 additions & 21 deletions src/csharp/Pester/ToStringConverter.cs
@@ -1,4 +1,4 @@
using System;
using System.IO;
using System.Management.Automation;

namespace Pester
Expand All @@ -18,29 +18,26 @@ static string ResultToString(string result)
};
}

internal static string ContainerToString(Container container)
internal static string ContainerItemToString(string type, object item)
{
string path;
switch (container.Type)
return type switch
{
case Constants.File:
path = container.Item.ToString();
break;
case Constants.ScriptBlock:
path = "<ScriptBlock>";
if (container.Item is ScriptBlock s) {
if (!string.IsNullOrWhiteSpace(s.File))
{
path += $":{s.File}:{s.StartPosition.StartLine}";
}
}
break;
default:
path = $"<{container.Type}>";
break;
}
Constants.File => item is FileInfo f ? f.FullName : item.ToString(),
Constants.ScriptBlock => item is ScriptBlock s && !string.IsNullOrWhiteSpace(s.File)
? $"<ScriptBlock>:{s.File}:{s.StartPosition.StartLine}"
: "<ScriptBlock>",
_ => $"<{type}>"
};
}

internal static string ContainerToString(Container container)
{
return $"{ResultToString(container.Result)} {container.Name}";
}

return $"{ResultToString(container.Result)} {path}";
internal static string ContainerInfoToString(ContainerInfo containerInfo)
{
return ContainerItemToString(containerInfo.Type, containerInfo.Item);
}

internal static string TestToString(Test test)
Expand Down
79 changes: 14 additions & 65 deletions src/functions/Output.ps1
Expand Up @@ -200,44 +200,13 @@ function Write-PesterStart {
$Context
)
process {
# if (-not ( $Context.Show | Has-Flag 'All, Fails, Header')) {
# return
# }

$OFS = $ReportStrings.MessageOfs

$hash = @{
Files = [System.Collections.Generic.List[object]]@()
ScriptBlocks = 0
}

foreach ($c in $Context.Containers) {
switch ($c.Type) {
"File" { $null = $hash.Files.Add($c.Item.FullName) }
"ScriptBlock" { $null = $hash.ScriptBlocks++ }
Default { throw "$($c.Type) is not supported." }
}
}

$moduleInfo = $MyInvocation.MyCommand.ScriptBlock.Module
$moduleVersion = $moduleInfo.Version.ToString()
if ($moduleInfo.PrivateData.PSData.Prerelease) {
$moduleVersion += "-$($moduleInfo.PrivateData.PSData.Prerelease)"
}
$message = $ReportStrings.VersionMessage -f $moduleVersion

# todo write out filters that are applied
# if ($PesterState.TestNameFilter) {
# $message += $ReportStrings.FilterMessage -f "$($PesterState.TestNameFilter)"
# }
# if ($PesterState.ScriptBlockFilter) {
# $m = $(foreach ($m in $PesterState.ScriptBlockFilter) { "$($m.Path):$($m.Line)" }) -join ", "
# $message += $ReportStrings.FilterMessage -f $m
# }
# if ($PesterState.TagFilter) {
# $message += $ReportStrings.TagMessage -f "$($PesterState.TagFilter)"
# }

Write-PesterHostMessage -ForegroundColor $ReportTheme.Discovery $message
}
}
Expand All @@ -253,15 +222,15 @@ function ConvertTo-PesterResult {
$testResult = @{
Name = $Name
Time = $time
FailureMessage = ""
StackTrace = ""
FailureMessage = ''
StackTrace = ''
ErrorRecord = $null
Success = $false
Result = "Failed"
Result = 'Failed'
}

if (-not $ErrorRecord) {
$testResult.Result = "Passed"
$testResult.Result = 'Passed'
$testResult.Success = $true
return $testResult
}
Expand All @@ -278,13 +247,13 @@ function ConvertTo-PesterResult {
if (-not $Pester.Strict) {
switch ($ErrorRecord.FullyQualifiedErrorID) {
PesterTestInconclusive {
$testResult.Result = "Inconclusive"; break;
$testResult.Result = 'Inconclusive'; break;
}
PesterTestPending {
$testResult.Result = "Pending"; break;
$testResult.Result = 'Pending'; break;
}
PesterTestSkipped {
$testResult.Result = "Skipped"; break;
$testResult.Result = 'Skipped'; break;
}
}
}
Expand All @@ -306,7 +275,7 @@ function ConvertTo-PesterResult {
function Write-PesterReport {
param (
[Parameter(mandatory = $true, valueFromPipeline = $true)]
$RunResult
[Pester.Run] $RunResult
)
# if(-not ($PesterState.Show | Has-Flag Summary)) { return }

Expand Down Expand Up @@ -380,25 +349,15 @@ function Write-PesterReport {
Write-PesterHostMessage ($ReportStrings.TestsNotRun -f $RunResult.NotRunCount) -Foreground $NotRun

if (0 -lt $RunResult.FailedBlocksCount) {
Write-PesterHostMessage ("BeforeAll \ AfterAll failed: {0}" -f $RunResult.FailedBlocksCount) -Foreground $ReportTheme.Fail
Write-PesterHostMessage ('BeforeAll \ AfterAll failed: {0}' -f $RunResult.FailedBlocksCount) -Foreground $ReportTheme.Fail
Write-PesterHostMessage ($(foreach ($b in $RunResult.FailedBlocks) { " - $($b.Path -join '.')" }) -join [Environment]::NewLine) -Foreground $ReportTheme.Fail
}

if (0 -lt $RunResult.FailedContainersCount) {
$cs = foreach ($container in $RunResult.FailedContainers) {
$path = if ("File" -eq $container.Type) {
$container.Item.FullName
}
elseif ("ScriptBlock" -eq $container.Type) {
"<ScriptBlock>$($container.Item.File):$($container.Item.StartPosition.StartLine)"
}
else {
throw "Container type '$($container.Type)' is not supported."
}

" - $path"
" - $($container.Name)"
}
Write-PesterHostMessage ("Container failed: {0}" -f $RunResult.FailedContainersCount) -Foreground $ReportTheme.Fail
Write-PesterHostMessage ('Container failed: {0}' -f $RunResult.FailedContainersCount) -Foreground $ReportTheme.Fail
Write-PesterHostMessage ($cs -join [Environment]::NewLine) -Foreground $ReportTheme.Fail
}
# & $SafeCommands['Write-Host'] ($ReportStrings.TestsPending -f $RunResult.PendingCount) -Foreground $Pending -NoNewLine
Expand Down Expand Up @@ -553,7 +512,7 @@ function ConvertTo-FailureLines {
if ($true) {
# no code
# non inlined scripts will have different paths just omit everything from the src folder
$path = [regex]::Escape(($PSScriptRoot | & $SafeCommands["Split-Path"]))
$path = [regex]::Escape(($PSScriptRoot | & $SafeCommands['Split-Path']))
[String]$isPesterFunction = "^at .*, .*$path.*: line [0-9]*$"
[String]$isShould = "^at (Should<End>|Invoke-Assertion), .*$path.*: line [0-9]*$"
}
Expand Down Expand Up @@ -619,18 +578,8 @@ function Get-WriteScreenPlugin ($Verbosity) {
$p.ContainerDiscoveryEnd = {
param ($Context)

if ("Failed" -eq $Context.Block.Result) {
$path = if ("File" -eq $container.Type) {
$container.Item.FullName
}
elseif ("ScriptBlock" -eq $container.Type) {
"<ScriptBlock>$($container.Item.File):$($container.Item.StartPosition.StartLine)"
}
else {
throw "Container type '$($container.Type)' is not supported."
}

$errorHeader = "[-] Discovery in $($path) failed with:"
if ('Failed' -eq $Context.Block.Result) {
$errorHeader = "[-] Discovery in $($Context.BlockContainer) failed with:"

$formatErrorParams = @{
Err = $Context.Block.ErrorRecord
Expand Down
21 changes: 5 additions & 16 deletions src/functions/TestResults.JUnit4.ps1
@@ -1,5 +1,5 @@
function Write-JUnitReport {
param($Result, [System.Xml.XmlWriter] $XmlWriter)
param([Pester.Run] $Result, [System.Xml.XmlWriter] $XmlWriter)
# Write the XML Declaration
$XmlWriter.WriteStartDocument($false)

Expand All @@ -24,7 +24,7 @@

function Write-JUnitTestResultAttributes {
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns','')]
param($Result, [System.Xml.XmlWriter] $XmlWriter)
param([Pester.Run] $Result, [System.Xml.XmlWriter] $XmlWriter)

$XmlWriter.WriteAttributeString('xmlns', 'xsi', $null, 'http://www.w3.org/2001/XMLSchema-instance')
$XmlWriter.WriteAttributeString('xsi', 'noNamespaceSchemaLocation', [Xml.Schema.XmlSchema]::InstanceNamespace , 'junit_schema_4.xsd')
Expand All @@ -38,27 +38,16 @@ function Write-JUnitTestResultAttributes {

function Write-JUnitTestSuiteElements {
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns','')]
param($Container, [System.Xml.XmlWriter] $XmlWriter, [uint16] $Id)
param([Pester.Container] $Container, [System.Xml.XmlWriter] $XmlWriter, [uint16] $Id)

$XmlWriter.WriteStartElement('testsuite')

if ('File' -eq $Container.Type) {
$path = $Container.Item.FullName
}
elseif ('ScriptBlock' -eq $Container.Type) {
$path = "<ScriptBlock>$($Container.Item.File):$($Container.Item.StartPosition.StartLine)"
}
else {
throw "Container type '$($Container.Type)' is not supported."
}

Write-JUnitTestSuiteAttributes -Action $Container -XmlWriter $XmlWriter -Package $path -Id $Id

Write-JUnitTestSuiteAttributes -Action $Container -XmlWriter $XmlWriter -Package $container.Name -Id $Id

$testResults = [Pester.Factory]::CreateCollection()
Fold-Container -Container $Container -OnTest { param ($t) if ($t.ShouldRun) { $testResults.Add($t) } }
foreach ($t in $testResults) {
Write-JUnitTestCaseElements -TestResult $t -XmlWriter $XmlWriter -Package $path
Write-JUnitTestCaseElements -TestResult $t -XmlWriter $XmlWriter -Package $container.Name
}

$XmlWriter.WriteEndElement()
Expand Down
17 changes: 4 additions & 13 deletions src/functions/TestResults.NUnit25.ps1
@@ -1,5 +1,5 @@
function Write-NUnitReport {
param($Result, [System.Xml.XmlWriter] $XmlWriter)
param([Pester.Run] $Result, [System.Xml.XmlWriter] $XmlWriter)
# Write the XML Declaration
$XmlWriter.WriteStartDocument($false)

Expand All @@ -14,7 +14,7 @@

function Write-NUnitTestResultAttributes {
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '')]
param($Result, [System.Xml.XmlWriter] $XmlWriter)
param([Pester.Run] $Result, [System.Xml.XmlWriter] $XmlWriter)

$XmlWriter.WriteAttributeString('xmlns', 'xsi', $null, 'http://www.w3.org/2001/XMLSchema-instance')
$XmlWriter.WriteAttributeString('xsi', 'noNamespaceSchemaLocation', [Xml.Schema.XmlSchema]::InstanceNamespace , 'nunit_schema_2.5.xsd')
Expand All @@ -33,7 +33,7 @@ function Write-NUnitTestResultAttributes {

function Write-NUnitTestResultChildNodes {
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '')]
param($Result, [System.Xml.XmlWriter] $XmlWriter)
param([Pester.Run] $Result, [System.Xml.XmlWriter] $XmlWriter)

Write-NUnitEnvironmentInformation -Result $Result -XmlWriter $XmlWriter
Write-NUnitCultureInformation -Result $Result -XmlWriter $XmlWriter
Expand All @@ -53,16 +53,7 @@ function Write-NUnitTestResultChildNodes {
continue
}

if ('File' -eq $container.Type) {
$path = $container.Item.FullName
}
elseif ('ScriptBlock' -eq $container.Type) {
$path = "<ScriptBlock>$($container.Item.File):$($container.Item.StartPosition.StartLine)"
}
else {
throw "Container type '$($container.Type)' is not supported."
}
Write-NUnitTestSuiteElements -XmlWriter $XmlWriter -Node $container -Path $path
Write-NUnitTestSuiteElements -XmlWriter $XmlWriter -Node $container -Path $container.Name
}

$XmlWriter.WriteEndElement()
Expand Down

0 comments on commit 1a316c3

Please sign in to comment.