|
| 1 | +package com.baeldung.metrics.servo; |
| 2 | + |
| 3 | +import com.netflix.servo.DefaultMonitorRegistry; |
| 4 | +import com.netflix.servo.Metric; |
| 5 | +import com.netflix.servo.monitor.BasicGauge; |
| 6 | +import com.netflix.servo.monitor.DynamicCounter; |
| 7 | +import com.netflix.servo.monitor.Gauge; |
| 8 | +import com.netflix.servo.monitor.MonitorConfig; |
| 9 | +import org.junit.Test; |
| 10 | + |
| 11 | +import java.util.Iterator; |
| 12 | +import java.util.List; |
| 13 | + |
| 14 | +import static com.netflix.servo.annotations.DataSourceType.GAUGE; |
| 15 | +import static java.util.concurrent.TimeUnit.SECONDS; |
| 16 | +import static org.hamcrest.Matchers.*; |
| 17 | +import static org.junit.Assert.assertEquals; |
| 18 | +import static org.junit.Assert.assertThat; |
| 19 | + |
| 20 | +/** |
| 21 | + * @author aiet |
| 22 | + */ |
| 23 | +public class MetricObserverTest extends MetricTestBase { |
| 24 | + |
| 25 | + @Test |
| 26 | + public void givenMetrics_whenRegister_thenMonitored() throws InterruptedException { |
| 27 | + Gauge<Double> gauge = new BasicGauge<>(MonitorConfig |
| 28 | + .builder("test") |
| 29 | + .build(), () -> 2.32); |
| 30 | + assertEquals(2.32, gauge.getValue(), 0.01); |
| 31 | + |
| 32 | + DefaultMonitorRegistry |
| 33 | + .getInstance() |
| 34 | + .register(gauge); |
| 35 | + |
| 36 | + for (int i = 0; i < 2; i++) { |
| 37 | + SECONDS.sleep(1); |
| 38 | + } |
| 39 | + |
| 40 | + List<List<Metric>> metrics = observer.getObservations(); |
| 41 | + assertThat(metrics, hasSize(greaterThanOrEqualTo(2))); |
| 42 | + |
| 43 | + Iterator<List<Metric>> metricIterator = metrics.iterator(); |
| 44 | + //skip first empty observation |
| 45 | + metricIterator.next(); |
| 46 | + while (metricIterator.hasNext()) { |
| 47 | + assertThat(metricIterator.next(), hasItem(allOf(hasProperty("config", hasProperty("tags", hasItem(GAUGE))), hasProperty("value", is(2.32))))); |
| 48 | + } |
| 49 | + |
| 50 | + } |
| 51 | + |
| 52 | + @Test |
| 53 | + public void givenMetrics_whenRegisterDynamically_thenMonitored() throws Exception { |
| 54 | + for (int i = 0; i < 2; i++) { |
| 55 | + DynamicCounter.increment("monitor-name", "tag-key", "tag-value"); |
| 56 | + SECONDS.sleep(1); |
| 57 | + } |
| 58 | + |
| 59 | + List<List<Metric>> metrics = observer.getObservations(); |
| 60 | + assertThat(metrics, hasSize(greaterThanOrEqualTo(2))); |
| 61 | + |
| 62 | + Iterator<List<Metric>> metricIterator = metrics.iterator(); |
| 63 | + //skip first empty observation |
| 64 | + metricIterator.next(); |
| 65 | + while (metricIterator.hasNext()) { |
| 66 | + assertThat(metricIterator.next(), hasItem(hasProperty("value", greaterThanOrEqualTo(1.0)))); |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | +} |
0 commit comments