Skip to content

Commit

Permalink
Add clear() method to StatefulMetric (#917)
Browse files Browse the repository at this point in the history
Signed-off-by: Fabian Stäber <[email protected]>
  • Loading branch information
fstab committed Mar 22, 2024
1 parent 48d1394 commit 66c9725
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -109,8 +109,12 @@ public void remove(String... labelValues) {
data.remove(Arrays.asList(labelValues));
}

// TODO: Write a clear() method that resets the metric (removes all data points),
// see https://prometheus.io/docs/instrumenting/writing_clientlibs/#labels
/**
* Reset the metric (remove all data points).
*/
public void clear() {
data.clear();
}

protected abstract T newDataPoint();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,32 @@ public void testLabelRemoveWhileCollecting() throws Exception {
Assert.assertNotNull(entry.getValue());
}
}

@Test
public void testClear() {
Counter counter = Counter.builder().name("test").labelNames("label1", "label2").build();
counter.labelValues("a", "b").inc(3.0);
counter.labelValues("c", "d").inc(3.0);
counter.labelValues("a", "b").inc();
Assert.assertEquals(2, counter.collect().getDataPoints().size());

counter.clear();
Assert.assertEquals(0, counter.collect().getDataPoints().size());

counter.labelValues("a", "b").inc();
Assert.assertEquals(1, counter.collect().getDataPoints().size());
}

@Test
public void testClearNoLabels() {
Counter counter = Counter.builder().name("test").build();
counter.inc();
Assert.assertEquals(1, counter.collect().getDataPoints().size());
Assert.assertEquals(1.0, counter.collect().getDataPoints().get(0).getValue(), 0.0);

counter.clear();
// No labels is always present, but as no value has been observed after clear() the value should be 0.0
Assert.assertEquals(1, counter.collect().getDataPoints().size());
Assert.assertEquals(0.0, counter.collect().getDataPoints().get(0).getValue(), 0.0);
}
}

0 comments on commit 66c9725

Please sign in to comment.