Skip to content
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,12 @@
from opentelemetry import metrics as metrics_api
from opentelemetry import trace as trace_api
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.metrics.export import InMemoryMetricReader, MetricReader
from opentelemetry.sdk.metrics.export import (
HistogramDataPoint,
InMemoryMetricReader,
MetricReader,
NumberDataPoint,
)
from opentelemetry.sdk.trace import TracerProvider, export
from opentelemetry.sdk.trace.export.in_memory_span_exporter import (
InMemorySpanExporter,
Expand Down Expand Up @@ -85,6 +90,79 @@ def sorted_spans(self, spans): # pylint: disable=R0201
reverse=True,
)

def sorted_metrics(self, metrics): # pylint: disable=R0201
"""
Sorts metrics by metric name.
"""
return sorted(
metrics,
key=lambda m: m.name,
)

def get_sorted_metrics(self):
resource_metrics = (
self.memory_metrics_reader.get_metrics_data().resource_metrics
)

all_metrics = []
for metrics in resource_metrics:
for scope_metrics in metrics.scope_metrics:
all_metrics.extend(scope_metrics.metrics)

return self.sorted_metrics(all_metrics)

def assert_histogram_expected(self, data_point, expected_value):
self.assertEqual(
data_point.count,
1,
)
self.assertEqual(
data_point.sum,
expected_value,
)
self.assertEqual(
data_point.max,
expected_value,
)
self.assertEqual(
data_point.min,
expected_value,
)

def assert_metric_expected(
self, metric, expected_value, expected_attributes
):
data_point = next(iter(metric.data.data_points))

if isinstance(data_point, HistogramDataPoint):
self.assert_histogram_expected(data_point, expected_value)
elif isinstance(data_point, NumberDataPoint):
self.assertEqual(
data_point.value,
expected_value,
)

self.assertDictEqual(
expected_attributes,
dict(data_point.attributes),
)

def assert_duration_metric_expected(
self, metric, duration_estimated, expected_attributes, est_delta=200
):
data_point = next(iter(metric.data.data_points))

self.assertAlmostEqual(
data_point.sum,
duration_estimated,
delta=est_delta,
)

self.assertDictEqual(
expected_attributes,
dict(data_point.attributes),
)

@staticmethod
def create_tracer_provider(**kwargs):
"""Helper to create a configured tracer provider.
Expand Down