diff --git a/lib/cane/threshold_check.rb b/lib/cane/threshold_check.rb index de95e12..110b7e9 100644 --- a/lib/cane/threshold_check.rb +++ b/lib/cane/threshold_check.rb @@ -1,51 +1,55 @@ require 'cane/file' -# Configurable check that allows the contents of a file to be compared against -# a given value. -class ThresholdCheck < Struct.new(:opts) - - def self.key; :threshold; end - def self.options - { - gte: ["If FILE contains a number, verify it is >= to THRESHOLD", - variable: "FILE,THRESHOLD", - type: Array] - } - end +module Cane + + # Configurable check that allows the contents of a file to be compared against + # a given value. + class ThresholdCheck < Struct.new(:opts) + + def self.key; :threshold; end + def self.options + { + gte: ["If FILE contains a number, verify it is >= to THRESHOLD", + variable: "FILE,THRESHOLD", + type: Array] + } + end + + def violations + thresholds.map do |operator, file, limit| + value = value_from_file(file) + + unless value.send(operator, limit.to_f) + { + description: 'Quality threshold crossed', + label: "%s is %s, should be %s %s" % [ + file, operator, value, limit + ] + } + end + end.compact + end - def violations - thresholds.map do |operator, file, limit| - value = value_from_file(file) - - unless value.send(operator, limit.to_f) - { - description: 'Quality threshold crossed', - label: "%s is %s, should be %s %s" % [ - file, operator, value, limit - ] - } + def value_from_file(file) + begin + contents = Cane::File.contents(file).chomp.to_f + rescue Errno::ENOENT + UnavailableValue.new end - end.compact - end + end - def value_from_file(file) - begin - contents = Cane::File.contents(file).chomp.to_f - rescue Errno::ENOENT - UnavailableValue.new + def thresholds + (opts[:gte] || []).map do |x| + x.unshift(:>=) + end end - end - def thresholds - (opts[:gte] || []).map do |x| - x.unshift(:>=) + # Null object for all cases when the value to be compared against cannot be + # read. + class UnavailableValue + def >=(_); false end + def to_s; 'unavailable' end end end - # Null object for all cases when the value to be compared against cannot be - # read. - class UnavailableValue - def >=(_); false end - def to_s; 'unavailable' end - end end diff --git a/spec/threshold_check_spec.rb b/spec/threshold_check_spec.rb index a6c654e..0e30f3a 100644 --- a/spec/threshold_check_spec.rb +++ b/spec/threshold_check_spec.rb @@ -2,9 +2,9 @@ require 'cane/threshold_check' -describe ThresholdCheck do +describe Cane::ThresholdCheck do it 'returns a value of unavailable when file cannot be read' do - check = ThresholdCheck.new(gte: [['bogus_file', 20]]) + check = Cane::ThresholdCheck.new(gte: [['bogus_file', 20]]) violations = check.violations violations.length.should == 1 violations[0].to_s.should include("unavailable")