temporalio / samples-java

Temporal Java SDK samples
http://docs.temporal.io/docs/java-quick-start
Other
170 stars 143 forks source link

Sample for a test verifying published metrics in unit tests #289

Open Spikhalskiy opened 2 years ago

Spikhalskiy commented 2 years ago

Temporal should provide a sample for users on how they may check the metrics in unit tests. I propose to wire MetricsScope with our standard MicrometerClientStatsReporter initialized with SimpleMeterRegistry micrometer. A little bit like micrometer does in one of their tests: https://www.programcreek.com/java-api-examples/?code=micrometer-metrics%2Fmicrometer%2Fmicrometer-master%2Fmicrometer-test%2Fsrc%2Fmain%2Fjava%2Fio%2Fmicrometer%2Fcore%2Ftck%2FTimerTest.java

        MeterRegistry registry = new SimpleMeterRegistry();

        try (Timer.ResourceSample sample = Timer.resource(registry, "requests")
                .description("This is an operation")
                .publishPercentileHistogram()) {
            try {
                if (outcome.equals("error")) {
                    throw new IllegalArgumentException("boom");
                }
                sample.tag("outcome", "success");
            } catch (Throwable t) {
                sample.tag("outcome", "error");
            }
        }

        assertThat(registry.get("requests").tag("outcome", outcome).timer().count())
                .isEqualTo(1);
Spikhalskiy commented 2 years ago

Since then I used this approach in SDK tests for metrics and it worked out quite fine. This is an example of using this approach in Temporal code: https://github.com/temporalio/sdk-java/blob/37a0e463fae2312882b5c946f423a0dbf85f9666/temporal-sdk/src/test/java/io/temporal/client/functional/MetricsTest.java#L76

antmendoza commented 2 years ago

Thank you @Spikhalskiy , I have started to work on this