0

给定一个检查器脚本部署到我的服务器的路径/tmp/foo,其中包含以下内容......

#!/bin/bash
a=`cat /tmp/a`
b=`cat /tmp/b`
echo -n $( expr $a - $b )

...我有一个 InSpec 测试来评估 a 和 b 之间的差异是否在可接受的范围内。

describe command('/tmp/foo') do 
  its('stdout') { should be >= 0 }
  its('stdout') { should be < 120 }
end

遗憾的是,be 匹配器不会将输入强制转换为可与数学运算符一起使用的类型。

如何将此值强制为整数?


到目前为止我已经尝试过

  • ('stdout').to_i
undefined method `to_i' for #<Class:0x00007f8a86b91f00> (NoMethodError) Did you mean?  to_s
  • ('stdout').to_s('stdout').to_s.to_i
   Command: `/tmp/foo`
     ↺  
     ↺  

Test Summary: 0 successful, 0 failures, 2 skipped
  • (('stdout').to_i)
undefined method `0' for Command: `/tmp/foo`:#<Class:0x00007f9a52b912e0>

作为背景,/tmp/a并且/tmp/b是来自先前 InSpec 测试的一对 epoch 输出。

如果值在可接受的范围内,我可以检查客户端,但如果可能的话,我希望通过 InSpec 评估检查和报告这种差异,而不用正则表达式巫术代替人类可读的数学表达式。

4

3 回答 3

0

@cwolfe归功于厨师社区 slack #InSpec频道

be具有匹配和方法链接的精确类型

另一种方法是尝试在stdout文字中进行方法链接,如下所示:

describe command("bash /tmp/foo") do 
  its('stdout.strip.to_i') { should be >= 5 }
end

InSpec 使用rspec-its 库,它将点解释为方法调用。

于 2019-09-10T17:21:50.397 回答
0

Credit to @aaronlippold the chef community slack #InSpec channel

Exact typing with be match & explicit subject syntax

The stdout of the InSpec command can be cached outside of the describe block and modified arbitrarily. Here we ask InSpec to run the script, grab its stdout and strip the line (\n), then look at the result and ensure it is between the expected values using the be matcher syntax for strict type comparison.

x = inspec.command("bash /tmp/foo").stdout.strip.to_i

describe x do 
  its { should be >= 5 }
  its { should be < 10 }
end

Alternately, you can use the rspec explicit subject syntax to pull the return value out to make it more clear in the code.

describe "The value of my EPOC is between the required values" do
  subject { command("bash /tmp/foo").stdout.strip.to_i }
  it { should be >= 5 }
  it { should be < 10 }
end

This also allows you to better report to the “what” vs the “how” as well.

Another syntax option for this approach uses puts()

cmd = command("bash /tmp/foo")
puts(cmd.inspect)
describe cmd do 
  its('stdout') { expect(cmd.strip.to_i).to be >= 5 }
end
于 2019-09-10T20:23:07.820 回答
0

@bodumin归功于厨师社区 slack #InSpec频道

cmp带有匹配的模糊输入

最简单的解决方案是使用cmp匹配器而不是be匹配器。cmp虽然 [the official docs for ]上的示例没有给出明确的数学运算符,但cmp匹配中的数学运算将正确评估

describe command('/tmp/foo') do 
  its('stdout') { should cmp >= 0 }
  its('stdout') { should cmp < 120 }
end

@aaronlippold

cmp是我们在后端进行的逻辑比较……也就是 1 为真 TRUE 为真。因此,以 SSHD 配置为例……您可以使用 1 或 true 或 TRUE 或 True 等设置道具。它是一个更宽容的匹配器,我们已经构建了一个说服函数等。

于 2019-09-10T17:06:27.683 回答