Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Pester Test to Check for Duplicate Function Definitions #1404

Merged
merged 4 commits into from
Oct 20, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 58 additions & 1 deletion tests/unit/_.Tests.ps1
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingWriteHost', '')]
param()

BeforeDiscovery {
Expand Down Expand Up @@ -176,4 +177,60 @@ Describe 'Examples Script Headers' {
}
}

}
}


Describe 'Check for Duplicate Function Definitions' {
BeforeAll { $path = $PSCommandPath
$src = (Split-Path -Parent -Path $path) -ireplace '[\\/]tests[\\/]unit', '/src/'
# Retrieve all function definitions from the module files
$functionNames = @{}
$duplicatedFunctionNames = @{}
$moduleFiles = Get-ChildItem -Path $src -Recurse -Include '*.ps1', '*.psm1'

foreach ($file in $moduleFiles) {
$content = Get-Content -Path $file.FullName
$lineNumber = 0
foreach ($line in $content) {
# Increment line number for accurate tracking
$lineNumber++
# Match function definitions (e.g., "function MyFunction {")
if ($line -match 'function\s+([^\s{]+)\s*{') {
$functionName = $Matches[1]

# Check if function name already exists
if (! $functionNames.ContainsKey($functionName)) {
$functionNames[$functionName] = @{
FunctionName = $functionName
FilePath = @( )
LineNumber = @( )
}
}
else {
# Add to duplicated function names if not already tracked
$duplicatedFunctionNames[$functionName] = $functionNames[$functionName]
}
# Update the function details
$functionNames[$functionName].LineNumber += $lineNumber
$functionNames[$functionName].FilePath += $file.FullName
}
}
}

# Additional information in case of failure
if ($duplicatedFunctionNames.Count -gt 0) {
Write-host 'The following functions have multiple definitions:'
foreach ($key in $duplicatedFunctionNames.Keys) {
Write-host "Function: $($key)"
for ($i = 0; $i -lt $duplicatedFunctionNames[$key].LineNumber.Count ; $i++) {
Write-host " - File: $($duplicatedFunctionNames[$key].FilePath[$i]), Line: $($duplicatedFunctionNames[$key].LineNumber[$i])"
}
}
}
}

It 'should not have duplicate function definitions' {
# Assert no duplicate function definitions
$duplicatedFunctionNames.Count | Should -Be 0
}
}