// Copyright (c) Microsoft Corporation. All rights reserved. // InMemoryAgentRuntimeFixture.cs using System.Diagnostics; using Microsoft.AutoGen.Contracts; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Hosting; using AgentRegistration = (string Name, System.Type Type); namespace Microsoft.AutoGen.Core.Tests; /// /// InMemoryAgentRuntimeFixture - provides a fixture for the agent runtime. /// /// /// This fixture is used to provide a runtime for the agent tests. /// However, it is shared between tests. So operations from one test can affect another. /// public sealed class InMemoryAgentRuntimeFixture : IDisposable { private static IEnumerable DefaultAgents = [(nameof(TestAgent), typeof(TestAgent))]; public InMemoryAgentRuntimeFixture() : this(null, null) { } public InMemoryAgentRuntimeFixture(HostApplicationBuilder? hostBuilder = null, IEnumerable? agentTypes = null) { var builder = hostBuilder ?? new HostApplicationBuilder(); builder.Services.TryAddSingleton(DistributedContextPropagator.Current); builder.AddAgentWorker(); foreach (var agentType in agentTypes ?? DefaultAgents) { builder.AddAgent(agentType.Name, agentType.Type); } AppHost = builder.Build(); AppHost.StartAsync().Wait(); } public IHost AppHost { get; } /// /// Start - starts the agent /// /// IAgentWorker, TestAgent public (IAgentRuntime, TestAgent) Start() => Start(); public (IAgentRuntime, TAgent) Start() where TAgent : Agent { var agent = ActivatorUtilities.CreateInstance(AppHost.Services); var worker = AppHost.Services.GetRequiredService(); Agent.Initialize(worker, agent); return (worker, agent); } /// /// Stop - stops the agent and ensures cleanup /// public void Stop() { AppHost?.StopAsync().GetAwaiter().GetResult(); } /// /// Dispose - Ensures cleanup after each test /// public void Dispose() { Stop(); } }