66require 'prometheus_exporter/instrumentation'
77
88class PrometheusActiveRecordCollectorTest < Minitest ::Test
9+ include CollectorHelper
10+
911 def collector
1012 @collector ||= PrometheusExporter ::Server ::ActiveRecordCollector . new
1113 end
@@ -27,7 +29,6 @@ def test_collecting_metrics
2729 end
2830
2931 def test_collecting_metrics_with_custom_labels
30-
3132 collector . collect (
3233 "type" => "active_record" ,
3334 "pid" => "1000" ,
@@ -49,7 +50,6 @@ def test_collecting_metrics_with_custom_labels
4950 end
5051
5152 def test_collecting_metrics_with_client_default_labels
52-
5353 collector . collect (
5454 "type" => "active_record" ,
5555 "pid" => "1000" ,
@@ -108,4 +108,56 @@ def test_collecting_metrics_for_multiple_pools
108108 assert ( metrics . first . metric_text . include? ( 'active_record_connection_pool_connections{pool_name="primary",pid="1000",hostname="localhost"} 50' ) )
109109 assert ( metrics . first . metric_text . include? ( 'active_record_connection_pool_connections{pool_name="other",pid="1000",hostname="localhost"} 5' ) )
110110 end
111+
112+ def test_metrics_deduplication
113+ data = {
114+ "pid" => "1000" ,
115+ "hostname" => "localhost" ,
116+ "metric_labels" => { "pool_name" => "primary" } ,
117+ "connections" => 100
118+ }
119+
120+ collector . collect ( data )
121+ collector . collect ( data . merge ( "connections" => 200 ) )
122+ collector . collect ( data . merge ( "pid" => "2000" , "connections" => 300 ) )
123+ collector . collect ( data . merge ( "pid" => "3000" , "connections" => 400 ) )
124+ collector . collect ( data . merge ( "hostname" => "localhost2" , "pid" => "2000" , "connections" => 500 ) )
125+
126+ metrics = collector . metrics
127+ metrics_lines = metrics . map ( &:metric_text ) . join . split ( "\n " )
128+
129+ assert_equal 1 , metrics . size
130+ assert_equal [
131+ 'active_record_connection_pool_connections{pool_name="primary",pid="1000",hostname="localhost"} 200' ,
132+ 'active_record_connection_pool_connections{pool_name="primary",pid="2000",hostname="localhost"} 300' ,
133+ 'active_record_connection_pool_connections{pool_name="primary",pid="3000",hostname="localhost"} 400' ,
134+ 'active_record_connection_pool_connections{pool_name="primary",pid="2000",hostname="localhost2"} 500'
135+ ] , metrics_lines
136+ end
137+
138+ def test_metrics_expiration
139+ data = {
140+ "pid" => "1000" ,
141+ "hostname" => "localhost" ,
142+ "connections" => 50 ,
143+ "busy" => 20 ,
144+ "dead" => 10 ,
145+ "idle" => 20 ,
146+ "waiting" => 0 ,
147+ "size" => 120 ,
148+ "metric_labels" => {
149+ "pool_name" => "primary"
150+ }
151+ }
152+
153+ stub_monotonic_clock ( 0 ) do
154+ collector . collect ( data )
155+ collector . collect ( data . merge ( "pid" => "1001" , "hostname" => "localhost2" ) )
156+ assert_equal 6 , collector . metrics . size
157+ end
158+
159+ stub_monotonic_clock ( max_metric_age + 1 ) do
160+ assert_equal 0 , collector . metrics . size
161+ end
162+ end
111163end
0 commit comments