File: test_logs_client_async.py

package info (click to toggle)
python-azure 20230112%2Bgit-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 749,544 kB
  • sloc: python: 6,815,827; javascript: 287; makefile: 195; xml: 109; sh: 105
file content (228 lines) | stat: -rw-r--r-- 9,797 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
# -------------------------------------------------------------------------
# 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
from azure.monitor.query.aio import LogsQueryClient
from devtools_testutils import AzureRecordedTestCase


class TestLogsClientAsync(AzureRecordedTestCase):

    @pytest.mark.asyncio
    async def test_logs_auth(self, recorded_test, monitor_info):
        client = self.create_client_from_credential(
            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.tables is not None

    @pytest.mark.asyncio
    async def test_logs_auth_no_timespan(self, monitor_info):
        client = self.create_client_from_credential(
            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.create_client_from_credential(
            LogsQueryClient, self.get_credential(LogsQueryClient, is_async=True))
        async with client:
            with pytest.raises(HttpResponseError) as e:
                response = await client.query_workspace(
                    monitor_info['workspace_id'],
                    "range x from 1 to 10000000000 step 1 | count",
                    timespan=None,
                    server_timeout=1,
                )
                assert e.message.contains('Gateway timeout')

    @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.create_client_from_credential(
            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.create_client_from_credential(
            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.create_client_from_credential(
            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.create_client_from_credential(
            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.create_client_from_credential(
            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.create_client_from_credential(
            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.create_client_from_credential(
            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