csharp-sdk/tests/ModelContextProtocol.AspNetCore.Tests/Utils/KestrelInMemoryTransport.cs
Eirik Tsarpalis 39ab6cde0d
Separate ASP.NET Core tests into a distinct project and make the main test project netfx compatible. (#254)
* Separate ASP.NET Core tests into a distinct project and make the main test project netfx compatible.

* Fix merge conflicts.

* Update tests/ModelContextProtocol.Tests/ModelContextProtocol.Tests.csproj

Co-authored-by: Stephen Halter <halter73@gmail.com>

* Revert "Fix merge conflicts."

This reverts commit 852169b96786bad2144795540fa164e20b4b197e.

* Fix merge conflicts

---------

Co-authored-by: Stephen Halter <halter73@gmail.com>
2025-04-09 19:16:53 +01:00

50 lines
1.5 KiB
C#

using Microsoft.AspNetCore.Connections;
using System.Net;
using System.Threading.Channels;
namespace ModelContextProtocol.Tests.Utils;
public sealed class KestrelInMemoryTransport : IConnectionListenerFactory, IConnectionListener
{
private readonly Channel<ConnectionContext> _acceptQueue = Channel.CreateUnbounded<ConnectionContext>();
private EndPoint? _endPoint;
public EndPoint EndPoint => _endPoint ?? throw new InvalidOperationException("EndPoint is not set. Call BindAsync first.");
public KestrelInMemoryConnection CreateConnection()
{
var connection = new KestrelInMemoryConnection();
_acceptQueue.Writer.TryWrite(connection);
return connection;
}
public async ValueTask<ConnectionContext?> AcceptAsync(CancellationToken cancellationToken = default)
{
if (await _acceptQueue.Reader.WaitToReadAsync(cancellationToken))
{
while (_acceptQueue.Reader.TryRead(out var item))
{
return item;
}
}
return null;
}
public ValueTask<IConnectionListener> BindAsync(EndPoint endpoint, CancellationToken cancellationToken = default)
{
_endPoint = endpoint;
return new ValueTask<IConnectionListener>(this);
}
public ValueTask DisposeAsync()
{
return UnbindAsync(default);
}
public ValueTask UnbindAsync(CancellationToken cancellationToken = default)
{
_acceptQueue.Writer.TryComplete();
return default;
}
}