File: test_logs_ingestion_async.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 (181 lines) | stat: -rw-r--r-- 7,363 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
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for
# license information.
# -------------------------------------------------------------------------
import gzip
import os
import json
from unittest import mock
import uuid

import pytest

from azure.core.exceptions import HttpResponseError
from azure.monitor.ingestion.aio import LogsIngestionClient
from azure.monitor.ingestion._version import VERSION

from base_testcase import LogsIngestionClientTestCase


LOGS_BODY = [
    {
        "Time": "2021-12-08T23:51:14.1104269Z",
        "Computer": "Computer1",
        "AdditionalContext": {"testContextKey": 3, "CounterName": "AppMetric1"},
    },
    {
        "Time": "2021-12-08T23:51:14.1104269Z",
        "Computer": "Computer2",
        "AdditionalContext": {"testContextKey": 2, "CounterName": "AppMetric1"},
    },
]


class TestLogsIngestionClientAsync(LogsIngestionClientTestCase):

    @pytest.mark.asyncio
    async def test_send_logs_async(self, recorded_test, monitor_info):
        credential = self.get_credential(LogsIngestionClient, is_async=True)
        client = self.get_client(LogsIngestionClient, credential, endpoint=monitor_info["dce"])
        async with client:
            await client.upload(rule_id=monitor_info["dcr_id"], stream_name=monitor_info["stream_name"], logs=LOGS_BODY)
        await credential.close()

    @pytest.mark.asyncio
    async def test_send_logs_large(self, recorded_test, monitor_info, large_data):
        credential = self.get_credential(LogsIngestionClient, is_async=True)
        client = self.get_client(LogsIngestionClient, credential, endpoint=monitor_info["dce"])
        async with client:
            await client.upload(
                rule_id=monitor_info["dcr_id"], stream_name=monitor_info["stream_name"], logs=large_data
            )
        await credential.close()

    @pytest.mark.asyncio
    async def test_send_logs_error(self, recorded_test, monitor_info):
        credential = self.get_credential(LogsIngestionClient, is_async=True)
        client = self.get_client(LogsIngestionClient, credential, endpoint=monitor_info["dce"])
        body = [{"foo": "bar"}]

        with pytest.raises(HttpResponseError) as ex:
            async with client:
                await client.upload(rule_id="bad-rule", stream_name=monitor_info["stream_name"], logs=body)
        await credential.close()

    @pytest.mark.asyncio
    async def test_send_logs_error_custom(self, recorded_test, monitor_info):
        credential = self.get_credential(LogsIngestionClient, is_async=True)
        client = self.get_client(LogsIngestionClient, credential, endpoint=monitor_info["dce"])
        body = [{"foo": "bar"}]

        async def on_error(e):
            on_error.called = True
            assert isinstance(e.error, HttpResponseError)
            assert e.failed_logs == body

        on_error.called = False

        async with client:
            await client.upload(
                rule_id="bad-rule", stream_name=monitor_info["stream_name"], logs=body, on_error=on_error
            )
        assert on_error.called
        await credential.close()

    @pytest.mark.asyncio
    async def test_send_logs_json_file(self, recorded_test, monitor_info):
        credential = self.get_credential(LogsIngestionClient, is_async=True)
        client = self.get_client(LogsIngestionClient, credential, endpoint=monitor_info["dce"])

        temp_file = str(uuid.uuid4()) + ".json"
        with open(temp_file, "w") as f:
            json.dump(LOGS_BODY, f)

        async with client:
            with open(temp_file, "r") as f:
                await client.upload(rule_id=monitor_info["dcr_id"], stream_name=monitor_info["stream_name"], logs=f)
        os.remove(temp_file)
        await credential.close()

    @pytest.mark.asyncio
    @pytest.mark.live_test_only("Issues recording binary streams with test-proxy")
    async def test_send_logs_gzip_file(self, monitor_info):
        credential = self.get_credential(LogsIngestionClient, is_async=True)
        client = self.get_client(LogsIngestionClient, credential, endpoint=monitor_info["dce"])

        temp_file = str(uuid.uuid4()) + ".json.gz"
        with gzip.open(temp_file, "wb") as f:
            f.write(json.dumps(LOGS_BODY).encode("utf-8"))

        async with client:
            with open(temp_file, "rb") as f:
                await client.upload(rule_id=monitor_info["dcr_id"], stream_name=monitor_info["stream_name"], logs=f)
        os.remove(temp_file)
        await credential.close()

    @pytest.mark.asyncio
    async def test_abort_error_handler(self, monitor_info):
        credential = self.get_credential(LogsIngestionClient, is_async=True)
        client = self.get_client(LogsIngestionClient, credential, endpoint=monitor_info["dce"])

        class TestException(Exception):
            pass

        async def on_error(e):
            on_error.called = True
            if isinstance(e.error, RuntimeError):
                raise TestException("Abort")
            return

        on_error.called = False

        async with client:
            # No exception should be raised
            with mock.patch(
                "azure.monitor.ingestion.aio._operations._patch.GeneratedOps._upload", side_effect=ConnectionError
            ):
                await client.upload(
                    rule_id=monitor_info["dcr_id"],
                    stream_name=monitor_info["stream_name"],
                    logs=LOGS_BODY,
                    on_error=on_error,
                )

            assert on_error.called

            on_error.called = False
            # Exception should now be raised since error handler checked for RuntimeError.
            with mock.patch(
                "azure.monitor.ingestion.aio._operations._patch.GeneratedOps._upload", side_effect=RuntimeError
            ):
                with pytest.raises(TestException):
                    await client.upload(
                        rule_id=monitor_info["dcr_id"],
                        stream_name=monitor_info["stream_name"],
                        logs=LOGS_BODY,
                        on_error=on_error,
                    )

            assert on_error.called
        await credential.close()

    @pytest.mark.asyncio
    @pytest.mark.parametrize("logs", ['[{"foo": "bar"}]', "foo", {"foo": "bar"}, None])
    async def test_invalid_logs_format(self, monitor_info, logs):
        credential = self.get_credential(LogsIngestionClient, is_async=True)
        client = self.get_client(LogsIngestionClient, credential, endpoint=monitor_info["dce"])

        async with client:
            with pytest.raises(ValueError):
                await client.upload(rule_id="rule", stream_name="stream", logs=logs)
        await credential.close()

    @pytest.mark.asyncio
    async def test_user_agent_version(self, monitor_info):
        credential = self.get_credential(LogsIngestionClient, is_async=True)
        client = self.get_client(LogsIngestionClient, credential, endpoint=monitor_info["dce"])

        async with client:
            assert f"azsdk-python-monitor-ingestion/{VERSION}" in client._config.user_agent_policy.user_agent
        await credential.close()