Skip to content

Commit d6608d4

Browse files
committed
test: 为硬件和Windows模块测试添加模拟和清理逻辑
在硬件模块测试中,为 CI 环境中可能不存在的 `nvidia-smi` 和 `free` 命令创建全局占位函数,确保 Pester 的 Mock 可以正常工作,并在测试结束后清理这些函数。 在 Windows 模块测试中,模拟 `WScript.Shell` COM 对象及其 `CreateShortcut` 方法,以避免在 TestDrive 路径上创建实际快捷文件时可能出现的兼容性问题。
1 parent 48f793e commit d6608d4

2 files changed

Lines changed: 28 additions & 0 deletions

File tree

psutils/tests/hardware.Tests.ps1

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,22 @@
11
BeforeAll {
2+
# 为 CI 环境中不存在的外部命令创建占位函数,使 Pester Mock 能正常工作
3+
# Pester 的 Mock 要求目标命令在当前会话中可解析
4+
if (-not (Get-Command nvidia-smi -ErrorAction SilentlyContinue)) {
5+
function global:nvidia-smi { }
6+
}
7+
if (-not (Get-Command free -ErrorAction SilentlyContinue)) {
8+
function global:free { }
9+
}
210
Import-Module "$PSScriptRoot\..\modules\hardware.psm1" -Force
311
Import-Module "$PSScriptRoot\..\modules\os.psm1" -Force
412
}
513

14+
AfterAll {
15+
# 清理占位函数
16+
Remove-Item Function:\nvidia-smi -ErrorAction SilentlyContinue
17+
Remove-Item Function:\free -ErrorAction SilentlyContinue
18+
}
19+
620
Describe "Get-GpuInfo 函数测试" {
721
Context "Linux 环境下 nvidia-smi CSV 输出" {
822
It "应该解析 nvidia-smi CSV 输出并返回正确的 GPU 信息" {

psutils/tests/win.Tests.ps1

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,20 @@ Describe "New-Shortcut 函数测试" -Tag 'windowsOnly' {
3232
Set-ItResult -Skipped -Because "仅 Windows 环境"
3333
return
3434
}
35+
36+
# Mock COM 对象以避免 TestDrive 路径上 WScript.Shell 的兼容性问题
37+
$mockShortcut = [PSCustomObject]@{
38+
TargetPath = ''
39+
Arguments = ''
40+
WorkingDirectory = ''
41+
IconLocation = ''
42+
}
43+
$mockShortcut | Add-Member -MemberType ScriptMethod -Name Save -Value { }
44+
$mockWshShell = [PSCustomObject]@{}
45+
$mockWshShell | Add-Member -MemberType ScriptMethod -Name CreateShortcut -Value { param($path) $mockShortcut }
46+
47+
Mock -ModuleName win New-Object { $mockWshShell } -ParameterFilter { $ComObject -eq 'WScript.Shell' }
48+
3549
$testTarget = "$TestDrive\target.txt"
3650
"" | Out-File -FilePath $testTarget -Encoding utf8
3751
$testShortcut = "$TestDrive\shortcut.lnk"

0 commit comments

Comments
 (0)