Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: add unit tests for dotnet and improve test infrastructure #5269

Merged
merged 9 commits into from
Jan 30, 2025
108 changes: 52 additions & 56 deletions dotnet/test/Microsoft.AutoGen.Core.Tests/AgentTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,49 +7,71 @@

namespace Microsoft.AutoGen.Core.Tests;

//[Collection(ClusterFixtureCollection.Name)]
public class AgentTests()
{
[Fact]
public async Task Agent_ShouldNotReceiveMessages_WhenNotSubscribed()
public async Task AgentShouldNotReceiveMessagesWhenNotSubscribedTest()
{
var runtime = new InProcessRuntime();
await runtime.StartAsync();

Logger<BaseAgent> logger = new(new LoggerFactory());
await runtime.RegisterAgentFactoryAsync("MyAgent", (id, runtime) => ValueTask.FromResult(new TestAgent(id, runtime, logger)));
await runtime.RegisterImplicitAgentSubscriptionsAsync<TestAgent>("MyAgent");
TestAgent agent = null!;

var topicType = "TestTopic";
await runtime.RegisterAgentFactoryAsync("MyAgent", (id, runtime) =>
{
agent = new TestAgent(id, runtime, logger);
return ValueTask.FromResult(agent);
});

// Ensure the agent is actually created
AgentId agentId = await runtime.GetAgentAsync("MyAgent", lazy: false);

await runtime.PublishMessageAsync(new TextMessage { Source = topicType, Content = "test" }, new TopicId("TestTopic")).ConfigureAwait(true);
// Validate agent ID
agentId.Should().Be(agent.Id, "Agent ID should match the registered agent");

var topicType = "TestTopic";

await runtime.PublishMessageAsync(new TextMessage { Source = topicType, Content = "test" }, new TopicId(topicType)).ConfigureAwait(true);
await runtime.RunUntilIdleAsync();

TestAgent.ReceivedMessages.Any().Should().BeFalse("Agent should not receive messages when not subscribed.");
agent.ReceivedMessages.Any().Should().BeFalse("Agent should not receive messages when not subscribed.");
}

[Fact]
public async Task Agent_ShoulReceiveMessages_WhenSubscribed()
public async Task AgentShouldReceiveMessagesWhenSubscribedTest()
{
var runtime = new InProcessRuntime();
await runtime.StartAsync();

Logger<BaseAgent> logger = new(new LoggerFactory());
await runtime.RegisterAgentFactoryAsync("MyAgent", (id, runtime) => ValueTask.FromResult(new SubscribedAgent(id, runtime, logger)));
SubscribedAgent agent = null!;

await runtime.RegisterAgentFactoryAsync("MyAgent", (id, runtime) =>
{
agent = new SubscribedAgent(id, runtime, logger);
return ValueTask.FromResult(agent);
});

// Ensure the agent is actually created
AgentId agentId = await runtime.GetAgentAsync("MyAgent", lazy: false);

// Validate agent ID
agentId.Should().Be(agent.Id, "Agent ID should match the registered agent");

await runtime.RegisterImplicitAgentSubscriptionsAsync<SubscribedAgent>("MyAgent");

var topicType = "TestTopic";

await runtime.PublishMessageAsync(new TextMessage { Source = topicType, Content = "test" }, new TopicId("TestTopic")).ConfigureAwait(true);
await runtime.PublishMessageAsync(new TextMessage { Source = topicType, Content = "test" }, new TopicId(topicType)).ConfigureAwait(true);

await runtime.RunUntilIdleAsync();

TestAgent.ReceivedMessages.Any().Should().BeTrue("Agent should receive messages when subscribed.");
agent.ReceivedMessages.Any().Should().BeTrue("Agent should receive messages when subscribed.");
}

[Fact]
public async Task SendMessageAsync_ShouldReturnResponse()
public async Task SendMessageAsyncShouldReturnResponseTest()
{
// Arrange
var runtime = new InProcessRuntime();
Expand All @@ -72,43 +94,6 @@ public async Task SendMessageAsync_ShouldReturnResponse()
}
}

