Update analyzers for .NET 10 SDK (#2611)

This commit is contained in:
Stephen Toub
2025-12-10 10:34:56 +00:00
committed by GitHub
parent 2f0b2db12a
commit b01fd23cd2
41 changed files with 382 additions and 259 deletions
+4
View File
@@ -1,6 +1,10 @@
# Suppressing errors for Test projects under dotnet/tests folder
[*.cs]
dotnet_diagnostic.CA1822.severity = none # Member does not access instance data and can be marked as static
dotnet_diagnostic.CA1873.severity = none # Evaluation of logging arguments may be expensive
dotnet_diagnostic.CA1875.severity = none # Regex.IsMatch/Count instead of Regex.Match(...).Success/Regex.Matches(...).Count
dotnet_diagnostic.CA2007.severity = none # Do not directly await a Task
dotnet_diagnostic.CA2249.severity = none # Use `string.Contains` instead of `string.IndexOf` to improve readability
dotnet_diagnostic.CS1591.severity = none # Missing XML comment for publicly visible type or member
@@ -547,7 +547,7 @@ public sealed class A2AAgentTests : IDisposable
var result = await this._agent.RunAsync("Test message");
// Assert
if (taskState == TaskState.Submitted || taskState == TaskState.Working)
if (taskState is TaskState.Submitted or TaskState.Working)
{
Assert.NotNull(result.ContinuationToken);
}
@@ -64,12 +64,12 @@ public sealed class A2AArtifactExtensionsTests
{
ArtifactId = "artifact-ai-multi",
Name = "test",
Parts = new List<Part>
{
Parts =
[
new TextPart { Text = "Part 1" },
new TextPart { Text = "Part 2" },
new TextPart { Text = "Part 3" }
},
],
Metadata = null
};
@@ -93,7 +93,7 @@ public sealed class A2AArtifactExtensionsTests
{
ArtifactId = "artifact-empty",
Name = "test",
Parts = new List<Part>(),
Parts = [],
Metadata = null
};
@@ -919,7 +919,7 @@ public sealed class AGUIAgentTests
List<ChatMessage> messages = [new ChatMessage(ChatRole.User, "Test")];
// Act - First turn
List<ChatMessage> conversation = new(messages);
List<ChatMessage> conversation = [.. messages];
string? conversationId = null;
await foreach (var update in chatClient.GetStreamingResponseAsync(conversation, options))
{
@@ -2684,13 +2684,12 @@ public sealed class AzureAIProjectChatClientExtensionsTests
private sealed class MockPipelineResponse : PipelineResponse
{
private readonly int _status;
private readonly BinaryData _content;
private readonly MockPipelineResponseHeaders _headers;
public MockPipelineResponse(int status, BinaryData? content = null)
{
this._status = status;
this._content = content ?? BinaryData.Empty;
this.Content = content ?? BinaryData.Empty;
this._headers = new MockPipelineResponseHeaders();
}
@@ -2704,7 +2703,7 @@ public sealed class AzureAIProjectChatClientExtensionsTests
set { }
}
public override BinaryData Content => this._content;
public override BinaryData Content { get; }
protected override PipelineResponseHeaders HeadersCore => this._headers;
@@ -8,7 +8,6 @@ using System.Text.Json.Serialization.Metadata;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Identity;
using Microsoft.Agents.AI;
using Microsoft.Azure.Cosmos;
using Microsoft.Extensions.AI;
using Xunit;
@@ -81,7 +80,7 @@ public sealed class CosmosChatMessageStoreTests : IAsyncLifetime, IDisposable
throughput: 400);
// Create container for hierarchical partitioning tests with hierarchical partition key
var hierarchicalContainerProperties = new ContainerProperties(HierarchicalTestContainerId, new List<string> { "/tenantId", "/userId", "/sessionId" });
var hierarchicalContainerProperties = new ContainerProperties(HierarchicalTestContainerId, ["/tenantId", "/userId", "/sessionId"]);
await databaseResponse.Database.CreateContainerIfNotExistsAsync(
hierarchicalContainerProperties,
throughput: 400);
@@ -247,7 +246,7 @@ public sealed class CosmosChatMessageStoreTests : IAsyncLifetime, IDisposable
PartitionKey = new PartitionKey(conversationId)
});
List<dynamic> rawResults = new();
List<dynamic> rawResults = [];
while (rawIterator.HasMoreResults)
{
var rawResponse = await rawIterator.ReadNextAsync();
@@ -77,7 +77,7 @@ public class CosmosCheckpointStoreTests : IAsyncLifetime, IDisposable
this._emulatorAvailable = true;
}
catch (Exception ex) when (!(ex is OutOfMemoryException || ex is StackOverflowException || ex is AccessViolationException))
catch (Exception ex) when (ex is not (OutOfMemoryException or StackOverflowException or AccessViolationException))
{
// Emulator not available, tests will be skipped
this._emulatorAvailable = false;
@@ -100,9 +100,6 @@ public sealed class AGUIServerSentEventsResultTests
// Act
await result.ExecuteAsync(httpContext);
// Assert
Assert.Equal(StatusCodes.Status200OK, result.StatusCode);
}
[Fact]
@@ -49,14 +49,14 @@ public sealed class Mem0ProviderTests : IDisposable
var sut = new Mem0Provider(this._httpClient, storageScope);
await sut.ClearStoredMemoriesAsync();
var ctxBefore = await sut.InvokingAsync(new AIContextProvider.InvokingContext(new[] { question }));
var ctxBefore = await sut.InvokingAsync(new AIContextProvider.InvokingContext([question]));
Assert.DoesNotContain("Caoimhe", ctxBefore.Messages?[0].Text ?? string.Empty);
// Act
await sut.InvokedAsync(new AIContextProvider.InvokedContext(new[] { input }, aiContextProviderMessages: null));
await sut.InvokedAsync(new AIContextProvider.InvokedContext([input], aiContextProviderMessages: null));
var ctxAfterAdding = await GetContextWithRetryAsync(sut, question);
await sut.ClearStoredMemoriesAsync();
var ctxAfterClearing = await sut.InvokingAsync(new AIContextProvider.InvokingContext(new[] { question }));
var ctxAfterClearing = await sut.InvokingAsync(new AIContextProvider.InvokingContext([question]));
// Assert
Assert.Contains("Caoimhe", ctxAfterAdding.Messages?[0].Text ?? string.Empty);
@@ -73,14 +73,14 @@ public sealed class Mem0ProviderTests : IDisposable
var sut = new Mem0Provider(this._httpClient, storageScope);
await sut.ClearStoredMemoriesAsync();
var ctxBefore = await sut.InvokingAsync(new AIContextProvider.InvokingContext(new[] { question }));
var ctxBefore = await sut.InvokingAsync(new AIContextProvider.InvokingContext([question]));
Assert.DoesNotContain("Caoimhe", ctxBefore.Messages?[0].Text ?? string.Empty);
// Act
await sut.InvokedAsync(new AIContextProvider.InvokedContext(new[] { assistantIntro }, aiContextProviderMessages: null));
await sut.InvokedAsync(new AIContextProvider.InvokedContext([assistantIntro], aiContextProviderMessages: null));
var ctxAfterAdding = await GetContextWithRetryAsync(sut, question);
await sut.ClearStoredMemoriesAsync();
var ctxAfterClearing = await sut.InvokingAsync(new AIContextProvider.InvokingContext(new[] { question }));
var ctxAfterClearing = await sut.InvokingAsync(new AIContextProvider.InvokingContext([question]));
// Assert
Assert.Contains("Caoimhe", ctxAfterAdding.Messages?[0].Text ?? string.Empty);
@@ -99,13 +99,13 @@ public sealed class Mem0ProviderTests : IDisposable
await sut1.ClearStoredMemoriesAsync();
await sut2.ClearStoredMemoriesAsync();
var ctxBefore1 = await sut1.InvokingAsync(new AIContextProvider.InvokingContext(new[] { question }));
var ctxBefore2 = await sut2.InvokingAsync(new AIContextProvider.InvokingContext(new[] { question }));
var ctxBefore1 = await sut1.InvokingAsync(new AIContextProvider.InvokingContext([question]));
var ctxBefore2 = await sut2.InvokingAsync(new AIContextProvider.InvokingContext([question]));
Assert.DoesNotContain("Caoimhe", ctxBefore1.Messages?[0].Text ?? string.Empty);
Assert.DoesNotContain("Caoimhe", ctxBefore2.Messages?[0].Text ?? string.Empty);
// Act
await sut1.InvokedAsync(new AIContextProvider.InvokedContext(new[] { assistantIntro }, aiContextProviderMessages: null));
await sut1.InvokedAsync(new AIContextProvider.InvokedContext([assistantIntro], aiContextProviderMessages: null));
var ctxAfterAdding1 = await GetContextWithRetryAsync(sut1, question);
var ctxAfterAdding2 = await GetContextWithRetryAsync(sut2, question);
@@ -123,7 +123,7 @@ public sealed class Mem0ProviderTests : IDisposable
AIContext? ctx = null;
for (int i = 0; i < attempts; i++)
{
ctx = await provider.InvokingAsync(new AIContextProvider.InvokingContext(new[] { question }), CancellationToken.None);
ctx = await provider.InvokingAsync(new AIContextProvider.InvokingContext([question]), CancellationToken.None);
var text = ctx.Messages?[0].Text;
if (!string.IsNullOrEmpty(text) && text.IndexOf("Caoimhe", StringComparison.OrdinalIgnoreCase) >= 0)
{
@@ -35,6 +35,10 @@ public sealed class Mem0ProviderTests : IDisposable
.Setup(f => f.CreateLogger(typeof(Mem0Provider).FullName!))
.Returns(this._loggerMock.Object);
this._loggerMock
.Setup(f => f.IsEnabled(It.IsAny<LogLevel>()))
.Returns(true);
this._httpClient = new HttpClient(this._handler)
{
BaseAddress = new Uri("https://localhost/")
@@ -131,10 +135,10 @@ public sealed class Mem0ProviderTests : IDisposable
}
[Theory]
[InlineData(false, false, 2)]
[InlineData(true, false, 2)]
[InlineData(false, true, 1)]
[InlineData(true, true, 1)]
[InlineData(false, false, 4)]
[InlineData(true, false, 4)]
[InlineData(false, true, 2)]
[InlineData(true, true, 2)]
public async Task InvokingAsync_LogsUserIdBasedOnEnableSensitiveTelemetryDataAsync(bool enableSensitiveTelemetryData, bool requestThrows, int expectedLogInvocations)
{
// Arrange
@@ -157,7 +161,7 @@ public sealed class Mem0ProviderTests : IDisposable
var options = new Mem0ProviderOptions { EnableSensitiveTelemetryData = enableSensitiveTelemetryData };
var sut = new Mem0Provider(this._httpClient, storageScope, options: options, loggerFactory: this._loggerFactoryMock.Object);
var invokingContext = new AIContextProvider.InvokingContext(new[] { new ChatMessage(ChatRole.User, "Who am I?") });
var invokingContext = new AIContextProvider.InvokingContext([new ChatMessage(ChatRole.User, "Who am I?")]);
// Act
await sut.InvokingAsync(invokingContext, CancellationToken.None);
@@ -166,7 +170,12 @@ public sealed class Mem0ProviderTests : IDisposable
Assert.Equal(expectedLogInvocations, this._loggerMock.Invocations.Count);
foreach (var logInvocation in this._loggerMock.Invocations)
{
var state = Assert.IsAssignableFrom<IReadOnlyList<KeyValuePair<string, object?>>>(logInvocation.Arguments[2]);
if (logInvocation.Method.Name == nameof(ILogger.IsEnabled))
{
continue;
}
var state = Assert.IsType<IReadOnlyList<KeyValuePair<string, object?>>>(logInvocation.Arguments[2], exactMatch: false);
var userIdValue = state.First(kvp => kvp.Key == "UserId").Value;
Assert.Equal(enableSensitiveTelemetryData ? "user" : "<redacted>", userIdValue);
@@ -275,8 +284,8 @@ public sealed class Mem0ProviderTests : IDisposable
[Theory]
[InlineData(false, false, 0)]
[InlineData(true, false, 0)]
[InlineData(false, true, 1)]
[InlineData(true, true, 1)]
[InlineData(false, true, 2)]
[InlineData(true, true, 2)]
public async Task InvokedAsync_LogsUserIdBasedOnEnableSensitiveTelemetryDataAsync(bool enableSensitiveTelemetryData, bool requestThrows, int expectedLogCount)
{
// Arrange
@@ -315,7 +324,12 @@ public sealed class Mem0ProviderTests : IDisposable
Assert.Equal(expectedLogCount, this._loggerMock.Invocations.Count);
foreach (var logInvocation in this._loggerMock.Invocations)
{
var state = Assert.IsAssignableFrom<IReadOnlyList<KeyValuePair<string, object?>>>(logInvocation.Arguments[2]);
if (logInvocation.Method.Name == nameof(ILogger.IsEnabled))
{
continue;
}
var state = Assert.IsType<IReadOnlyList<KeyValuePair<string, object?>>>(logInvocation.Arguments[2], exactMatch: false);
var userIdValue = state.First(kvp => kvp.Key == "UserId").Value;
Assert.Equal(enableSensitiveTelemetryData ? "user" : "<redacted>", userIdValue);
}
@@ -386,7 +400,7 @@ public sealed class Mem0ProviderTests : IDisposable
// Arrange
var storageScope = new Mem0ProviderScope { ApplicationId = "app" };
var provider = new Mem0Provider(this._httpClient, storageScope, loggerFactory: this._loggerFactoryMock.Object);
var invokingContext = new AIContextProvider.InvokingContext(new[] { new ChatMessage(ChatRole.User, "Q?") });
var invokingContext = new AIContextProvider.InvokingContext([new ChatMessage(ChatRole.User, "Q?")]);
// Act
var aiContext = await provider.InvokingAsync(invokingContext, CancellationToken.None);
@@ -1,7 +1,6 @@
// Copyright (c) Microsoft. All rights reserved.
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Text;
@@ -50,10 +49,10 @@ public sealed class PurviewClientTests : IDisposable
{
Id = "test-id-123",
ProtectionScopeState = ProtectionScopeState.NotModified,
PolicyActions = new List<DlpActionInfo>
{
PolicyActions =
[
new() { Action = DlpAction.NotifyUser }
}
]
};
this._handler.StatusCodeToReturn = HttpStatusCode.OK;
@@ -228,8 +227,8 @@ public sealed class PurviewClientTests : IDisposable
var expectedResponse = new ProtectionScopesResponse
{
Scopes = new List<PolicyScopeBase>
{
Scopes =
[
new()
{
Activities = ProtectionScopeActivities.UploadText,
@@ -238,7 +237,7 @@ public sealed class PurviewClientTests : IDisposable
new ("microsoft.graph.policyLocationApplication", "app-123")
]
}
}
]
};
this._handler.StatusCodeToReturn = HttpStatusCode.OK;
@@ -264,7 +263,7 @@ public sealed class PurviewClientTests : IDisposable
{
// Arrange
var request = new ProtectionScopesRequest("test-user-id", "test-tenant-id");
var expectedResponse = new ProtectionScopesResponse { Scopes = new List<PolicyScopeBase>() };
var expectedResponse = new ProtectionScopesResponse { Scopes = [] };
this._handler.StatusCodeToReturn = HttpStatusCode.OK;
this._handler.ResponseToReturn = JsonSerializer.Serialize(expectedResponse, PurviewSerializationUtils.SerializationSettings.GetTypeInfo(typeof(ProtectionScopesResponse)));
@@ -56,8 +56,8 @@ public sealed class ScopedContentProcessorTests
var psResponse = new ProtectionScopesResponse
{
Scopes = new List<PolicyScopeBase>
{
Scopes =
[
new()
{
Activities = ProtectionScopeActivities.UploadText,
@@ -67,7 +67,7 @@ public sealed class ScopedContentProcessorTests
],
ExecutionMode = ExecutionMode.EvaluateInline
}
}
]
};
this._mockPurviewClient.Setup(x => x.GetProtectionScopesAsync(
@@ -76,10 +76,10 @@ public sealed class ScopedContentProcessorTests
var pcResponse = new ProcessContentResponse
{
PolicyActions = new List<DlpActionInfo>
{
PolicyActions =
[
new() { Action = DlpAction.BlockAccess }
}
]
};
this._mockPurviewClient.Setup(x => x.ProcessContentAsync(
@@ -115,8 +115,8 @@ public sealed class ScopedContentProcessorTests
var psResponse = new ProtectionScopesResponse
{
Scopes = new List<PolicyScopeBase>
{
Scopes =
[
new()
{
Activities = ProtectionScopeActivities.UploadText,
@@ -126,7 +126,7 @@ public sealed class ScopedContentProcessorTests
],
ExecutionMode = ExecutionMode.EvaluateInline
}
}
]
};
this._mockPurviewClient.Setup(x => x.GetProtectionScopesAsync(
@@ -135,10 +135,10 @@ public sealed class ScopedContentProcessorTests
var pcResponse = new ProcessContentResponse
{
PolicyActions = new List<DlpActionInfo>
{
PolicyActions =
[
new() { RestrictionAction = RestrictionAction.Block }
}
]
};
this._mockPurviewClient.Setup(x => x.ProcessContentAsync(
@@ -174,8 +174,8 @@ public sealed class ScopedContentProcessorTests
var psResponse = new ProtectionScopesResponse
{
Scopes = new List<PolicyScopeBase>
{
Scopes =
[
new()
{
Activities = ProtectionScopeActivities.UploadText,
@@ -185,7 +185,7 @@ public sealed class ScopedContentProcessorTests
],
ExecutionMode = ExecutionMode.EvaluateInline
}
}
]
};
this._mockPurviewClient.Setup(x => x.GetProtectionScopesAsync(
@@ -194,10 +194,10 @@ public sealed class ScopedContentProcessorTests
var pcResponse = new ProcessContentResponse
{
PolicyActions = new List<DlpActionInfo>
{
PolicyActions =
[
new() { Action = DlpAction.NotifyUser }
}
]
};
this._mockPurviewClient.Setup(x => x.ProcessContentAsync(
@@ -229,8 +229,8 @@ public sealed class ScopedContentProcessorTests
var cachedPsResponse = new ProtectionScopesResponse
{
Scopes = new List<PolicyScopeBase>
{
Scopes =
[
new()
{
Activities = ProtectionScopeActivities.UploadText,
@@ -240,7 +240,7 @@ public sealed class ScopedContentProcessorTests
],
ExecutionMode = ExecutionMode.EvaluateInline
}
}
]
};
this._mockCacheProvider.Setup(x => x.GetAsync<ProtectionScopesCacheKey, ProtectionScopesResponse>(
@@ -249,7 +249,7 @@ public sealed class ScopedContentProcessorTests
var pcResponse = new ProcessContentResponse
{
PolicyActions = new List<DlpActionInfo>()
PolicyActions = []
};
this._mockPurviewClient.Setup(x => x.ProcessContentAsync(
@@ -285,8 +285,8 @@ public sealed class ScopedContentProcessorTests
var psResponse = new ProtectionScopesResponse
{
Scopes = new List<PolicyScopeBase>
{
Scopes =
[
new()
{
Activities = ProtectionScopeActivities.UploadText,
@@ -296,7 +296,7 @@ public sealed class ScopedContentProcessorTests
],
ExecutionMode = ExecutionMode.EvaluateInline
}
}
]
};
this._mockPurviewClient.Setup(x => x.GetProtectionScopesAsync(
@@ -306,7 +306,7 @@ public sealed class ScopedContentProcessorTests
var pcResponse = new ProcessContentResponse
{
ProtectionScopeState = ProtectionScopeState.Modified,
PolicyActions = new List<DlpActionInfo>()
PolicyActions = []
};
this._mockPurviewClient.Setup(x => x.ProcessContentAsync(
@@ -342,8 +342,8 @@ public sealed class ScopedContentProcessorTests
var psResponse = new ProtectionScopesResponse
{
Scopes = new List<PolicyScopeBase>
{
Scopes =
[
new()
{
Activities = ProtectionScopeActivities.UploadText,
@@ -352,7 +352,7 @@ public sealed class ScopedContentProcessorTests
new ("microsoft.graph.policyLocationApplication", "app-456")
]
}
}
]
};
this._mockPurviewClient.Setup(x => x.GetProtectionScopesAsync(
@@ -436,7 +436,7 @@ public sealed class ScopedContentProcessorTests
It.IsAny<ProtectionScopesCacheKey>(), It.IsAny<CancellationToken>()))
.ReturnsAsync((ProtectionScopesResponse?)null);
var psResponse = new ProtectionScopesResponse { Scopes = new List<PolicyScopeBase>() };
var psResponse = new ProtectionScopesResponse { Scopes = [] };
this._mockPurviewClient.Setup(x => x.GetProtectionScopesAsync(
It.IsAny<ProtectionScopesRequest>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(psResponse);
@@ -471,7 +471,7 @@ public sealed class ScopedContentProcessorTests
It.IsAny<ProtectionScopesCacheKey>(), It.IsAny<CancellationToken>()))
.ReturnsAsync((ProtectionScopesResponse?)null);
var psResponse = new ProtectionScopesResponse { Scopes = new List<PolicyScopeBase>() };
var psResponse = new ProtectionScopesResponse { Scopes = [] };
this._mockPurviewClient.Setup(x => x.GetProtectionScopesAsync(
It.IsAny<ProtectionScopesRequest>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(psResponse);
@@ -30,6 +30,10 @@ public sealed class TextSearchProviderTests
this._loggerFactoryMock
.Setup(f => f.CreateLogger(typeof(TextSearchProvider).FullName!))
.Returns(this._loggerMock.Object);
this._loggerMock
.Setup(f => f.IsEnabled(It.IsAny<LogLevel>()))
.Returns(true);
}
[Theory]
@@ -135,7 +139,7 @@ public sealed class TextSearchProviderTests
FunctionToolDescription = overrideDescription
};
var provider = new TextSearchProvider(this.NoResultSearchAsync, default, null, options);
var invokingContext = new AIContextProvider.InvokingContext(new[] { new ChatMessage(ChatRole.User, "Q?") });
var invokingContext = new AIContextProvider.InvokingContext([new ChatMessage(ChatRole.User, "Q?")]);
// Act
var aiContext = await provider.InvokingAsync(invokingContext, CancellationToken.None);
@@ -154,7 +158,7 @@ public sealed class TextSearchProviderTests
{
// Arrange
var provider = new TextSearchProvider(this.FailingSearchAsync, default, null, loggerFactory: this._loggerFactoryMock.Object);
var invokingContext = new AIContextProvider.InvokingContext(new[] { new ChatMessage(ChatRole.User, "Q?") });
var invokingContext = new AIContextProvider.InvokingContext([new ChatMessage(ChatRole.User, "Q?")]);
// Act
var aiContext = await provider.InvokingAsync(invokingContext, CancellationToken.None);
@@ -247,7 +251,7 @@ public sealed class TextSearchProviderTests
ContextFormatter = r => $"Custom formatted context with {r.Count} results."
};
var provider = new TextSearchProvider(SearchDelegateAsync, default, null, options);
var invokingContext = new AIContextProvider.InvokingContext(new[] { new ChatMessage(ChatRole.User, "Q?") });
var invokingContext = new AIContextProvider.InvokingContext([new ChatMessage(ChatRole.User, "Q?")]);
// Act
var aiContext = await provider.InvokingAsync(invokingContext, CancellationToken.None);
@@ -281,7 +285,7 @@ public sealed class TextSearchProviderTests
ContextFormatter = r => string.Join(",", r.Select(x => ((RawPayload)x.RawRepresentation!).Id))
};
var provider = new TextSearchProvider(SearchDelegateAsync, default, null, options);
var invokingContext = new AIContextProvider.InvokingContext(new[] { new ChatMessage(ChatRole.User, "Q?") });
var invokingContext = new AIContextProvider.InvokingContext([new ChatMessage(ChatRole.User, "Q?")]);
// Act
var aiContext = await provider.InvokingAsync(invokingContext, CancellationToken.None);
@@ -298,7 +302,7 @@ public sealed class TextSearchProviderTests
// Arrange
var options = new TextSearchProviderOptions { SearchTime = TextSearchProviderOptions.TextSearchBehavior.BeforeAIInvoke };
var provider = new TextSearchProvider(this.NoResultSearchAsync, default, null, options);
var invokingContext = new AIContextProvider.InvokingContext(new[] { new ChatMessage(ChatRole.User, "Q?") });
var invokingContext = new AIContextProvider.InvokingContext([new ChatMessage(ChatRole.User, "Q?")]);
// Act
var aiContext = await provider.InvokingAsync(invokingContext, CancellationToken.None);
@@ -338,10 +342,10 @@ public sealed class TextSearchProviderTests
};
await provider.InvokedAsync(new(initialMessages, aiContextProviderMessages: null) { InvokeException = new InvalidOperationException("Request Failed") });
var invokingContext = new AIContextProvider.InvokingContext(new[]
{
var invokingContext = new AIContextProvider.InvokingContext(
[
new ChatMessage(ChatRole.User, "E")
});
]);
// Act
await provider.InvokingAsync(invokingContext, CancellationToken.None);
@@ -378,10 +382,10 @@ public sealed class TextSearchProviderTests
};
await provider.InvokedAsync(new(initialMessages, aiContextProviderMessages: null));
var invokingContext = new AIContextProvider.InvokingContext(new[]
{
var invokingContext = new AIContextProvider.InvokingContext(
[
new ChatMessage(ChatRole.User, "E")
});
]);
// Act
await provider.InvokingAsync(invokingContext, CancellationToken.None);
@@ -409,21 +413,21 @@ public sealed class TextSearchProviderTests
var provider = new TextSearchProvider(SearchDelegateAsync, default, null, options);
// First memory update (A,B)
await provider.InvokedAsync(new(new[]
{
await provider.InvokedAsync(new(
[
new ChatMessage(ChatRole.User, "A"),
new ChatMessage(ChatRole.Assistant, "B"),
}, aiContextProviderMessages: null));
], aiContextProviderMessages: null));
// Second memory update (C,D,E)
await provider.InvokedAsync(new(new[]
{
await provider.InvokedAsync(new(
[
new ChatMessage(ChatRole.User, "C"),
new ChatMessage(ChatRole.Assistant, "D"),
new ChatMessage(ChatRole.User, "E"),
}, aiContextProviderMessages: null));
], aiContextProviderMessages: null));
var invokingContext = new AIContextProvider.InvokingContext(new[] { new ChatMessage(ChatRole.User, "F") });
var invokingContext = new AIContextProvider.InvokingContext([new ChatMessage(ChatRole.User, "F")]);
// Act
await provider.InvokingAsync(invokingContext, CancellationToken.None);
@@ -460,10 +464,10 @@ public sealed class TextSearchProviderTests
};
await provider.InvokedAsync(new(initialMessages, null));
var invokingContext = new AIContextProvider.InvokingContext(new[]
{
var invokingContext = new AIContextProvider.InvokingContext(
[
new ChatMessage(ChatRole.User, "Question?") // Current request message always appended.
});
]);
// Act
await provider.InvokingAsync(invokingContext, CancellationToken.None);
@@ -36,6 +36,10 @@ public class ChatHistoryMemoryProviderTests
.Setup(f => f.CreateLogger(typeof(ChatHistoryMemoryProvider).FullName!))
.Returns(this._loggerMock.Object);
this._loggerMock
.Setup(f => f.IsEnabled(It.IsAny<LogLevel>()))
.Returns(true);
this._vectorStoreCollectionMock = new(MockBehavior.Strict);
this._vectorStoreMock = new(MockBehavior.Strict);
@@ -218,8 +222,8 @@ public class ChatHistoryMemoryProviderTests
[Theory]
[InlineData(false, false, 0)]
[InlineData(true, false, 0)]
[InlineData(false, true, 1)]
[InlineData(true, true, 1)]
[InlineData(false, true, 2)]
[InlineData(true, true, 2)]
public async Task InvokedAsync_LogsUserIdBasedOnEnableSensitiveTelemetryDataAsync(bool enableSensitiveTelemetryData, bool requestThrows, int expectedLogInvocations)
{
// Arrange
@@ -259,6 +263,11 @@ public class ChatHistoryMemoryProviderTests
Assert.Equal(expectedLogInvocations, this._loggerMock.Invocations.Count);
foreach (var logInvocation in this._loggerMock.Invocations)
{
if (logInvocation.Method.Name == nameof(ILogger.IsEnabled))
{
continue;
}
var state = Assert.IsType<IReadOnlyList<KeyValuePair<string, object?>>>(logInvocation.Arguments[2], exactMatch: false);
var userIdValue = state.First(kvp => kvp.Key == "UserId").Value;
Assert.Equal(enableSensitiveTelemetryData ? "user1" : "<redacted>", userIdValue);
@@ -385,10 +394,10 @@ public class ChatHistoryMemoryProviderTests
}
[Theory]
[InlineData(false, false, 1)]
[InlineData(true, false, 1)]
[InlineData(false, true, 1)]
[InlineData(true, true, 1)]
[InlineData(false, false, 2)]
[InlineData(true, false, 2)]
[InlineData(false, true, 2)]
[InlineData(true, true, 2)]
public async Task InvokingAsync_LogsUserIdBasedOnEnableSensitiveTelemetryDataAsync(bool enableSensitiveTelemetryData, bool requestThrows, int expectedLogInvocations)
{
// Arrange
@@ -442,7 +451,12 @@ public class ChatHistoryMemoryProviderTests
Assert.Equal(expectedLogInvocations, this._loggerMock.Invocations.Count);
foreach (var logInvocation in this._loggerMock.Invocations)
{
var state = Assert.IsAssignableFrom<IReadOnlyList<KeyValuePair<string, object?>>>(logInvocation.Arguments[2]);
if (logInvocation.Method.Name == nameof(ILogger.IsEnabled))
{
continue;
}
var state = Assert.IsType<IReadOnlyList<KeyValuePair<string, object?>>>(logInvocation.Arguments[2], exactMatch: false);
var userIdValue = state.First(kvp => kvp.Key == "UserId").Value;
Assert.Equal(enableSensitiveTelemetryData ? "user1" : "<redacted>", userIdValue);
@@ -57,7 +57,7 @@ internal class TestEchoAgent(string? id = null, string? name = null, string? pre
protected virtual IEnumerable<ChatMessage> GetEpilogueMessages(AgentRunOptions? options = null)
{
return Enumerable.Empty<ChatMessage>();
return [];
}
public override Task<AgentRunResponse> RunAsync(IEnumerable<ChatMessage> messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default)