Files
agent-framework/dotnet/tests/Microsoft.Agents.AI.Foundry.Hosting.UnitTests/AgentFrameworkResponseHandlerWorkflowTests.cs
Roger Barreto fb97e93a01 .NET: Add dedicated Foundry.Hosting UnitTest project (#5592)
* Foundry.Hosting.UnitTests: extract project from Foundry.UnitTests

Move all Hosting/* tests, three toolbox TestData JSONs, and the FakeAuthenticationTokenProvider/HttpHandlerAssert/TestDataUtil helpers (trimmed to toolbox getters) into a new Microsoft.Agents.AI.Foundry.Hosting.UnitTests project. Add it to the slnx and grant the new assembly InternalsVisibleTo from Microsoft.Agents.AI.Foundry and Microsoft.Agents.AI.Foundry.Hosting.

* Foundry.Hosting.UnitTests: align namespaces to assembly name

Rename namespaces from Microsoft.Agents.AI.Foundry.UnitTests(.Hosting) to Microsoft.Agents.AI.Foundry.Hosting.UnitTests across all moved tests, the duplicated helpers, and the trimmed TestDataUtil. Also fixes the prior namespace inconsistency in FoundryToolboxTests.

* Foundry.Hosting.UnitTests: split WorkflowIntegrationTests by SUT

Replace the WorkflowIntegrationTests file (an IT-named file inside a UT project) with two SUT-focused files plus a shared test-doubles file:

- AgentFrameworkResponseHandlerWorkflowTests.cs - the 5 handler-driven tests that exercise AgentFrameworkResponseHandler with a real workflow agent.
- OutputConverterWorkflowTests.cs - the 5 OutputConverter tests driven by hand-crafted update sequences mirroring real workflow patterns.
- WorkflowTestAgents.cs - StreamingTextAgent and ThrowingStreamingAgent extracted as internal types used by both files.

* Foundry.UnitTests: trim Hosting-related conditionals and dead testdata

Now that Hosting tests live in their own project:
- drop the Compile Remove guard for the Hosting subfolder,
- drop the .NETCoreApp-only PackageReferences (Azure.AI.AgentServer.Responses, Microsoft.AspNetCore.TestHost, OpenTelemetry, OpenTelemetry.Exporter.InMemory),
- drop the conditional ProjectReference to Microsoft.Agents.AI.Foundry.Hosting,
- delete the three Toolbox JSON files and the matching Toolbox getters in TestDataUtil.

* Foundry.Hosting.UnitTests: drop redundant 'using Microsoft.Agents.AI.Foundry.Hosting'

The new project namespace is Microsoft.Agents.AI.Foundry.Hosting.UnitTests, which already brings the parent Microsoft.Agents.AI.Foundry.Hosting namespace into scope. The explicit using statement is therefore redundant (IDE0005). Caught by 'dotnet format --verify-no-changes' running on Linux against the .NET 10 SDK.

* Foundry.Hosting: drop InternalsVisibleTo to Foundry.UnitTests

The non-hosting Foundry.UnitTests project no longer holds any Hosting tests after the split, so it doesn't need access to internal types in Microsoft.Agents.AI.Foundry.Hosting. Only Microsoft.Agents.AI.Foundry.Hosting.UnitTests needs it.

* Foundry.Hosting: rename DelegatingResponsesClient to UserAgentResponsesClient

Address westey-m's review feedback on PR #5453: `Delegating*` is conventionally reserved for inheritable base classes (mirroring `DelegatingHandler`) where consumers override one or two members. This polyfill is sealed and only injects the User-Agent supplement, so the new name reflects its actual purpose.

Renamed via `git mv` to preserve history:
* `src/Microsoft.Agents.AI.Foundry.Hosting/DelegatingResponsesClient.cs` to `UserAgentResponsesClient.cs`
* `tests/Microsoft.Agents.AI.Foundry.Hosting.UnitTests/DelegatingResponsesClientTests.cs` to `UserAgentResponsesClientTests.cs`

Class, constructor, and all references updated across:
* `src/.../UserAgentResponsesClient.cs` (class + constructor + internal log message)
* `src/.../ServiceCollectionExtensions.cs` (cref + type check + instantiation)
* `src/.../HostedAgentUserAgentPolicy.cs` (cref)
* `tests/Foundry.UnitTests/RequestOptionsExtensionsTests.cs` (comment)
* `tests/Foundry.Hosting.UnitTests/UserAgentResponsesClientTests.cs` (class + cref + instantiations)
2026-04-30 21:09:25 +00:00

213 lines
8.9 KiB
C#

// Copyright (c) Microsoft. All rights reserved.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Azure.AI.AgentServer.Responses;
using Azure.AI.AgentServer.Responses.Models;
using Microsoft.Agents.AI.Workflows;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Moq;
namespace Microsoft.Agents.AI.Foundry.Hosting.UnitTests;
/// <summary>
/// Unit tests for <see cref="AgentFrameworkResponseHandler"/> that verify behavior
/// when the registered agent is a workflow-backed <see cref="AIAgent"/>. These exercise
/// real workflow builders and the in-process execution environment to drive the handler
/// through realistic streaming event patterns.
/// </summary>
public class AgentFrameworkResponseHandlerWorkflowTests
{
[Fact]
public async Task SequentialWorkflow_SingleAgent_ProducesTextOutputAsync()
{
// Arrange: single-agent sequential workflow
var echoAgent = new StreamingTextAgent("echo", "Hello from the workflow!");
var workflow = AgentWorkflowBuilder.BuildSequential("test-sequential", echoAgent);
var workflowAgent = workflow.AsAIAgent(
id: "workflow-agent",
name: "Test Workflow",
executionEnvironment: InProcessExecution.OffThread,
includeExceptionDetails: true);
var (handler, request, context) = CreateHandlerWithAgent(workflowAgent, "Hello");
// Act
var events = await CollectEventsAsync(handler, request, context);
// Assert: should have lifecycle events + at least one text output + terminal
Assert.IsType<ResponseCreatedEvent>(events[0]);
Assert.IsType<ResponseInProgressEvent>(events[1]);
Assert.True(events.Count >= 4, $"Expected at least 4 events, got {events.Count}");
var lastEvent = events[^1];
Assert.True(
lastEvent is ResponseCompletedEvent || lastEvent is ResponseFailedEvent,
$"Expected terminal event, got {lastEvent.GetType().Name}");
}
[Fact]
public async Task SequentialWorkflow_TwoAgents_ProducesOutputFromBothAsync()
{
// Arrange: two agents in sequence
var agent1 = new StreamingTextAgent("agent1", "First agent says hello");
var agent2 = new StreamingTextAgent("agent2", "Second agent says goodbye");
var workflow = AgentWorkflowBuilder.BuildSequential("test-sequential-2", agent1, agent2);
var workflowAgent = workflow.AsAIAgent(
id: "seq-workflow",
name: "Sequential Workflow",
executionEnvironment: InProcessExecution.OffThread,
includeExceptionDetails: true);
var (handler, request, context) = CreateHandlerWithAgent(workflowAgent, "Process this");
// Act
var events = await CollectEventsAsync(handler, request, context);
// Assert: should have workflow action events for executor lifecycle
var lastEvent = events[^1];
Assert.True(
lastEvent is ResponseCompletedEvent || lastEvent is ResponseFailedEvent,
$"Expected terminal event, got {lastEvent.GetType().Name}");
// Should have output item events (either text messages or workflow actions)
Assert.True(events.OfType<ResponseOutputItemAddedEvent>().Any(),
"Expected at least one output item from the workflow");
}
[Fact]
public async Task Workflow_AgentThrowsException_ProducesErrorOutputAsync()
{
// Arrange: workflow with an agent that throws
var throwingAgent = new ThrowingStreamingAgent("thrower", new InvalidOperationException("Agent crashed"));
var workflow = AgentWorkflowBuilder.BuildSequential("test-error", throwingAgent);
var workflowAgent = workflow.AsAIAgent(
id: "error-workflow",
name: "Error Workflow",
executionEnvironment: InProcessExecution.OffThread,
includeExceptionDetails: true);
var (handler, request, context) = CreateHandlerWithAgent(workflowAgent, "Trigger error");
// Act
var events = await CollectEventsAsync(handler, request, context);
// Assert: should have lifecycle events + error/failure indicator
Assert.IsType<ResponseCreatedEvent>(events[0]);
Assert.IsType<ResponseInProgressEvent>(events[1]);
var lastEvent = events[^1];
// Workflow errors surface as either Failed or Completed (depending on error handling)
Assert.True(
lastEvent is ResponseCompletedEvent || lastEvent is ResponseFailedEvent,
$"Expected terminal event, got {lastEvent.GetType().Name}");
}
[Fact]
public async Task Workflow_ExecutorEvents_ProduceWorkflowActionItemsAsync()
{
// Arrange
var agent = new StreamingTextAgent("test-agent", "Result");
var workflow = AgentWorkflowBuilder.BuildSequential("test-actions", agent);
var workflowAgent = workflow.AsAIAgent(
id: "actions-workflow",
name: "Actions Workflow",
executionEnvironment: InProcessExecution.OffThread);
var (handler, request, context) = CreateHandlerWithAgent(workflowAgent, "Hello");
// Act
var events = await CollectEventsAsync(handler, request, context);
// Assert: workflow should produce OutputItemAdded events for executor lifecycle
var addedEvents = events.OfType<ResponseOutputItemAddedEvent>().ToList();
Assert.True(addedEvents.Count >= 1,
$"Expected at least 1 output item added event, got {addedEvents.Count}");
}
[Fact]
public async Task WorkflowAgent_RegisteredWithKey_ResolvesCorrectlyAsync()
{
// Arrange: workflow agent registered with a keyed service name
var agent = new StreamingTextAgent("inner", "Keyed workflow response");
var workflow = AgentWorkflowBuilder.BuildSequential("keyed-wf", agent);
var workflowAgent = workflow.AsAIAgent(
id: "keyed-workflow",
name: "Keyed Workflow",
executionEnvironment: InProcessExecution.OffThread);
var services = new ServiceCollection();
services.AddSingleton<AgentSessionStore>(new InMemoryAgentSessionStore());
services.AddKeyedSingleton("my-workflow", workflowAgent);
var sp = services.BuildServiceProvider();
var handler = new AgentFrameworkResponseHandler(sp, NullLogger<AgentFrameworkResponseHandler>.Instance);
var request = new CreateResponse { Model = "test", AgentReference = new AgentReference("my-workflow") };
request.Input = CreateUserInput("Test keyed workflow");
var mockContext = CreateMockContext();
// Act
var events = await CollectEventsAsync(handler, request, mockContext.Object);
// Assert
Assert.IsType<ResponseCreatedEvent>(events[0]);
Assert.True(events.Count >= 3, $"Expected at least 3 events, got {events.Count}");
}
private static (AgentFrameworkResponseHandler handler, CreateResponse request, ResponseContext context)
CreateHandlerWithAgent(AIAgent agent, string userMessage)
{
var services = new ServiceCollection();
services.AddSingleton<AgentSessionStore>(new InMemoryAgentSessionStore());
services.AddSingleton(agent);
services.AddSingleton<ILogger<AgentFrameworkResponseHandler>>(NullLogger<AgentFrameworkResponseHandler>.Instance);
var sp = services.BuildServiceProvider();
var handler = new AgentFrameworkResponseHandler(sp, NullLogger<AgentFrameworkResponseHandler>.Instance);
var request = new CreateResponse { Model = "test" };
request.Input = CreateUserInput(userMessage);
var mockContext = CreateMockContext();
return (handler, request, mockContext.Object);
}
private static BinaryData CreateUserInput(string text)
{
return BinaryData.FromObjectAsJson(new[]
{
new { type = "message", id = "msg_in_1", status = "completed", role = "user",
content = new[] { new { type = "input_text", text } }
}
});
}
private static Mock<ResponseContext> CreateMockContext()
{
var mock = new Mock<ResponseContext>("resp_" + new string('0', 46)) { CallBase = true };
mock.Setup(x => x.GetHistoryAsync(It.IsAny<CancellationToken>()))
.ReturnsAsync(Array.Empty<OutputItem>());
mock.Setup(x => x.GetInputItemsAsync(It.IsAny<bool>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(Array.Empty<Item>());
return mock;
}
private static async Task<List<ResponseStreamEvent>> CollectEventsAsync(
AgentFrameworkResponseHandler handler,
CreateResponse request,
ResponseContext context)
{
var events = new List<ResponseStreamEvent>();
await foreach (var evt in handler.CreateAsync(request, context, CancellationToken.None))
{
events.Add(evt);
}
return events;
}
}