// Copyright (c) Microsoft. All rights reserved.
using System.ClientModel;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.AI;
using OpenAI.Chat;
namespace Microsoft.Agents.AI.OpenAI.UnitTests.ChatClient;
///
/// Unit tests for the class.
///
public sealed class AsyncStreamingChatCompletionUpdateCollectionResultTests
{
///
/// Verify that GetContinuationToken returns null.
///
[Fact]
public void GetContinuationToken_ReturnsNull()
{
// Arrange
IAsyncEnumerable updates = CreateTestUpdatesAsync();
AsyncCollectionResult collectionResult = new AsyncStreamingChatCompletionUpdateCollectionResult(updates);
// Act
ContinuationToken? token = collectionResult.GetContinuationToken(null!);
// Assert
Assert.Null(token);
}
///
/// Verify that GetRawPagesAsync returns a single page.
///
[Fact]
public async Task GetRawPagesAsync_ReturnsSinglePageAsync()
{
// Arrange
IAsyncEnumerable updates = CreateTestUpdatesAsync();
AsyncCollectionResult collectionResult = new AsyncStreamingChatCompletionUpdateCollectionResult(updates);
// Act
List pages = [];
await foreach (ClientResult page in collectionResult.GetRawPagesAsync())
{
pages.Add(page);
}
// Assert
Assert.Single(pages);
}
///
/// Verify that iterating through the collection yields streaming updates.
///
[Fact]
public async Task IterateCollection_YieldsUpdatesAsync()
{
// Arrange
IAsyncEnumerable updates = CreateTestUpdatesAsync();
AsyncCollectionResult collectionResult = new AsyncStreamingChatCompletionUpdateCollectionResult(updates);
// Act
List results = [];
await foreach (StreamingChatCompletionUpdate update in collectionResult)
{
results.Add(update);
}
// Assert
Assert.Single(results);
}
///
/// Verify that iterating through the collection with multiple updates yields all updates.
///
[Fact]
public async Task IterateCollection_WithMultipleUpdates_YieldsAllUpdatesAsync()
{
// Arrange
IAsyncEnumerable updates = CreateMultipleTestUpdatesAsync();
AsyncCollectionResult collectionResult = new AsyncStreamingChatCompletionUpdateCollectionResult(updates);
// Act
List results = [];
await foreach (StreamingChatCompletionUpdate update in collectionResult)
{
results.Add(update);
}
// Assert
Assert.Equal(3, results.Count);
}
private static async IAsyncEnumerable CreateTestUpdatesAsync()
{
yield return new AgentResponseUpdate(ChatRole.Assistant, "test");
await Task.CompletedTask;
}
private static async IAsyncEnumerable CreateMultipleTestUpdatesAsync()
{
yield return new AgentResponseUpdate(ChatRole.Assistant, "first");
yield return new AgentResponseUpdate(ChatRole.Assistant, "second");
yield return new AgentResponseUpdate(ChatRole.Assistant, "third");
await Task.CompletedTask;
}
}