如何使用Pester测试验证目录树是否符合含子文件夹或rbac.jsonc文件的规则
Pester 目录校验脚本实现方案
可行性说明
你描述的校验逻辑完全可以通过Pester配合PowerShell的文件系统操作实现,无需依赖额外工具。
核心实现逻辑
- 遍历根目录时全程跳过所有名为
.policy的文件夹,不做任何校验 - 遇到包含
rbac.jsonc的文件夹时直接剪枝,不再遍历其下的所有子目录 - 对每个校验范围内的文件夹,判断是否满足两个条件之一:存在
rbac.jsonc,或子路径下最终能找到rbac.jsonc - 收集所有不符合规则的目录,最后统一触发测试失败
完整测试脚本
param( [Parameter(Mandatory = $true)] [string]$topMgFolderPath ) BeforeAll { function Get-InvalidDirectories { param( [string]$CurrentPath ) # 规则3:跳过所有.policy文件夹 if ((Split-Path $CurrentPath -Leaf) -eq '.policy') { return @() } # 规则2①:存在rbac.jsonc则跳过所有子目录校验 if (Test-Path (Join-Path $CurrentPath 'rbac.jsonc') -PathType Leaf) { return @() } $childDirs = Get-ChildItem -Path $CurrentPath -Directory -ErrorAction SilentlyContinue | Where-Object { $_.Name -ne '.policy' } $invalidPaths = @() # 没有子文件夹,不满足规则②,标记为无效 if (-not $childDirs) { $invalidPaths += $CurrentPath return $invalidPaths } # 递归校验子文件夹 $childInvalid = $childDirs | ForEach-Object { Get-InvalidDirectories $_.FullName } $invalidPaths += $childInvalid # 校验当前文件夹:子路径下是否存在有效rbac.jsonc $hasValidChild = $childDirs | ForEach-Object { $tempPath = $_.FullName while ($tempPath -and (Split-Path $tempPath -Parent) -ne (Split-Path $topMgFolderPath -Parent)) { if (Test-Path (Join-Path $tempPath 'rbac.jsonc') -PathType Leaf) { return $true } $tempPath = Split-Path $tempPath -Parent } return $false } if (-not $hasValidChild) { $invalidPaths += $CurrentPath } return $invalidPaths | Select-Object -Unique } $invalidDirs = Get-InvalidDirectories $topMgFolderPath } Describe "目录RBAC配置校验" { It "所有非.policy目录都需符合RBAC配置规则" { $invalidDirs.Count | Should -Be 0 -Because "以下目录不符合规则:`n$($invalidDirs -join "`n")" } }
使用方法
- 将上述代码保存为名为
DirectoryRbacCheck.Tests.ps1的文件 - 打开PowerShell终端,执行如下命令触发校验:
Invoke-Pester -Path ./DirectoryRbacCheck.Tests.ps1 -Output Detailed -Parameter @{topMgFolderPath = "替换为你的根目录实际路径"}
- 测试执行后如果存在不符合规则的目录,会直接标记测试失败,并输出所有不符合规则的目录列表
内容的提问来源于stack exchange,提问作者Nadia Hansen
相关产品推荐
相关产品推荐

