File: test_exporter.py

package info (click to toggle)
python-azure 20250603%2Bgit-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 851,724 kB
  • sloc: python: 7,362,925; ansic: 804; javascript: 287; makefile: 195; sh: 145; xml: 109
file content (404 lines) | stat: -rw-r--r-- 18,476 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.

import unittest
from unittest import mock

from opentelemetry.sdk.metrics.export import (
    AggregationTemporality,
    Metric,
    MetricExportResult,
    MetricsData as OTMetricsData,
    NumberDataPoint,
    ResourceMetrics,
    ScopeMetrics,
    Sum,
)
from opentelemetry.sdk.util.instrumentation import InstrumentationScope
from opentelemetry.sdk.resources import Resource, ResourceAttributes
from azure.core.exceptions import HttpResponseError
from azure.monitor.opentelemetry.exporter._quickpulse._generated._client import QuickpulseClient
from azure.monitor.opentelemetry.exporter._quickpulse._generated.models import MonitoringDataPoint
from azure.monitor.opentelemetry.exporter._quickpulse._exporter import (
    _POST_INTERVAL_SECONDS,
    _QuickpulseExporter,
    _QuickpulseMetricReader,
    _QuickpulseState,
    _Response,
    _UnsuccessfulQuickPulsePostError,
)
from azure.monitor.opentelemetry.exporter._quickpulse._state import (
    _get_global_quickpulse_state,
    _get_quickpulse_etag,
    _set_global_quickpulse_state,
    _set_quickpulse_etag,
    _QuickpulseState,
)


def throw(exc_type, *args, **kwargs):
    def func(*_args, **_kwargs):
        raise exc_type(*args, **kwargs)

    return func


