Files
agent-framework/dotnet/tests/Microsoft.Extensions.AI.Agents.Abstractions.UnitTests/InMemoryAgentThreadTests.cs
T
Stephen Toub 03ef7f054f .NET: Add AgentWorkflowBuilder group chat (#861)
* Add AgentWorkflowBuilder group chat

And fix a variety of issues along the way:
- Use DateTime{Offset}.UtcNow rather than Now
- AIAgentHostExecutor shouldn't be publishing empty messages
- Sequential workflows should be flowing all history and not just the output from the previous agent as the input into the next agent
- Renamed some of the new agent workflow methods... still not super happy with the shape, though
- Simplified handoffs builder, e.g. using a hashset with a custom comparer instead of a dictionary
- Improved multi-service use by trying to change assistant->user role for messages created by other agents
- Changed MessageMerger to rely on M.E.AI's coalescing more and to avoid empty contents / text
- Ensured that messages from ChatClientAgent include MessageId and CreatedAt timestamps
- Avoided including instructions for agents in a handoff workflow that don't have any handoffs
- Removed the unnecessary end function in handoffs
- Improved naming of executors to include agent name for debuggability
- Use "N" formatting with Guid.ToString everywhere, to avoid the unnecessary extra dash character which is also not valid in various places (like function tool names)
- Replace `params T[]` with `params IEnumerable<T>` to make public APIs more flexible in what they consume

* Address feedback

- Fix unintentional provider change in sample
2025-09-24 16:38:34 +00:00

155 lines
4.9 KiB
C#

// Copyright (c) Microsoft. All rights reserved.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
namespace Microsoft.Extensions.AI.Agents.Abstractions.UnitTests;
/// <summary>
/// Contains tests for <see cref="InMemoryAgentThread"/>.
/// </summary>
public class InMemoryAgentThreadTests
{
#region Constructor and Property Tests
[Fact]
public void Constructor_SetsDefaultMessageStore()
{
// Arrange & Act
var thread = new TestInMemoryAgentThread();
// Assert
Assert.NotNull(thread.GetMessageStore());
Assert.Empty(thread.GetMessageStore());
}
[Fact]
public void Constructor_WithMessageStore_SetsProperty()
{
// Arrange
InMemoryChatMessageStore store = [new(ChatRole.User, "Hello")];
// Act
var thread = new TestInMemoryAgentThread(store);
// Assert
Assert.Same(store, thread.GetMessageStore());
Assert.Single(thread.GetMessageStore());
Assert.Equal("Hello", thread.GetMessageStore()[0].Text);
}
[Fact]
public void Constructor_WithMessages_SetsProperty()
{
// Arrange
var messages = new List<ChatMessage> { new(ChatRole.User, "Hi") };
// Act
var thread = new TestInMemoryAgentThread(messages);
// Assert
Assert.NotNull(thread.GetMessageStore());
Assert.Single(thread.GetMessageStore());
Assert.Equal("Hi", thread.GetMessageStore()[0].Text);
}
[Fact]
public async Task Constructor_WithSerializedState_SetsPropertyAsync()
{
// Arrange
InMemoryChatMessageStore store = [new(ChatRole.User, "TestMsg")];
var storeState = await store.SerializeStateAsync();
var json = JsonSerializer.SerializeToElement(new { storeState });
// Act
var thread = new TestInMemoryAgentThread(json);
// Assert
Assert.NotNull(thread.GetMessageStore());
Assert.Single(thread.GetMessageStore());
Assert.Equal("TestMsg", thread.GetMessageStore()[0].Text);
}
[Fact]
public void Constructor_WithInvalidJson_ThrowsArgumentException()
{
// Arrange
var invalidJson = JsonSerializer.SerializeToElement(42);
// Act & Assert
Assert.Throws<ArgumentException>(() => new TestInMemoryAgentThread(invalidJson));
}
#endregion
#region SerializeAsync Tests
[Fact]
public async Task SerializeAsync_ReturnsCorrectJson_WhenMessagesExistAsync()
{
// Arrange
var thread = new TestInMemoryAgentThread([new(ChatRole.User, "TestContent")]);
// Act
var json = await thread.SerializeAsync();
// Assert
Assert.Equal(JsonValueKind.Object, json.ValueKind);
Assert.True(json.TryGetProperty("storeState", out var storeStateProperty));
Assert.Equal(JsonValueKind.Object, storeStateProperty.ValueKind);
Assert.True(storeStateProperty.TryGetProperty("messages", out var messagesProperty));
Assert.Equal(JsonValueKind.Array, messagesProperty.ValueKind);
var messagesList = messagesProperty.EnumerateArray().ToList();
Assert.Single(messagesList);
}
[Fact]
public async Task SerializeAsync_ReturnsEmptyMessages_WhenNoMessagesAsync()
{
// Arrange
var thread = new TestInMemoryAgentThread();
// Act
var json = await thread.SerializeAsync();
// Assert
Assert.Equal(JsonValueKind.Object, json.ValueKind);
Assert.True(json.TryGetProperty("storeState", out var storeStateProperty));
Assert.Equal(JsonValueKind.Object, storeStateProperty.ValueKind);
Assert.True(storeStateProperty.TryGetProperty("messages", out var messagesProperty));
Assert.Equal(JsonValueKind.Array, messagesProperty.ValueKind);
Assert.Empty(messagesProperty.EnumerateArray());
}
#endregion
#region GetService Tests
[Fact]
public void GetService_RequestingChatMessageStore_ReturnsChatMessageStore()
{
// Arrange
var thread = new TestInMemoryAgentThread();
// Act & Assert
Assert.NotNull(thread.GetService(typeof(ChatMessageStore)));
Assert.Same(thread.GetMessageStore(), thread.GetService(typeof(ChatMessageStore)));
Assert.Same(thread.GetMessageStore(), thread.GetService(typeof(InMemoryChatMessageStore)));
}
#endregion
// Sealed test subclass to expose protected members for testing
private sealed class TestInMemoryAgentThread : InMemoryAgentThread
{
public TestInMemoryAgentThread() { }
public TestInMemoryAgentThread(InMemoryChatMessageStore? store) : base(store) { }
public TestInMemoryAgentThread(IEnumerable<ChatMessage> messages) : base(messages) { }
public TestInMemoryAgentThread(JsonElement serializedThreadState) : base(serializedThreadState) { }
public InMemoryChatMessageStore GetMessageStore() => this.MessageStore;
}
}