Skip to content

Commit

Permalink
Replace New-Object calls with ::new() (#2469)
Browse files Browse the repository at this point in the history
* Replace New-Object with ::new()

* Remove unused helper method

* Replace dynamic New-Object usage with ::new()

* Update build script

* Update Pester.BuildAnalyzerRules

* Fix missing cast in Get-ShouldOperator
  • Loading branch information
fflaten authored May 20, 2024
1 parent 6a50365 commit 1a3cad0
Show file tree
Hide file tree
Showing 9 changed files with 30 additions and 40 deletions.
4 changes: 2 additions & 2 deletions Pester.BuildAnalyzerRules/Pester.BuildAnalyzerRules.psm1
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,8 @@ function Measure-SafeCommands {
[string]$correction = "& `$SafeCommands['$commandName']"
[string]$file = $MyInvocation.MyCommand.Definition
[string]$description = 'Replacing with SafeCommands-type'
$correctionExtent = New-Object 'Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic.CorrectionExtent' $startLineNumber, $endLineNumber, $startColumnNumber, $endColumnNumber, $correction, $file, $description
$suggestedCorrections = New-Object System.Collections.ObjectModel.Collection['Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic.CorrectionExtent']
$correctionExtent = [Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic.CorrectionExtent]::new($startLineNumber, $endLineNumber, $startColumnNumber, $endColumnNumber, $correction, $file, $description)
$suggestedCorrections = [System.Collections.ObjectModel.Collection[Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic.CorrectionExtent]]::new()
$suggestedCorrections.add($correctionExtent) > $null

# Output error
Expand Down
4 changes: 2 additions & 2 deletions build.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -230,7 +230,7 @@ if ($Clean) {
$listControl = $builder.EndEntry().EndList()

$ViewDef = $formatViewCtor.Invoke(($section.FullName, $listControl, [guid]::NewGuid())) -as [System.Collections.Generic.List[System.Management.Automation.FormatViewDefinition]]
New-Object -TypeName 'System.Management.Automation.ExtendedTypeDefinition' $section.FullName, $ViewDef
[System.Management.Automation.ExtendedTypeDefinition]::new($section.FullName, $ViewDef)
}

# Create view for Option to ensure Table and hide IsModified
Expand All @@ -241,7 +241,7 @@ if ($Clean) {
$tableControl = $builder.EndRowDefinition().EndTable()

$ViewDef = $formatViewCtor.Invoke(('Pester.Option', $tableControl, [guid]::NewGuid())) -as [System.Collections.Generic.List[System.Management.Automation.FormatViewDefinition]]
$typeDefs += New-Object -TypeName 'System.Management.Automation.ExtendedTypeDefinition' 'Pester.Option', $ViewDef
$typeDefs += [System.Management.Automation.ExtendedTypeDefinition]::new('Pester.Option', $ViewDef)

# Export all formatdata
Export-FormatData -InputObject $typeDefs -Path "$PSScriptRoot/bin/PesterConfiguration.Format.ps1xml"
Expand Down
35 changes: 15 additions & 20 deletions src/Main.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ function Add-ShouldOperator {
}
}
return New-Object psobject -Property @{
return [PSCustomObject]@{
Succeeded = $succeeded
FailureMessage = $failureMessage
}
Expand Down Expand Up @@ -80,17 +80,12 @@ function Add-ShouldOperator {
[switch] $SupportsArrayInput
)

$entry = & $SafeCommands['New-Object'] psobject -Property @{
$entry = [PSCustomObject]@{
Test = $Test
SupportsArrayInput = [bool]$SupportsArrayInput
Name = $Name
Alias = $Alias
InternalName = If ($InternalName) {
$InternalName
}
Else {
$Name
}
InternalName = If ($InternalName) { $InternalName } else { $Name }
}
if (Test-AssertionOperatorIsDuplicate -Operator $entry) {
# This is an exact duplicate of an existing assertion operator.
Expand Down Expand Up @@ -197,32 +192,32 @@ function Add-AssertionDynamicParameterSet {
$commandInfo = & $SafeCommands['Get-Command'] __AssertionTest__ -CommandType Function
$metadata = [System.Management.Automation.CommandMetadata]$commandInfo

$attribute = & $SafeCommands['New-Object'] Management.Automation.ParameterAttribute
$attribute = [Management.Automation.ParameterAttribute]::new()
$attribute.ParameterSetName = $AssertionEntry.Name


$attributeCollection = & $SafeCommands['New-Object'] Collections.ObjectModel.Collection[Attribute]
$attributeCollection = [Collections.ObjectModel.Collection[Attribute]]::new()
$null = $attributeCollection.Add($attribute)
if (-not ([string]::IsNullOrWhiteSpace($AssertionEntry.Alias))) {
Assert-ValidAssertionAlias -Alias $AssertionEntry.Alias
$attribute = & $SafeCommands['New-Object'] System.Management.Automation.AliasAttribute($AssertionEntry.Alias)
$attribute = [System.Management.Automation.AliasAttribute]::new($AssertionEntry.Alias)
$attributeCollection.Add($attribute)
}

# Register assertion
$dynamic = & $SafeCommands['New-Object'] System.Management.Automation.RuntimeDefinedParameter($AssertionEntry.Name, [switch], $attributeCollection)
$dynamic = [System.Management.Automation.RuntimeDefinedParameter]::new($AssertionEntry.Name, [switch], $attributeCollection)
$null = $script:AssertionDynamicParams.Add($AssertionEntry.Name, $dynamic)

# Register -Not in the assertion's parameter set. Create parameter if not already present (first assertion).
if ($script:AssertionDynamicParams.ContainsKey('Not')) {
$dynamic = $script:AssertionDynamicParams['Not']
}
else {
$dynamic = & $SafeCommands['New-Object'] System.Management.Automation.RuntimeDefinedParameter('Not', [switch], (& $SafeCommands['New-Object'] System.Collections.ObjectModel.Collection[Attribute]))
$dynamic = [System.Management.Automation.RuntimeDefinedParameter]::new('Not', [switch], ([System.Collections.ObjectModel.Collection[Attribute]]::new()))
$null = $script:AssertionDynamicParams.Add('Not', $dynamic)
}

$attribute = & $SafeCommands['New-Object'] System.Management.Automation.ParameterAttribute
$attribute = [System.Management.Automation.ParameterAttribute]::new()
$attribute.ParameterSetName = $AssertionEntry.Name
$attribute.Mandatory = $false
$attribute.HelpMessage = 'Reverse the assertion'
Expand Down Expand Up @@ -264,11 +259,11 @@ function Add-AssertionDynamicParameterSet {
$type = [object]
}

$dynamic = & $SafeCommands['New-Object'] System.Management.Automation.RuntimeDefinedParameter($parameter.Name, $type, (& $SafeCommands['New-Object'] System.Collections.ObjectModel.Collection[Attribute]))
$dynamic = [System.Management.Automation.RuntimeDefinedParameter]::new($parameter.Name, $type, ([System.Collections.ObjectModel.Collection[Attribute]]::new()))
$null = $script:AssertionDynamicParams.Add($parameter.Name, $dynamic)
}

$attribute = & $SafeCommands['New-Object'] Management.Automation.ParameterAttribute
$attribute = [Management.Automation.ParameterAttribute]::new()
$attribute.ParameterSetName = $AssertionEntry.Name
$attribute.Mandatory = $false
$attribute.Position = ($i++)
Expand Down Expand Up @@ -1175,7 +1170,7 @@ function New-PesterOption {
$script:DisableScopeHints = $true
}

return & $script:SafeCommands['New-Object'] psobject -Property @{
return [PSCustomObject]@{
ReadMe = "New-PesterOption is deprecated and kept only for backwards compatibility when executing Pester v5 using the " +
"legacy parameter set. When the object is used with Invoke-Pester -PesterOption it will be ignored."
IncludeVSCodeMarker = [bool] $IncludeVSCodeMarker
Expand Down Expand Up @@ -1225,7 +1220,7 @@ function ResolveTestScripts {
& $script:SafeCommands['Write-Error'] "Script path '$unresolvedPath' is not a ps1 file."
}
else {
& $script:SafeCommands['New-Object'] psobject -Property @{
[PSCustomObject]@{
Path = $unresolvedPath
Script = $null
Arguments = $arguments
Expand All @@ -1243,7 +1238,7 @@ function ResolveTestScripts {
& $script:SafeCommands['Where-Object'] { -not $_.PSIsContainer } |
& $script:SafeCommands['Select-Object'] -ExpandProperty FullName -Unique |
& $script:SafeCommands['ForEach-Object'] {
& $script:SafeCommands['New-Object'] psobject -Property @{
[PSCustomObject]@{
Path = $_
Script = $null
Arguments = $arguments
Expand All @@ -1253,7 +1248,7 @@ function ResolveTestScripts {
}
}
elseif (-not [string]::IsNullOrEmpty($script)) {
& $script:SafeCommands['New-Object'] psobject -Property @{
[PSCustomObject]@{
Path = $null
Script = $script
Arguments = $arguments
Expand Down
2 changes: 1 addition & 1 deletion src/Pester.State.ps1
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
$script:AssertionOperators = [Collections.Generic.Dictionary[string, object]]([StringComparer]::InvariantCultureIgnoreCase)
$script:AssertionAliases = [Collections.Generic.Dictionary[string, object]]([StringComparer]::InvariantCultureIgnoreCase)
$script:AssertionDynamicParams = [Pester.Factory]::CreateRuntimeDefinedParameterDictionary()
$script:AssertionDynamicParams = [System.Management.Automation.RuntimeDefinedParameterDictionary]::new()
$script:DisableScopeHints = $true
4 changes: 0 additions & 4 deletions src/csharp/Pester/Factory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,6 @@ public static Dictionary<string, object> CreateDictionary()
return new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
}

public static RuntimeDefinedParameterDictionary CreateRuntimeDefinedParameterDictionary() {
return new System.Management.Automation.RuntimeDefinedParameterDictionary();
}

public static List<object> CreateCollection()
{
return new List<object>();
Expand Down
11 changes: 5 additions & 6 deletions src/functions/Get-ShouldOperator.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,9 @@
DynamicParam {
$ParameterName = 'Name'

$RuntimeParameterDictionary = & $SafeCommands['New-Object'] System.Management.Automation.RuntimeDefinedParameterDictionary
$AttributeCollection = & $SafeCommands['New-Object'] System.Collections.ObjectModel.Collection[System.Attribute]
$ParameterAttribute = & $SafeCommands['New-Object'] System.Management.Automation.ParameterAttribute
$RuntimeParameterDictionary = [System.Management.Automation.RuntimeDefinedParameterDictionary]::new()
$AttributeCollection = [System.Collections.ObjectModel.Collection[System.Attribute]]::new()
$ParameterAttribute = [System.Management.Automation.ParameterAttribute]::new()
$ParameterAttribute.Position = 0
$ParameterAttribute.HelpMessage = 'Name or alias of operator'

Expand All @@ -55,11 +55,10 @@
& $SafeCommands['Select-Object'] -Property Name, Alias |
& $SafeCommands['ForEach-Object'] { $_.Name; $_.Alias }

$ValidateSetAttribute = & $SafeCommands['New-Object']System.Management.Automation.ValidateSetAttribute($arrSet)

$ValidateSetAttribute = [System.Management.Automation.ValidateSetAttribute]::new([string[]]$arrSet)
$AttributeCollection.Add($ValidateSetAttribute)

$RuntimeParameter = & $SafeCommands['New-Object'] System.Management.Automation.RuntimeDefinedParameter($ParameterName, [string], $AttributeCollection)
$RuntimeParameter = [System.Management.Automation.RuntimeDefinedParameter]::new($ParameterName, [string], $AttributeCollection)
$RuntimeParameterDictionary.Add($ParameterName, $RuntimeParameter)
return $RuntimeParameterDictionary
}
Expand Down
4 changes: 2 additions & 2 deletions src/functions/Mock.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -1529,7 +1529,7 @@ function Get-DynamicParametersForCmdlet {
$Parameters = @{ }
}

$cmdlet = & $SafeCommands['New-Object'] $command.ImplementingType.FullName
$cmdlet = ($command.ImplementingType)::new()

$flags = [System.Reflection.BindingFlags]'Instance, Nonpublic'
$context = $ExecutionContext.GetType().GetField('_context', $flags).GetValue($ExecutionContext)
Expand Down Expand Up @@ -1880,7 +1880,7 @@ function Repair-EnumParameters {
return $ParamBlock
}

$sb = & $SafeCommands['New-Object'] System.Text.StringBuilder($ParamBlock)
$sb = [System.Text.StringBuilder]::new($ParamBlock)

foreach ($attr in $brokenValidateRange) {
$paramName = $attr.Parent.Name.VariablePath.UserPath
Expand Down
4 changes: 2 additions & 2 deletions src/functions/TestResults.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -287,7 +287,7 @@ function ConvertTo-NUnitReport {
$stringWriter = $null
$xmlWriter = $null
try {
$stringWriter = & $SafeCommands['New-Object'] IO.StringWriter
$stringWriter = [IO.StringWriter]::new()
$xmlWriter = [Xml.XmlWriter]::Create($stringWriter, $settings)

switch ($Format) {
Expand Down Expand Up @@ -374,7 +374,7 @@ function ConvertTo-JUnitReport {
$stringWriter = $null
$xmlWriter = $null
try {
$stringWriter = & $SafeCommands['New-Object'] IO.StringWriter
$stringWriter = [IO.StringWriter]::new()
$xmlWriter = [Xml.XmlWriter]::Create($stringWriter, $settings)

Write-JUnitReport -XmlWriter $xmlWriter -Result $Result
Expand Down
2 changes: 1 addition & 1 deletion src/functions/assertions/Should.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ function New-ShouldErrorRecord ([string] $Message, [string] $File, [string] $Lin
$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; Terminating = $Terminating }
$errorRecord = & $SafeCommands['New-Object'] Management.Automation.ErrorRecord $exception, $errorID, $errorCategory, $targetObject
$errorRecord = [Management.Automation.ErrorRecord]::new($exception, $errorID, $errorCategory, $targetObject)
return $errorRecord
}

Expand Down

0 comments on commit 1a3cad0

Please sign in to comment.