linux - Chefspec 在 Linux 上删除 Win32::Service

标签 linux winapi chef-infra chefspec

我们的 Recipe 可在 Linux 和 Windows 机器上使用,当它运行/收敛时,代码在两种类型的系统上都能完美运行。但是 rake 单元 测试在 Linux 上失败。在我的 Recipe 中我有:

service 'MyService' do
  action %i[enable start]
  only_if { ::Win32::Service.exists?("MyService") }
  not_if { ::File.exist?("#{install_dir}\\scripts\\instance-stopped") }
end

我们得到的错误是:

Failures:

  1. perfagent::install_windows When set to install agent on Windows converges successfully Failure/Error: expect { chef_run }.to_not raise_error

    expected no Exception, got #<NameError: uninitialized constant Win32> with backtrace: # /tmp/chefspec20200924-2530-350e0zfile_cache_path/cookbooks/perfagent/resources/install_agent.rb:83:in `block (3 levels) in class_from_file'

是否有可能,仅对于 Linux 系统,在我的规范文件中为上面的“only_if”虚拟出值,以便每当我们在 Linux 上运行 rake 时我的 rake 单元测试都会成功?


更新:

由于该说明书在 Linux 和 Windows 系统上执行,因此我们在执行说明书时进行了早期检查,例如:

if node['platform_family'] == 'windows'
  include_recipe 'cookbook::install_windows'
elsif node['platform_family'] == 'rhel'
  include_recipe 'cookbook::install_linux'
else
  log "This OS family (#{node['platform_family']})  is not supported" do
    level :info
  end
end

这意味着 Recipe 仅根据 platform_family 调用相关 Recipe 。但是,当我们在 Linux 上运行 rake 单元时,会出现上述错误,而在 Windows 上 rake 会成功。

我尝试添加:

allow(::Win32::Service).to receive(:exists?).with(windows_service[:name]).and_return(true)

到规范文件,但这在 Linux 上仍然失败,并导致 Windows rake 单元也失败。

最佳答案

对于嵌套类, stub 会稍微复杂一些。您还需要对类本身进行 stub 。使用stub_const from the RSpec for that :

let :subject do
  fake_win32 = Class.new
  stub_const('Win32::Service', fake_win32)
  allow(fake_win32).to receive(:exists?).and_return false
  ChefSpec::Runner.new(platform: 'windows', version: '2008R2').converge described_recipe
end

关于linux - Chefspec 在 Linux 上删除 Win32::Service,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64048907/

相关文章:

linux - ld 找不到已安装的库

winapi - 为商业应用程序 Hook Win32 API 的推荐方法是什么?

api - 检测计算机是否为域 Controller

chef-infra - 你如何使 Chef 资源成为可选的?

linux - rrdtool图: one graph line plotted incorectly

linux - cat pipe awk 操作与文件上 awk 命令的比较

c - g_strdup_printf 中不需要的换行符或空符号

chef-infra - 无法访问子配方属性文件中默认 Chef 配方的属性

c++ - 如何知道应用程序中可用的虚拟内存