You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

InProcessRuntimeTests.cs 6.0 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  1. // Copyright (c) Microsoft Corporation. All rights reserved.
  2. // InProcessRuntimeTests.cs
  3. using System.Text.Json;
  4. using FluentAssertions;
  5. using Microsoft.AutoGen.Contracts;
  6. using Microsoft.Extensions.Logging;
  7. using Xunit;
  8. namespace Microsoft.AutoGen.Core.Tests;
  9. [Trait("Category", "UnitV2")]
  10. public class InProcessRuntimeTests()
  11. {
  12. // Agent will not deliver to self will success when runtime.DeliverToSelf is false (default)
  13. [Fact]
  14. public async Task RuntimeAgentPublishToSelfDefaultNoSendTest()
  15. {
  16. var runtime = new InProcessRuntime();
  17. await runtime.StartAsync();
  18. Logger<BaseAgent> logger = new(new LoggerFactory());
  19. SubscribedSelfPublishAgent agent = null!;
  20. await runtime.RegisterAgentFactoryAsync("MyAgent", (id, runtime) =>
  21. {
  22. agent = new SubscribedSelfPublishAgent(id, runtime, logger);
  23. return ValueTask.FromResult(agent);
  24. });
  25. // Ensure the agent is actually created
  26. AgentId agentId = await runtime.GetAgentAsync("MyAgent", lazy: false);
  27. // Validate agent ID
  28. agentId.Should().Be(agent.Id, "Agent ID should match the registered agent");
  29. await runtime.RegisterImplicitAgentSubscriptionsAsync<SubscribedSelfPublishAgent>("MyAgent");
  30. var topicType = "TestTopic";
  31. await runtime.PublishMessageAsync("SelfMessage", new TopicId(topicType)).ConfigureAwait(true);
  32. await runtime.RunUntilIdleAsync();
  33. // Agent has default messages and could not publish to self
  34. agent.Text.Source.Should().Be("DefaultTopic");
  35. agent.Text.Content.Should().Be("DefaultContent");
  36. }
  37. // Agent delivery to self will success when runtime.DeliverToSelf is true
  38. [Fact]
  39. public async Task RuntimeAgentPublishToSelfDeliverToSelfTrueTest()
  40. {
  41. var runtime = new InProcessRuntime();
  42. runtime.DeliverToSelf = true;
  43. await runtime.StartAsync();
  44. Logger<BaseAgent> logger = new(new LoggerFactory());
  45. SubscribedSelfPublishAgent agent = null!;
  46. await runtime.RegisterAgentFactoryAsync("MyAgent", (id, runtime) =>
  47. {
  48. agent = new SubscribedSelfPublishAgent(id, runtime, logger);
  49. return ValueTask.FromResult(agent);
  50. });
  51. // Ensure the agent is actually created
  52. AgentId agentId = await runtime.GetAgentAsync("MyAgent", lazy: false);
  53. // Validate agent ID
  54. agentId.Should().Be(agent.Id, "Agent ID should match the registered agent");
  55. await runtime.RegisterImplicitAgentSubscriptionsAsync<SubscribedSelfPublishAgent>("MyAgent");
  56. var topicType = "TestTopic";
  57. await runtime.PublishMessageAsync("SelfMessage", new TopicId(topicType)).ConfigureAwait(true);
  58. await runtime.RunUntilIdleAsync();
  59. // Agent sucessfully published to self
  60. agent.Text.Source.Should().Be("TestTopic");
  61. agent.Text.Content.Should().Be("SelfMessage");
  62. }
  63. [Fact]
  64. public async Task RuntimeShouldSaveLoadStateCorrectlyTest()
  65. {
  66. // Create a runtime and register an agent
  67. var runtime = new InProcessRuntime();
  68. await runtime.StartAsync();
  69. Logger<BaseAgent> logger = new(new LoggerFactory());
  70. SubscribedSaveLoadAgent agent = null!;
  71. await runtime.RegisterAgentFactoryAsync("MyAgent", (id, runtime) =>
  72. {
  73. agent = new SubscribedSaveLoadAgent(id, runtime, logger);
  74. return ValueTask.FromResult(agent);
  75. });
  76. // Get agent ID and instantiate agent by publishing
  77. AgentId agentId = await runtime.GetAgentAsync("MyAgent", lazy: true);
  78. await runtime.RegisterImplicitAgentSubscriptionsAsync<SubscribedSaveLoadAgent>("MyAgent");
  79. var topicType = "TestTopic";
  80. await runtime.PublishMessageAsync(new TextMessage { Source = topicType, Content = "test" }, new TopicId(topicType)).ConfigureAwait(true);
  81. await runtime.RunUntilIdleAsync();
  82. agent.ReceivedMessages.Any().Should().BeTrue("Agent should receive messages when subscribed.");
  83. // Save the state
  84. var savedState = await runtime.SaveStateAsync();
  85. // Ensure calling TryGetPropertyValue with the agent's key returns the agent's state
  86. savedState.TryGetProperty(agentId.ToString(), out var agentState).Should().BeTrue("Agent state should be saved");
  87. // Ensure the agent's state is stored as a valid JSON object
  88. agentState.ValueKind.Should().Be(JsonValueKind.Object, "Agent state should be stored as a JSON object");
  89. // Serialize and Deserialize the state to simulate persistence
  90. string json = JsonSerializer.Serialize(savedState);
  91. json.Should().NotBeNullOrEmpty("Serialized state should not be empty");
  92. var deserializedState = JsonSerializer.Deserialize<IDictionary<string, JsonElement>>(json)
  93. ?? throw new Exception("Deserialized state is unexpectedly null");
  94. deserializedState.Should().ContainKey(agentId.ToString());
  95. // Start new runtime and restore the state
  96. var newRuntime = new InProcessRuntime();
  97. await newRuntime.StartAsync();
  98. await newRuntime.RegisterAgentFactoryAsync("MyAgent", (id, runtime) =>
  99. {
  100. agent = new SubscribedSaveLoadAgent(id, runtime, logger);
  101. return ValueTask.FromResult(agent);
  102. });
  103. await newRuntime.RegisterImplicitAgentSubscriptionsAsync<SubscribedSaveLoadAgent>("MyAgent");
  104. // Show that no agent instances exist in the new runtime
  105. newRuntime.agentInstances.Count.Should().Be(0, "Agent should be registered in the new runtime");
  106. // Load the state into the new runtime and show that agent is now instantiated
  107. await newRuntime.LoadStateAsync(savedState);
  108. newRuntime.agentInstances.Count.Should().Be(1, "Agent should be registered in the new runtime");
  109. newRuntime.agentInstances.Should().ContainKey(agentId, "Agent should be loaded into the new runtime");
  110. }
  111. }