File: test_logs_client_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 (271 lines) | stat: -rw-r--r-- 11,725 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. See LICENSE.txt in the project root for
# license information.
# -------------------------------------------------------------------------
from datetime import timedelta

import pytest

from azure.core.exceptions import HttpResponseError
from azure.monitor.query import (
    LogsBatchQuery,
    LogsQueryError,
    LogsTable,
    LogsQueryResult,
    LogsTableRow,
    LogsQueryStatus,
)
from azure.monitor.query.aio import LogsQueryClient
from azure.monitor.query._version import VERSION

from base_testcase import AzureMonitorQueryLogsTestCase


class TestLogsClientAsync(AzureMonitorQueryLogsTestCase):

    @pytest.mark.asyncio
    async def test_logs_auth(self, recorded_test, monitor_info):
        client = self.get_client(LogsQueryClient, self.get_credential(LogsQueryClient, is_async=True))
        async with client:
            query = """AppRequests |
            where TimeGenerated > ago(12h) |
            summarize avgRequestDuration=avg(DurationMs) by bin(TimeGenerated, 10m), _ResourceId"""

            # returns LogsQueryResult
            response = await client.query_workspace(monitor_info["workspace_id"], query, timespan=None)

            assert response is not None
            assert response.status == LogsQueryStatus.SUCCESS
            assert response.tables is not None

    @pytest.mark.asyncio
    async def test_logs_auth_no_timespan(self, monitor_info):
        client = self.get_client(LogsQueryClient, self.get_credential(LogsQueryClient, is_async=True))
        async with client:
            query = """AppRequests |
            where TimeGenerated > ago(12h) |
            summarize avgRequestDuration=avg(DurationMs) by bin(TimeGenerated, 10m), _ResourceId"""

            # returns LogsQueryResult
            with pytest.raises(TypeError):
                await client.query_workspace(monitor_info["workspace_id"], query)

    @pytest.mark.asyncio
    async def test_logs_server_timeout(self, recorded_test, monitor_info):
        client = self.get_client(LogsQueryClient, self.get_credential(LogsQueryClient, is_async=True))

        try:
            async with client:
                response = await client.query_workspace(
                    monitor_info["workspace_id"],
                    "range x from 1 to 1000000000000000 step 1 | count",
                    timespan=None,
                    server_timeout=2,
                    retry_total=0,
                )
        except HttpResponseError as e:
            assert "Gateway timeout" in e.message
        else:
            # Response an be observed as either 504 response code from the gateway or a partial failure 200 response.
            assert response.status == LogsQueryStatus.PARTIAL
            assert "timed out" in str(response.partial_error)

    @pytest.mark.asyncio
    async def test_logs_query_batch_raises_on_no_timespan(self, monitor_info):
        with pytest.raises(TypeError):
            LogsBatchQuery(
                workspace_id=monitor_info["workspace_id"],
                query="AzureActivity | summarize count()",
            )

    @pytest.mark.live_test_only("Issues recording dynamic 'id' values in requests/responses")
    @pytest.mark.asyncio
    async def test_logs_query_batch_default(self, monitor_info):
        client = self.get_client(LogsQueryClient, self.get_credential(LogsQueryClient, is_async=True))
        async with client:
            requests = [
                LogsBatchQuery(
                    monitor_info["workspace_id"], query="AzureActivity | summarize count()", timespan=timedelta(hours=1)
                ),
                LogsBatchQuery(
                    monitor_info["workspace_id"],
                    query="""AppRequests | take 10  |
                        summarize avgRequestDuration=avg(DurationMs) by bin(TimeGenerated, 10m), _ResourceId""",
                    timespan=timedelta(hours=1),
                ),
                LogsBatchQuery(monitor_info["workspace_id"], query="Wrong query | take 2", timespan=None),
            ]
            response = await client.query_batch(requests)

            assert len(response) == 3
            r0 = response[0]
            assert r0.tables[0].columns == ["count_"]
            r1 = response[1]
            assert r1.tables[0].columns[0] == "TimeGenerated"
            assert r1.tables[0].columns[1] == "_ResourceId"
            assert r1.tables[0].columns[2] == "avgRequestDuration"
            r2 = response[2]
            assert r2.__class__ == LogsQueryError

    @pytest.mark.asyncio
    async def test_logs_single_query_additional_workspaces_async(self, recorded_test, monitor_info):
        client = self.get_client(LogsQueryClient, self.get_credential(LogsQueryClient, is_async=True))
        async with client:
            query = (
                f"{monitor_info['table_name']} | where TimeGenerated > ago(100d)"
                "| project TenantId | summarize count() by TenantId"
            )

            # returns LogsQueryResult
            response = await client.query_workspace(
                monitor_info["workspace_id"],
                query,
                timespan=None,
                additional_workspaces=[monitor_info["secondary_workspace_id"]],
            )

            assert response
            assert len(response.tables[0].rows) == 2

    @pytest.mark.skip("Flaky deserialization issues with msrest. Re-enable after removing msrest dependency.")
    @pytest.mark.live_test_only("Issues recording dynamic 'id' values in requests/responses")
    @pytest.mark.asyncio
    async def test_logs_query_batch_additional_workspaces(self, monitor_info):
        client = self.get_client(LogsQueryClient, self.get_credential(LogsQueryClient, is_async=True))
        async with client:
            query = (
                f"{monitor_info['table_name']} | where TimeGenerated > ago(100d)"
                "| project TenantId | summarize count() by TenantId"
            )
            requests = [
                LogsBatchQuery(
                    monitor_info["workspace_id"],
                    query,
                    timespan=None,
                    additional_workspaces=[monitor_info["secondary_workspace_id"]],
                ),
                LogsBatchQuery(
                    monitor_info["workspace_id"],
                    query,
                    timespan=None,
                    additional_workspaces=[monitor_info["secondary_workspace_id"]],
                ),
                LogsBatchQuery(
                    monitor_info["workspace_id"],
                    query,
                    timespan=None,
                    additional_workspaces=[monitor_info["secondary_workspace_id"]],
                ),
            ]
            response = await client.query_batch(requests)

            assert len(response) == 3
            for resp in response:
                assert len(resp.tables[0].rows) == 2

    @pytest.mark.asyncio
    async def test_logs_single_query_with_visualization(self, recorded_test, monitor_info):
        client = self.get_client(LogsQueryClient, self.get_credential(LogsQueryClient, is_async=True))
        async with client:
            query = """AppRequests | take 10"""

            # returns LogsQueryResult
            response = await client.query_workspace(
                monitor_info["workspace_id"], query, timespan=None, include_visualization=True
            )

            assert response.visualization is not None

    @pytest.mark.asyncio
    async def test_logs_single_query_with_visualization_and_stats(self, recorded_test, monitor_info):
        client = self.get_client(LogsQueryClient, self.get_credential(LogsQueryClient, is_async=True))
        async with client:
            query = """AppRequests | take 10"""
            # returns LogsQueryResult
            response = await client.query_workspace(
                monitor_info["workspace_id"], query, timespan=None, include_visualization=True, include_statistics=True
            )

            assert response.visualization is not None
            assert response.statistics is not None

    @pytest.mark.asyncio
    async def test_logs_query_result_iterate_over_tables(self, recorded_test, monitor_info):
        client = self.get_client(LogsQueryClient, self.get_credential(LogsQueryClient, is_async=True))
        async with client:
            query = "AppRequests | take 10; AppRequests | take 5"
            response = await client.query_workspace(
                monitor_info["workspace_id"], query, timespan=None, include_statistics=True, include_visualization=True
            )

            ## should iterate over tables
            for item in response:
                assert item.__class__ == LogsTable

            assert response.statistics is not None
            assert response.visualization is not None
            assert len(response.tables) == 2
            assert response.__class__ == LogsQueryResult

    @pytest.mark.asyncio
    async def test_logs_query_result_row_type(self, recorded_test, monitor_info):
        client = self.get_client(LogsQueryClient, self.get_credential(LogsQueryClient, is_async=True))
        async with client:
            query = "AppRequests | take 5"
            response = await client.query_workspace(
                monitor_info["workspace_id"],
                query,
                timespan=None,
            )

            ## should iterate over tables
            for table in response:
                assert table.__class__ == LogsTable

                for row in table.rows:
                    assert row.__class__ == LogsTableRow

    @pytest.mark.asyncio
    async def test_logs_resource_query(self, recorded_test, monitor_info):
        client = self.get_client(LogsQueryClient, self.get_credential(LogsQueryClient, is_async=True))
        async with client:
            query = "requests | summarize count()"

            response = await client.query_resource(monitor_info["metrics_resource_id"], query, timespan=None)

            assert response is not None
            assert response.tables is not None
            assert len(response.tables[0].rows) == 1

    @pytest.mark.asyncio
    async def test_logs_resource_query_additional_options(self, recorded_test, monitor_info):
        client = self.get_client(LogsQueryClient, self.get_credential(LogsQueryClient, is_async=True))
        async with client:
            query = "requests | summarize count()"

            response = await client.query_resource(
                monitor_info["metrics_resource_id"],
                query,
                timespan=None,
                include_statistics=True,
                include_visualization=True,
            )

            assert response.visualization is not None
            assert response.statistics is not None

    @pytest.mark.asyncio
    async def test_client_different_endpoint(self):
        credential = self.get_credential(LogsQueryClient, is_async=True)
        endpoint = "https://api.loganalytics.azure.cn/v1"
        client = LogsQueryClient(credential, endpoint=endpoint)

        assert client._endpoint == endpoint
        assert "https://api.loganalytics.azure.cn/.default" in client._client._config.authentication_policy._scopes

    @pytest.mark.asyncio
    async def test_client_user_agent(self):
        client: LogsQueryClient = self.get_client(LogsQueryClient, self.get_credential(LogsQueryClient, is_async=True))
        async with client:
            assert f"monitor-query/{VERSION}" in client._client._config.user_agent_policy.user_agent