Skip to content

Commit 8e2014e

Browse files
authored
Fix Azure.Monitor.Query live tests (Azure#21609)
1 parent 70ae544 commit 8e2014e

File tree

13 files changed

+265
-146
lines changed

13 files changed

+265
-146
lines changed

sdk/monitor/Azure.Monitor.Query/README.md

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -269,7 +269,6 @@ try
269269
catch (Exception e)
270270
{
271271
Console.WriteLine(e);
272-
throw;
273272
}
274273
```
275274

sdk/monitor/Azure.Monitor.Query/src/Generated/Models/LogsBatchQueryResultInternal.Serialization.cs

Lines changed: 0 additions & 35 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

sdk/monitor/Azure.Monitor.Query/src/LogsQueryClient.cs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ namespace Azure.Monitor.Query
1717
/// </summary>
1818
public class LogsQueryClient
1919
{
20+
private static readonly TimeSpan _networkTimeoutOffset = TimeSpan.FromSeconds(15);
2021
private readonly QueryRestClient _queryClient;
2122
private readonly ClientDiagnostics _clientDiagnostics;
2223
private readonly HttpPipeline _pipeline;
@@ -226,7 +227,8 @@ private async Task<Response<LogsQueryResult>> ExecuteAsync(string workspaceId, s
226227

227228
if (options?.ServerTimeout != null)
228229
{
229-
message.NetworkTimeout = options.ServerTimeout;
230+
// Offset the service timeout a bit to make sure we have time to receive the response.
231+
message.NetworkTimeout = options.ServerTimeout.Value.Add(_networkTimeoutOffset);
230232
}
231233

232234
if (async)
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
// Copyright (c) Microsoft Corporation. All rights reserved.
2+
// Licensed under the MIT License.
3+
4+
using System;
5+
using System.Collections.Generic;
6+
using System.Text.Json;
7+
using Azure.Core;
8+
9+
namespace Azure.Monitor.Query.Models
10+
{
11+
[CodeGenModel("logQueryResult")]
12+
internal partial class LogsBatchQueryResultInternal: LogsQueryResult
13+
{
14+
internal ErrorInfo Error { get; }
15+
16+
// TODO, remove after https://github.com/Azure/azure-sdk-for-net/issues/21655 is fixed
17+
internal static LogsBatchQueryResultInternal DeserializeLogsBatchQueryResultInternal(JsonElement element)
18+
{
19+
Optional<ErrorInfo> error = default;
20+
IReadOnlyList<LogsQueryResultTable> tables = default;
21+
Optional<JsonElement> statistics = default;
22+
23+
// This is the workaround to remove the double-encoding
24+
if (element.ValueKind == JsonValueKind.String)
25+
{
26+
try
27+
{
28+
using var document = JsonDocument.Parse(element.GetString());
29+
element = document.RootElement.Clone();
30+
}
31+
catch
32+
{
33+
// ignore
34+
}
35+
}
36+
37+
foreach (var property in element.EnumerateObject())
38+
{
39+
if (property.NameEquals("error"))
40+
{
41+
if (property.Value.ValueKind == JsonValueKind.Null)
42+
{
43+
property.ThrowNonNullablePropertyIsNull();
44+
continue;
45+
}
46+
error = ErrorInfo.DeserializeErrorInfo(property.Value);
47+
continue;
48+
}
49+
if (property.NameEquals("tables"))
50+
{
51+
List<LogsQueryResultTable> array = new List<LogsQueryResultTable>();
52+
foreach (var item in property.Value.EnumerateArray())
53+
{
54+
array.Add(LogsQueryResultTable.DeserializeLogsQueryResultTable(item));
55+
}
56+
tables = array;
57+
continue;
58+
}
59+
if (property.NameEquals("statistics"))
60+
{
61+
statistics = property.Value.Clone();
62+
continue;
63+
}
64+
}
65+
return new LogsBatchQueryResultInternal(tables, statistics, error.Value);
66+
}
67+
}
68+
}

sdk/monitor/Azure.Monitor.Query/src/Models/LogsQueryResult.cs

Lines changed: 0 additions & 13 deletions
This file was deleted.

sdk/monitor/Azure.Monitor.Query/tests/LogsClientSamples.cs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -217,7 +217,6 @@ public async Task BadRequest()
217217
catch (Exception e)
218218
{
219219
Console.WriteLine(e);
220-
throw;
221220
}
222221
#endregion
223222
}

sdk/monitor/Azure.Monitor.Query/tests/LogsQueryClientClientLiveTests.cs

Lines changed: 30 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,10 @@ private LogsQueryClient CreateClient()
3232
return InstrumentClient(new LogsQueryClient(
3333
TestEnvironment.LogsEndpoint,
3434
TestEnvironment.Credential,
35-
InstrumentClientOptions(new LogsQueryClientOptions())
35+
InstrumentClientOptions(new LogsQueryClientOptions()
36+
{
37+
Diagnostics = { IsLoggingContentEnabled = true }
38+
})
3639
));
3740
}
3841

@@ -444,6 +447,7 @@ public async Task ThrowsExceptionWhenBatchQueryNotFound()
444447

445448
LogsBatchQuery batch = new LogsBatchQuery();
446449
batch.AddQuery(TestEnvironment.WorkspaceId, _logsTestData.TableAName, _logsTestData.DataTimeRange);
450+
447451
var batchResult = await client.QueryBatchAsync(batch);
448452

449453
var exception = Assert.Throws<ArgumentException>(() => batchResult.Value.GetResult("12345"));
@@ -502,16 +506,35 @@ public async Task CanQueryWithStatisticsBatch(bool include)
502506
}
503507

504508
[RecordedTest]
505-
public void CanSetServiceTimeout()
509+
public async Task CanSetServiceTimeout()
506510
{
507511
var client = CreateClient();
508512

509-
var exception = Assert.ThrowsAsync<RequestFailedException>(async () => await client.QueryAsync(TestEnvironment.WorkspaceId, "range x from 1 to 100000000000 step 1 | count", _logsTestData.DataTimeRange, options: new LogsQueryOptions()
513+
// Sometimes the service doesn't abort the query quickly enough
514+
// and the request gets aborted instead
515+
// Retry until we get the service to abort
516+
while (true)
510517
{
511-
ServerTimeout = TimeSpan.FromSeconds(1)
512-
}));
513-
514-
Assert.AreEqual(504, exception.Status);
518+
// Punch through caching
519+
var cnt = 100000000000 + Recording.Random.Next(10000);
520+
try
521+
{
522+
await client.QueryAsync(TestEnvironment.WorkspaceId, $"range x from 1 to {cnt} step 1 | count", _logsTestData.DataTimeRange, options: new LogsQueryOptions()
523+
{
524+
ServerTimeout = TimeSpan.FromSeconds(1)
525+
});
526+
}
527+
catch (TaskCanceledException)
528+
{
529+
// The client cancelled, retry.
530+
continue;
531+
}
532+
catch (RequestFailedException exception)
533+
{
534+
Assert.AreEqual(504, exception.Status);
535+
return;
536+
}
537+
}
515538
}
516539

517540
private record TestModel

sdk/monitor/Azure.Monitor.Query/tests/LogsQueryClientClientTests.cs

Lines changed: 42 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,10 @@
22
// Licensed under the MIT License.
33

44
using System;
5+
using System.Threading.Tasks;
6+
using Azure.Core;
57
using Azure.Core.TestFramework;
8+
using Azure.Monitor.Query.Models;
69
using NUnit.Framework;
710

811
namespace Azure.Monitor.Query.Tests
@@ -20,7 +23,7 @@ public void CanSetServiceTimeout_Mocked()
2023
Assert.True(message.Request.Headers.TryGetValue("prefer", out preferHeader));
2124
networkOverride = message.NetworkTimeout;
2225

23-
return new MockResponse(500);
26+
return new MockResponse(403);
2427
});
2528

2629
var client = new LogsQueryClient(new Uri("https://api.loganalytics.io"), new MockCredential(), new LogsQueryClientOptions()
@@ -34,7 +37,44 @@ public void CanSetServiceTimeout_Mocked()
3437
}));
3538

3639
Assert.AreEqual("wait=600", preferHeader);
37-
Assert.AreEqual(TimeSpan.FromMinutes(10), networkOverride);
40+
// The network timeout is adjusted with 15 sec buffer
41+
Assert.AreEqual(TimeSpan.FromMinutes(10).Add(TimeSpan.FromSeconds(15)), networkOverride);
42+
}
43+
44+
[Test]
45+
public async Task QueryBatchHandledInvalidResponse()
46+
{
47+
var badResponse = @"{
48+
""responses"": [
49+
{
50+
""id"": ""0"",
51+
""status"": 200,
52+
""headers"": {
53+
""Age"": ""3"",
54+
""request-context"": ""appId=cid-v1:70941e4f-7e8f-40b7-b730-183893db0297""
55+
},
56+
""body"": ""{\""tables\"":[{\""name\"":\""PrimaryResult\"",\""columns\"":[{\""name\"":\""TenantId\"",\""type\"":\""string\""},{\""name\"":\""SourceSystem\"",\""type\"":\""string\""},{\""name\"":\""MG\"",\""type\"":\""string\""},{\""name\"":\""ManagementGroupName\"",\""type\"":\""string\""},{\""name\"":\""TimeGenerated\"",\""type\"":\""datetime\""},{\""name\"":\""Computer\"",\""type\"":\""string\""},{\""name\"":\""RawData\"",\""type\"":\""string\""},{\""name\"":\""IntColumn_d\"",\""type\"":\""real\""},{\""name\"":\""StringColumn_s\"",\""type\"":\""string\""},{\""name\"":\""BoolColumn_b\"",\""type\"":\""bool\""},{\""name\"":\""FloatColumn_d\"",\""type\"":\""real\""},{\""name\"":\""Type\"",\""type\"":\""string\""},{\""name\"":\""_ResourceId\"",\""type\"":\""string\""}],\""rows\"":[[\""e7bf7412-576d-4978-b47c-2edf669e3e2a\"",\""RestAPI\"",\""\"",\""\"",\""2021-05-31T00:00:00Z\"",\""\"",\""\"",1,\""a\"",false,0,\""TableA1_151_CL\"",\""\""],[\""e7bf7412-576d-4978-b47c-2edf669e3e2a\"",\""RestAPI\"",\""\"",\""\"",\""2021-06-02T00:00:00Z\"",\""\"",\""\"",3,\""b\"",true,1.20000005,\""TableA1_151_CL\"",\""\""],[\""e7bf7412-576d-4978-b47c-2edf669e3e2a\"",\""RestAPI\"",\""\"",\""\"",\""2021-06-05T00:00:00Z\"",\""\"",\""\"",1,\""c\"",false,1.10000002,\""TableA1_151_CL\"",\""\""]]}]}""
57+
}
58+
]
59+
}
60+
";
61+
var mockTransport = MockTransport.FromMessageCallback(message =>
62+
{
63+
var mockResponse = new MockResponse(200);
64+
mockResponse.SetContent(badResponse);
65+
return mockResponse;
66+
});
67+
68+
var client = new LogsQueryClient(new Uri("https://api.loganalytics.io"), new MockCredential(), new LogsQueryClientOptions()
69+
{
70+
Transport = mockTransport
71+
});
72+
73+
LogsBatchQuery batch = new LogsBatchQuery();
74+
batch.AddQuery("wid", "query", DateTimeRange.All);
75+
76+
LogsBatchQueryResult batchResult = await client.QueryBatchAsync(batch);
77+
Assert.NotNull(batchResult.GetResult("0"));
3878
}
3979
}
4080
}

sdk/monitor/Azure.Monitor.Query/tests/MetricsClientSamples.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ namespace Azure.Monitor.Query.Tests
1212
public class MetricsClientSamples: SamplesBase<MonitorQueryClientTestEnvironment>
1313
{
1414
[Test]
15+
[Ignore("https://github.com/Azure/azure-sdk-for-net/issues/21657")]
1516
public async Task QueryMetrics()
1617
{
1718
#region Snippet:QueryMetrics

sdk/monitor/Azure.Monitor.Query/tests/MetricsQueryClientLiveTests.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ private MetricsQueryClient CreateClient()
3131
[SetUp]
3232
public async Task SetUp()
3333
{
34-
_testData = new MetricsTestData(this);
34+
_testData = new MetricsTestData(TestEnvironment, Recording.UtcNow);
3535
await _testData.InitializeAsync();
3636
}
3737

0 commit comments

Comments
 (0)