diff --git a/lib/Test2/Tools/OpenTelemetry.pm b/lib/Test2/Tools/OpenTelemetry.pm index 24a0a02..a49e2c9 100644 --- a/lib/Test2/Tools/OpenTelemetry.pm +++ b/lib/Test2/Tools/OpenTelemetry.pm @@ -4,11 +4,20 @@ package our $VERSION = '0.001'; use Exporter 'import'; -our @EXPORT = qw( messages no_messages ); +our @EXPORT = qw( + messages + no_messages + metrics + no_metrics +); +use Feature::Compat::Defer; use Test2::API 'context'; use Test2::Compare qw( compare strict_convert ); +# TODO: Cannot lexically set a metrics adapter +use Metrics::Any::Adapter 'Test'; + require Log::Any::Adapter; my $capture_messages = sub { @@ -44,4 +53,35 @@ sub no_messages (&) { return !$delta; } +my $capture_metrics = sub { + my $code = shift; + + Metrics::Any::Adapter::Test->clear; + defer { Metrics::Any::Adapter::Test->clear } + + $code->(); + + [ split /\n/, Metrics::Any::Adapter::Test->metrics ]; +}; + +sub metrics (&) { goto $capture_metrics } + +sub no_metrics (&) { + my $name = 'No metrics collected'; + + my $data = shift->$capture_metrics; + my $context = context; + my $delta = compare $data, [], \&strict_convert; + + if ( $delta ) { + $context->fail( $name, $delta->diag ); + } + else { + $context->ok( 1, $name ); + } + + $context->release; + return !$delta; +} + 1;