File: test_base_exporter.py

package info (click to toggle)
python-azure 20201208%2Bgit-6
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 1,437,920 kB
  • sloc: python: 4,287,452; javascript: 269; makefile: 198; sh: 187; xml: 106
file content (271 lines) | stat: -rw-r--r-- 11,209 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
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.

import json
import os
import shutil
import unittest
from unittest import mock
from datetime import datetime

import requests
from opentelemetry.sdk.metrics.export import MetricsExportResult
from opentelemetry.sdk.trace.export import SpanExportResult

from microsoft.opentelemetry.exporter.azuremonitor.export._base import (
    BaseExporter,
    ExportResult,
    get_trace_export_result,
)
from microsoft.opentelemetry.exporter.azuremonitor._options import ExporterOptions
from microsoft.opentelemetry.exporter.azuremonitor._generated.models import TelemetryItem


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

    return func


# pylint: disable=W0212
# pylint: disable=R0904
class TestBaseExporter(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        os.environ[
            "APPINSIGHTS_INSTRUMENTATIONKEY"
        ] = "1234abcd-5678-4efa-8abc-1234567890ab"
        cls._base = BaseExporter()
        cls._envelopes_to_export = [TelemetryItem(name="Test", time=datetime.now())]

    @classmethod
    def tearDownClass(cls):
        shutil.rmtree(cls._base.storage._path, True)

    def test_constructor(self):
        """Test the constructor."""
        base = BaseExporter(
            connection_string="InstrumentationKey=4321abcd-5678-4efa-8abc-1234567890ab",
        )
        self.assertEqual(
            base._instrumentation_key,
            "4321abcd-5678-4efa-8abc-1234567890ab",
        )
        self.assertEqual(base.storage._max_size, 52428800)
        self.assertEqual(base.storage._retention_period, 604800)
        self.assertEqual(base._timeout, 10)

    def test_constructor_wrong_options(self):
        """Test the constructor with wrong options."""
        with self.assertRaises(TypeError):
            BaseExporter(something_else=6)

    def test_transmit_from_storage(self):
        envelopes_to_store = [x.as_dict() for x in self._envelopes_to_export]
        self._base.storage.put(envelopes_to_store)
        with mock.patch("requests.Session.request") as post:
            post.return_value = MockResponse(200, "OK")
            self._base._transmit_from_storage()
        # Run storage process to check lease, retention and timeout and clean file if needed
        self._base.storage.get()
        # File no longer present
        self.assertEqual(len(os.listdir(self._base.storage._path)), 0)

    def test_transmit_from_storage_failed_retryable(self):
        envelopes_to_store = [x.as_dict() for x in self._envelopes_to_export]
        self._base.storage.put(envelopes_to_store)
        # Timeout in HTTP request is a retryable case
        with mock.patch("requests.Session.request", throw(requests.Timeout)):
            self._base._transmit_from_storage()
        # File would be locked for 1 second
        self.assertIsNone(self._base.storage.get())
        # File still present
        self.assertGreaterEqual(len(os.listdir(self._base.storage._path)), 1)

    def test_transmit_from_storage_failed_not_retryable(self):
        envelopes_to_store = [x.as_dict() for x in self._envelopes_to_export]
        self._base.storage.put(envelopes_to_store)
        with mock.patch("requests.Session.request") as post:
            # Do not retry with internal server error responses
            post.return_value = MockResponse(400, "{}")
            self._base._transmit_from_storage()
        self._base.storage.get()
        # File no longer present
        self.assertEqual(len(os.listdir(self._base.storage._path)), 0)

    def test_transmit_from_storage_nothing(self):
        with mock.patch("requests.Session.request") as post:
            post.return_value = None
            self._base._transmit_from_storage()

    @mock.patch("requests.Session.request", return_value=mock.Mock())
    def test_transmit_from_storage_lease_failure(self, requests_mock):
        requests_mock.return_value = MockResponse(200, "unknown")
        envelopes_to_store = [x.as_dict() for x in self._envelopes_to_export]
        self._base.storage.put(envelopes_to_store)
        with mock.patch(
            "microsoft.opentelemetry.exporter.azuremonitor._storage.LocalFileBlob.lease"
        ) as lease:  # noqa: E501
            lease.return_value = False
            self._base._transmit_from_storage()
        self.assertTrue(self._base.storage.get())

    def test_transmit_request_timeout(self):
        with mock.patch("requests.Session.request", throw(requests.Timeout)):
            result = self._base._transmit(self._envelopes_to_export)
        self.assertEqual(result, ExportResult.FAILED_RETRYABLE)

    def test_transmit_request_exception(self):
        with mock.patch("requests.Session.request", throw(Exception)):
            result = self._base._transmit(self._envelopes_to_export)
        self.assertEqual(result, ExportResult.FAILED_RETRYABLE)

    def test_transmission_200(self):
        with mock.patch("requests.Session.request") as post:
            post.return_value = MockResponse(200, json.dumps(
                {
                    "itemsReceived": 1,
                    "itemsAccepted": 1,
                    "errors": [],
                }
            ), reason="OK", content="")
            result = self._base._transmit(self._envelopes_to_export)
        self.assertEqual(result, ExportResult.SUCCESS)

    def test_transmission_206(self):
        with mock.patch("requests.Session.request") as post:
            post.return_value = MockResponse(206, "unknown")
            result = self._base._transmit(self._envelopes_to_export)
        self.assertEqual(result, ExportResult.FAILED_RETRYABLE)

    def test_transmission_206_500(self):
        test_envelope = TelemetryItem(name="testEnvelope", time=datetime.now())
        custom_envelopes_to_export = [TelemetryItem(name="Test", time=datetime.now(
        )), TelemetryItem(name="Test", time=datetime.now()), test_envelope]
        with mock.patch("requests.Session.request") as post:
            post.return_value = MockResponse(
                206,
                json.dumps(
                    {
                        "itemsReceived": 5,
                        "itemsAccepted": 3,
                        "errors": [
                            {"index": 0, "statusCode": 400, "message": ""},
                            {
                                "index": 2,
                                "statusCode": 500,
                                "message": "Internal Server Error",
                            },
                        ],
                    }
                ),
            )
            result = self._base._transmit(custom_envelopes_to_export)
        self.assertEqual(result, ExportResult.FAILED_RETRYABLE)
        self._base.storage.get()
        self.assertEqual(
            self._base.storage.get().get()[0]["name"], "testEnvelope"
        )

    def test_transmission_206_no_retry(self):
        envelopes_to_export = map(lambda x: x.as_dict(), tuple(
            [TelemetryItem(name="testEnvelope", time=datetime.now())]))
        self._base.storage.put(envelopes_to_export)
        with mock.patch("requests.Session.request") as post:
            post.return_value = MockResponse(
                206,
                json.dumps(
                    {
                        "itemsReceived": 3,
                        "itemsAccepted": 2,
                        "errors": [
                            {"index": 0, "statusCode": 400, "message": ""}
                        ],
                    }
                ),
            )
            result = self._base._transmit(self._envelopes_to_export)
        self.assertEqual(result, ExportResult.FAILED_NOT_RETRYABLE)

    def test_transmission_206_bogus(self):
        envelopes_to_export = map(lambda x: x.as_dict(), tuple(
            [TelemetryItem(name="testEnvelope", time=datetime.now())]))
        self._base.storage.put(envelopes_to_export)
        with mock.patch("requests.Session.request") as post:
            post.return_value = MockResponse(
                206,
                json.dumps(
                    {
                        "itemsReceived": 5,
                        "itemsAccepted": 3,
                        "errors": [{"foo": 0, "bar": 1}],
                    }
                ),
            )
            result = self._base._transmit(self._envelopes_to_export)
        self.assertEqual(result, ExportResult.FAILED_NOT_RETRYABLE)

    def test_transmission_400(self):
        with mock.patch("requests.Session.request") as post:
            post.return_value = MockResponse(400, "{}")
            result = self._base._transmit(self._envelopes_to_export)
        self.assertEqual(result, ExportResult.FAILED_NOT_RETRYABLE)

    def test_transmission_408(self):
        with mock.patch("requests.Session.request") as post:
            post.return_value = MockResponse(408, "{}")
            result = self._base._transmit(self._envelopes_to_export)
        self.assertEqual(result, ExportResult.FAILED_RETRYABLE)

    def test_transmission_429(self):
        with mock.patch("requests.Session.request") as post:
            post.return_value = MockResponse(429, "{}")
            result = self._base._transmit(self._envelopes_to_export)
        self.assertEqual(result, ExportResult.FAILED_RETRYABLE)

    def test_transmission_439(self):
        with mock.patch("requests.Session.request") as post:
            post.return_value = MockResponse(439, "{}")
            result = self._base._transmit(self._envelopes_to_export)
        self.assertEqual(result, ExportResult.FAILED_RETRYABLE)

    def test_transmission_500(self):
        with mock.patch("requests.Session.request") as post:
            post.return_value = MockResponse(500, "{}")
            result = self._base._transmit(self._envelopes_to_export)
        self.assertEqual(result, ExportResult.FAILED_RETRYABLE)

    def test_transmission_503(self):
        with mock.patch("requests.Session.request") as post:
            post.return_value = MockResponse(503, "{}")
            result = self._base._transmit(self._envelopes_to_export)
        self.assertEqual(result, ExportResult.FAILED_RETRYABLE)

    def test_transmission_empty(self):
        status = self._base._transmit([])
        self.assertEqual(status, ExportResult.SUCCESS)

    def test_get_trace_export_result(self):
        self.assertEqual(
            get_trace_export_result(ExportResult.SUCCESS),
            SpanExportResult.SUCCESS,
        )
        self.assertEqual(
            get_trace_export_result(ExportResult.FAILED_NOT_RETRYABLE),
            SpanExportResult.FAILURE,
        )
        self.assertEqual(
            get_trace_export_result(ExportResult.FAILED_RETRYABLE),
            SpanExportResult.FAILURE,
        )
        self.assertEqual(get_trace_export_result(None), None)


class MockResponse:
    def __init__(self, status_code, text, headers={}, reason="test", content="{}"):
        self.status_code = status_code
        self.text = text
        self.headers = headers
        self.reason = reason
        self.content = content