class TestQuickpulse(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        _set_global_quickpulse_state(_QuickpulseState.PING_SHORT)
        cls._resource = Resource.create(
            {
                ResourceAttributes.SERVICE_INSTANCE_ID: "test_instance",
                ResourceAttributes.SERVICE_NAME: "test_service",
            }
        )
        cls._metrics_data = OTMetricsData(
            resource_metrics=ResourceMetrics(
                resource=cls._resource,
                scope_metrics=ScopeMetrics(
                    scope=InstrumentationScope("test_scope"),
                    metrics=[
                        Metric(
                            name="azureMonitor.memoryCommittedBytes",
                            description="test_desc",
                            unit="test_unit",
                            data=Sum(
                                data_points=[
                                    NumberDataPoint(
                                        attributes={},
                                        start_time_unix_nano=0,
                                        time_unix_nano=0,
                                        value=5,
                                    )
                                ],
                                aggregation_temporality=AggregationTemporality.DELTA,
                                is_monotonic=True,
                            ),
                        )
                    ],
                    schema_url="test_url",
                ),
                schema_url="test_url",
            )
        )
        cls._data_point = MonitoringDataPoint(
            version="test_version",
            invariant_version=1,
            instance="test_instance",
            role_name="test_role_name",
            machine_name="test_machine_name",
            stream_id="test_stream_id",
            is_web_app=False,
            performance_collection_supported=True,
        )
        cls._exporter = _QuickpulseExporter(
            connection_string="InstrumentationKey=4321abcd-5678-4efa-8abc-1234567890ac;LiveEndpoint=https://eastus.livediagnostics.monitor.azure.com/"
        )
        cls._reader = _QuickpulseMetricReader(
            cls._exporter,
            cls._data_point,
        )

    @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._generated._client.QuickpulseClient")
    def test_init(self, client_mock):
        exporter = _QuickpulseExporter(
            connection_string="InstrumentationKey=4321abcd-5678-4efa-8abc-1234567890ab;LiveEndpoint=https://eastus.livediagnostics.monitor.azure.com/"
        )
        self.assertEqual(exporter._live_endpoint, "https://eastus.livediagnostics.monitor.azure.com/")
        self.assertEqual(exporter._instrumentation_key, "4321abcd-5678-4efa-8abc-1234567890ab")
        self.assertTrue(isinstance(exporter._client, QuickpulseClient))

    def test_export_missing_data_point(self):
        result = self._exporter.export(OTMetricsData(resource_metrics=[]))
        self.assertEqual(result, MetricExportResult.FAILURE)

    @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._generated._client.QuickpulseClient.publish")
    @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._exporter._metric_to_quick_pulse_data_points")
    def test_export_subscribed_false(self, convert_mock, post_mock):
        post_response = _Response(
            mock.Mock(),
            None,
            {
                "x-ms-qps-subscribed": "false",
            },
        )
        convert_mock.return_value = [self._data_point]
        post_mock.return_value = post_response
        result = self._exporter.export(self._metrics_data, base_monitoring_data_point=self._data_point)
        self.assertEqual(result, MetricExportResult.FAILURE)

    @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._generated._client.QuickpulseClient.publish")
    @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._exporter._metric_to_quick_pulse_data_points")
    def test_export_subscribed_none(self, convert_mock, post_mock):
        post_response = None
        convert_mock.return_value = [self._data_point]
        post_mock.return_value = post_response
        result = self._exporter.export(self._metrics_data, base_monitoring_data_point=self._data_point)
        self.assertEqual(result, MetricExportResult.FAILURE)

    @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._exporter._metric_to_quick_pulse_data_points")
    def test_export_exception(self, convert_mock):
        post_response = _Response(
            mock.Mock(),
            None,
            {},
        )
        convert_mock.return_value = [self._data_point]
        with mock.patch(
            "azure.monitor.opentelemetry.exporter._quickpulse._generated._client.QuickpulseClient.publish",
            throw(Exception),
        ):  # noqa: E501
            result = self._exporter.export(self._metrics_data, base_monitoring_data_point=self._data_point)
            self.assertEqual(result, MetricExportResult.FAILURE)

    @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._generated._client.QuickpulseClient.publish")
    @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._exporter._metric_to_quick_pulse_data_points")
    def test_export_subscribed_true(self, convert_mock, post_mock):
        post_response = _Response(
            mock.Mock(),
            None,
            {
                "x-ms-qps-subscribed": "true",
            },
        )
        convert_mock.return_value = [self._data_point]
        post_mock.return_value = post_response
        result = self._exporter.export(self._metrics_data, base_monitoring_data_point=self._data_point)
        self.assertEqual(result, MetricExportResult.SUCCESS)

    @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._exporter._update_filter_configuration")
    @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._generated._client.QuickpulseClient.publish")
    @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._exporter._metric_to_quick_pulse_data_points")
    @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._exporter._get_quickpulse_etag")
    def test_export_subscribed_true_etag_changed(self, etag_mock, convert_mock, post_mock, update_filter_mock):
        pipeline_response = mock.Mock()
        config = {"test-config": "test-config-value"}
        pipeline_response.http_response.content = config
        post_response = _Response(
            pipeline_response,
            None,
            {
                "x-ms-qps-subscribed": "true",
                "x-ms-qps-configuration-etag": "new-etag",
            },
        )
        convert_mock.return_value = [self._data_point]
        post_mock.return_value = post_response
        etag_mock.return_value = "old-etag"
        result = self._exporter.export(self._metrics_data, base_monitoring_data_point=self._data_point)
        self.assertEqual(result, MetricExportResult.SUCCESS)
        update_filter_mock.assert_called_once_with("new-etag", config)

    @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._exporter._update_filter_configuration")
    @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._generated._client.QuickpulseClient.publish")
    @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._exporter._metric_to_quick_pulse_data_points")
    @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._exporter._get_quickpulse_etag")
    def test_export_subscribed_true_etag_same(self, etag_mock, convert_mock, post_mock, update_filter_mock):
        pipeline_response = mock.Mock()
        config = {"test-config": "test-config-value"}
        pipeline_response.http_response.content = config
        post_response = _Response(
            pipeline_response,
            None,
            {
                "x-ms-qps-subscribed": "true",
                "x-ms-qps-configuration-etag": "old-etag",
            },
        )
        convert_mock.return_value = [self._data_point]
        post_mock.return_value = post_response
        etag_mock.return_value = "old-etag"
        result = self._exporter.export(self._metrics_data, base_monitoring_data_point=self._data_point)
        self.assertEqual(result, MetricExportResult.SUCCESS)
        update_filter_mock.assert_not_called()

    @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._generated._client.QuickpulseClient.is_subscribed")
    def test_ping(self, ping_mock):
        ping_response = _Response(
            mock.Mock(),
            None,
            {
                "x-ms-qps-subscribed": "false",
            },
        )
        ping_mock.return_value = ping_response
        response = self._exporter._ping(monitoring_data_point=self._data_point)
        self.assertEqual(response, ping_response)

    def test_ping_exception(self):
        with mock.patch(
            "azure.monitor.opentelemetry.exporter._quickpulse._generated._client.QuickpulseClient.is_subscribed",
            throw(HttpResponseError),
        ):  # noqa: E501
            response = self._exporter._ping(monitoring_data_point=self._data_point)
            self.assertIsNone(response)

    @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._generated._client.QuickpulseClient.is_subscribed")
    def test_ping_etag_response(self, ping_mock):
        ping_response = _Response(
            mock.Mock(),
            None,
            {
                "x-ms-qps-subscribed": "false",
                "x-ms-qps-configuration-etag": "new-etag",
            },
        )
        ping_mock.return_value = ping_response
        response = self._exporter._ping(monitoring_data_point=self._data_point)
        self.assertEqual(response, ping_response)
        self.assertEqual(response._response_headers["x-ms-qps-configuration-etag"], "new-etag")

    @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._exporter.PeriodicTask")
    def test_quickpulsereader_init(self, task_mock):
        task_inst_mock = mock.Mock()
        task_mock.return_value = task_inst_mock
        reader = _QuickpulseMetricReader(
            self._exporter,
            self._data_point,
        )
        self.assertEqual(reader._exporter, self._exporter)
        self.assertEqual(_get_global_quickpulse_state(), _QuickpulseState.PING_SHORT)
        self.assertEqual(reader._base_monitoring_data_point, self._data_point)
        self.assertEqual(reader._elapsed_num_seconds, 0)
        self.assertEqual(reader._worker, task_inst_mock)
        task_mock.assert_called_with(
            interval=_POST_INTERVAL_SECONDS,
            function=reader._ticker,
            name="QuickpulseMetricReader",
        )
        self.assertTrue(reader._worker.daemon)
        task_inst_mock.start.assert_called_once()

    @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._exporter._QuickpulseExporter._ping")
    @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._exporter.PeriodicTask")
    def test_quickpulsereader_ticker_ping_true(self, task_mock, ping_mock):
        task_inst_mock = mock.Mock()
        task_mock.return_value = task_inst_mock
        reader = _QuickpulseMetricReader(
            self._exporter,
            self._data_point,
        )
        _set_global_quickpulse_state(_QuickpulseState.PING_SHORT)
        reader._elapsed_num_seconds = _QuickpulseState.PING_SHORT.value
        ping_mock.return_value = _Response(None, None, {"x-ms-qps-subscribed": "true"})
        reader._ticker()
        ping_mock.assert_called_once_with(
            self._data_point,
        )
        self.assertEqual(_get_global_quickpulse_state(), _QuickpulseState.POST_SHORT)
        self.assertEqual(reader._elapsed_num_seconds, 1)

    @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._exporter._QuickpulseExporter._ping")
    @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._exporter.PeriodicTask")
    def test_quickpulsereader_ticker_ping_false_backoff(self, task_mock, ping_mock):
        task_inst_mock = mock.Mock()
        task_mock.return_value = task_inst_mock
        reader = _QuickpulseMetricReader(
            self._exporter,
            self._data_point,
        )
        _set_global_quickpulse_state(_QuickpulseState.PING_SHORT)
        reader._elapsed_num_seconds = 60
        ping_mock.return_value = _Response(None, None, {"x-ms-qps-subscribed": "false"})
        reader._ticker()
        ping_mock.assert_called_once_with(
            self._data_point,
        )
        self.assertEqual(_get_global_quickpulse_state(), _QuickpulseState.PING_LONG)
        self.assertEqual(reader._elapsed_num_seconds, _QuickpulseState.PING_LONG.value + 1)
        self.assertEqual(_get_quickpulse_etag(), "")

    @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._exporter._QuickpulseExporter._ping")
    @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._exporter.PeriodicTask")
    def test_ticker_erroneous_no_response_backoff(self, task_mock, ping_mock):
        _set_global_quickpulse_state(_QuickpulseState.PING_SHORT)
        _set_quickpulse_etag("old-etag")
        task_inst_mock = mock.Mock()
        task_mock.return_value = task_inst_mock
        reader = _QuickpulseMetricReader(
            self._exporter,
            self._data_point,
        )
        reader._elapsed_num_seconds = 60
        ping_mock.return_value = None
        reader._ticker()
        self.assertEqual(_get_global_quickpulse_state(), _QuickpulseState.PING_LONG)
        self.assertEqual(_get_quickpulse_etag(), "")

    @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._exporter._QuickpulseMetricReader.collect")
    @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._exporter.PeriodicTask")
    def test_ticker_post_state(self, task_mock, collect_mock):
        _set_global_quickpulse_state(_QuickpulseState.POST_SHORT)
        task_inst_mock = mock.Mock()
        task_mock.return_value = task_inst_mock
        reader = _QuickpulseMetricReader(
            self._exporter,
            self._data_point,
        )
        reader._elapsed_num_seconds = 0
        reader._ticker()
        collect_mock.assert_called_once()
        self.assertEqual(_get_global_quickpulse_state(), _QuickpulseState.POST_SHORT)
        self.assertEqual(reader._elapsed_num_seconds, 1)

    @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._exporter._QuickpulseMetricReader.collect")
    @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._exporter.PeriodicTask")
    def test_ticker_post_unsuccessful_backoff(self, task_mock, collect_mock):
        _set_global_quickpulse_state(_QuickpulseState.POST_SHORT)
        task_inst_mock = mock.Mock()
        task_mock.return_value = task_inst_mock
        reader = _QuickpulseMetricReader(
            self._exporter,
            self._data_point,
        )
        reader._elapsed_num_seconds = 20
        with mock.patch(
            "azure.monitor.opentelemetry.exporter._quickpulse._exporter._QuickpulseMetricReader.collect",
            throw(_UnsuccessfulQuickPulsePostError),
        ):  # noqa: E501
            reader._ticker()
            self.assertEqual(_get_global_quickpulse_state(), _QuickpulseState.PING_SHORT)
            self.assertEqual(reader._elapsed_num_seconds, 1)

    @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._exporter._QuickpulseExporter.export")
    @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._exporter.PeriodicTask")
    def test_quickpulsereader_receive_metrics(self, task_mock, export_mock):
        task_inst_mock = mock.Mock()
        task_mock.return_value = task_inst_mock
        reader = _QuickpulseMetricReader(
            self._exporter,
            self._data_point,
        )
        export_mock.return_value = MetricExportResult.SUCCESS
        reader._receive_metrics(
            self._metrics_data,
            20_000,
        )
        export_mock.assert_called_once_with(
            self._metrics_data,
            timeout_millis=20_000,
            base_monitoring_data_point=self._data_point,
        )

    @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._exporter._QuickpulseExporter.export")
    @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._exporter.PeriodicTask")
    def test_quickpulsereader_receive_metrics_exception(self, task_mock, export_mock):
        task_inst_mock = mock.Mock()
        task_mock.return_value = task_inst_mock
        reader = _QuickpulseMetricReader(
            self._exporter,
            self._data_point,
        )
        export_mock.return_value = MetricExportResult.FAILURE
        with self.assertRaises(_UnsuccessfulQuickPulsePostError):
            reader._receive_metrics(
                self._metrics_data,
                20_000,
            )
            export_mock.assert_called_once_with(
                self._metrics_data,
                timeout_millis=20_000,
                base_monitoring_data_point=self._data_point,
                documents=[],
            )