// / <summary>
// / Verify that if the agent is not initialized via AgentWorker, it should throw the correct exception.
// / </summary>
// / <returns>void</returns>
// [Fact]
// public async Task Agent_ShouldThrowException_WhenNotInitialized()
// {
// using var fixture = new InMemoryAgentRuntimeFixture();
// var agent = ActivatorUtilities.CreateInstance<TestAgent>(fixture.AppHost.Services);
// await Assert.ThrowsAsync<UninitializedAgentWorker.AgentInitalizedIncorrectlyException>(
// async () =>
// {
// await agent.AddSubscriptionAsync("TestEvent");
// }
// );
// }

// /// <summary>
// /// validate that the agent is initialized correctly with implicit subs
// /// </summary>
// /// <returns>void</returns>
// [Fact]
// public async Task Agent_ShouldInitializeCorrectly()
// {
// var fixture = new InMemoryAgentRuntimeFixture();
// var (runtime, agent) = fixture.Start();
// Assert.Equal(nameof(AgentRuntime), runtime.GetType().Name);
// var subscriptions = await agent.GetSubscriptionsAsync();
// Assert.Equal(2, subscriptions.Count);
// fixture.Stop();
// }
/// <summary>
/// Test AddSubscriptionAsync method
/// </summary>
/// <returns>void</returns>
///

public class ReceiverAgent(AgentId id,
IAgentRuntime runtime) : BaseAgent(id, runtime, "Receiver Agent", null),
IHandle<string>
Expand All @@ -123,7 +108,7 @@ public ValueTask HandleAsync(string item, MessageContext messageContext)
}

[Fact]
public async Task SubscribeAsync_UnsubscribeAsync_and_GetSubscriptionsTest()
public async Task SubscribeAsyncRemoveSubscriptionAsyncAndGetSubscriptionsTest()
{
var runtime = new InProcessRuntime();
await runtime.StartAsync();
Expand Down Expand Up @@ -161,6 +146,23 @@ await runtime.RegisterAgentFactoryAsync("MyAgent", (id, runtime) =>
Assert.True(agent.ReceivedItems.Count == 1);
}

// / <summary>
// / Verify that if the agent is not initialized via AgentWorker, it should throw the correct exception.
// / </summary>
// / <returns>void</returns>
// [Fact]
// public async Task Agent_ShouldThrowException_WhenNotInitialized()
// {
// using var fixture = new InMemoryAgentRuntimeFixture();
// var agent = ActivatorUtilities.CreateInstance<TestAgent>(fixture.AppHost.Services);
// await Assert.ThrowsAsync<UninitializedAgentWorker.AgentInitalizedIncorrectlyException>(
// async () =>
// {
// await agent.AddSubscriptionAsync("TestEvent");
// }
// );
// }

// /// <summary>
// /// Test StoreAsync and ReadAsync methods
// /// </summary>
Expand Down Expand Up @@ -248,10 +250,4 @@ await runtime.RegisterAgentFactoryAsync("MyAgent", (id, runtime) =>

// TestAgent.ReceivedMessages[nameof(DelegateMessageToTestAgentAsync)].Should().NotBeNull();
// }

// [CollectionDefinition(Name)]
// public sealed class ClusterFixtureCollection : ICollectionFixture<InMemoryAgentRuntimeFixture>
// {
// public const string Name = nameof(ClusterFixtureCollection);
// }
}
3 changes: 2 additions & 1 deletion dotnet/test/Microsoft.AutoGen.Core.Tests/TestAgent.cs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,8 @@ public ValueTask<string> HandleAsync(RpcTextMessage item, MessageContext message
/// Key: source
/// Value: message
/// </summary>
public static Dictionary<string, object> ReceivedMessages { get; private set; } = new();
private readonly Dictionary<string, object> _receivedMessages = new();
public Dictionary<string, object> ReceivedMessages => _receivedMessages;
}

[TypeSubscription("TestTopic")]
Expand Down
Loading