我正在玩powershell
,并在本地和TravisCI上运行测试。
RequiredModules = @('ClipboardText')
当前,我在运行测试之前先安装powershell
和pester
addons:
apt:
sources:
- sourceline: deb [arch=amd64] https://packages.microsoft.com/ubuntu/14.04/prod trusty main
key_url: https://packages.microsoft.com/keys/microsoft.asc
packages:
- powershell
- xclip
before_script:
- pwsh -Command 'Install-Module -Name Pester -Force -Scope CurrentUser'
script:
- make test
test:
pwsh -Command 'Get-childItem -Recurse *.test.ps1 | foreach { Invoke-Pester -EnableExit $$_ }'
Build引发错误:
Import-Module : The required module 'ClipboardText' is not loaded.
Load the module or remove the module from 'RequiredModules' in the file '/home/travis/build/edouard-lopez/lesspass-powershell/lesspass.psd1'.
At /home/travis/build/edouard-lopez/lesspass-powershell/Clipboard.test.ps1:1 char:1
+ Import-Module $PSScriptRoot/lesspass.psd1 -Force # force code to be ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ResourceUnavailable: (/home/travis/bu...l/lesspass.psd1:String) [Import-Module], MissingMemberException
+ FullyQualifiedErrorId : Modules_InvalidManifest,Microsoft.PowerShell.Commands.ImportModuleCommand
我认为声明RequiredModules
将安装ClipboardText
,从而可以正确执行我的测试。
如果我在本地手动安装模块ClipboardText
,我的测试工作正常,但是对CI和模块的将来分发是否正确?
答案 0 :(得分:2)
对于其他答案,模块清单的RequiredModules
字段定义了在导入此模块之前必须导入全局环境中的所有模块。
因此,这些模块必须已经安装在系统上,但无需加载(导入)到当前会话中。
因此,为了确保您的测试在CI系统上正常工作,您需要确保测试脚本执行了所需模块的安装(例如,如果PSGallery或其他工具中提供了这些模块,则通过Install-Module
) nuget repo)。
如果可以在没有依赖模块的情况下测试脚本,则可以编写Pester脚本来解决该问题,方法是通过模拟所需功能而无需提供模块。这可以通过为缺少的cmdlet定义空函数,然后(可选)为它们声明模拟来完成,以便您可以验证它们是否已按预期被调用:
. YourModule.psm1
Function Some-Function { }
Mock Some-Function { }
Describe 'Testing Invoke-SomeCmdlet invokes Some-Function as part of its code' {
$Result = Invoke-SomeCmdlet
It 'Should invoke Some-Function' {
Assert-MockCalled Some-Function
}
}
如果不将cmdlet声明为空的Function
,则Mock
将会失败,因为您只能模拟存在的cmdlet /函数。
请注意,为了以此方式测试代码,您需要在不调用模块清单的情况下加载代码(例如,直接将.ps1或.psm1文件的点源与通过.psd1加载模块相比,否则RequiredModules
语句将导致测试脚本失败)。
显然,只提供所需的模块会更简单,但有时并非总是可能的,上面只是演示如何解决这种情况。
答案 1 :(得分:2)
如Mark Wragg和Dejulia489答案所述,您需要在导入之前安装模块。
将ClipboardText
添加到要安装的模块列表中:
before_script:
- pwsh -Command 'Install-Module -Name Pester,ClipboardText -Force -Scope CurrentUser'
答案 2 :(得分:1)
Powershell必需的模块必须在导入根模块之前加载到全局环境中。 -Powershell Module Manifest documentation
在导入此模块之前必须将其导入全局环境中的模块 RequiredModules = @()
确认在$ Env:PSModulePath中列出的路径之一中安装了“ ClipboardText”。您可以通过在Travis Build服务器上打开Powershell会话并运行
来完成此操作Import-Module 'ClipboardText'
如果失败,则需要正确安装剪贴板测试模块。