diff --git a/lib/prometheus/client/gauge.rb b/lib/prometheus/client/gauge.rb index e0f76521..fbcfdd4a 100644 --- a/lib/prometheus/client/gauge.rb +++ b/lib/prometheus/client/gauge.rb @@ -20,6 +20,10 @@ def set(value, labels: {}) @store.set(labels: label_set_for(labels), val: value) end + def set_to_current_time(labels: {}) + @store.set(labels: label_set_for(labels), val: Time.now.to_f) + end + # Increments Gauge value by 1 or adds the given value to the Gauge. # (The value can be negative, resulting in a decrease of the Gauge.) def increment(by: 1, labels: {}) diff --git a/prometheus-client.gemspec b/prometheus-client.gemspec index 6083a16e..029ff4f1 100644 --- a/prometheus-client.gemspec +++ b/prometheus-client.gemspec @@ -17,4 +17,5 @@ Gem::Specification.new do |s| s.add_development_dependency 'benchmark-ips' s.add_development_dependency 'concurrent-ruby' + s.add_development_dependency 'timecop' end diff --git a/spec/prometheus/client/gauge_spec.rb b/spec/prometheus/client/gauge_spec.rb index 376becd5..417daad2 100644 --- a/spec/prometheus/client/gauge_spec.rb +++ b/spec/prometheus/client/gauge_spec.rb @@ -48,6 +48,30 @@ end end + describe '#set_to_current_time' do + it 'it sets the gauge to the current Unix epoch time' do + Timecop.freeze(Time.at(12345.1)) do + expect do + gauge.set_to_current_time + end.to change { gauge.get }.from(0).to(12345.1) + end + end + + context "with a an expected label set" do + let(:expected_labels) { [:test] } + + it 'sets a metric value for a given label set' do + Timecop.freeze(Time.at(12345.1)) do + expect do + expect do + gauge.set_to_current_time(labels: { test: 'value' }) + end.to change { gauge.get(labels: { test: 'value' }) }.from(0).to(12345.1) + end.to_not change { gauge.get(labels: { test: 'other' }) } + end + end + end + end + describe '#increment' do before do gauge.set(0, labels: RSpec.current_example.metadata[:labels] || {}) diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 31000d69..b6f707b1 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,6 +1,7 @@ # encoding: UTF-8 require 'simplecov' +require 'timecop' RSpec.configure do |c| c.warnings = true @@ -9,3 +10,5 @@ SimpleCov.formatter = SimpleCov::Formatter::HTMLFormatter SimpleCov.start + +Timecop.safe_mode = true