csharp-sdk/tests/ModelContextProtocol.AspNetCore.Tests/Utils/KestrelInMemoryTest.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

38 lines
1.4 KiB
C#

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Connections;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
namespace ModelContextProtocol.Tests.Utils;
public class KestrelInMemoryTest : LoggedTest
{
private readonly KestrelInMemoryTransport _inMemoryTransport = new();
public KestrelInMemoryTest(ITestOutputHelper testOutputHelper)
: base(testOutputHelper)
{
// Use SlimBuilder instead of EmptyBuilder to avoid having to call UseRouting() and UseEndpoints(_ => { })
// or a helper that does the same every test. But clear out the existing socket transport to avoid potential port conflicts.
Builder = WebApplication.CreateSlimBuilder();
Builder.Services.RemoveAll<IConnectionListenerFactory>();
Builder.Services.AddSingleton<IConnectionListenerFactory>(_inMemoryTransport);
Builder.Services.AddSingleton(LoggerProvider);
}
public WebApplicationBuilder Builder { get; }
public HttpClient CreateHttpClient()
{
var socketsHttpHandler = new SocketsHttpHandler()
{
ConnectCallback = (context, token) =>
{
var connection = _inMemoryTransport.CreateConnection();
return new(connection.ClientStream);
},
};
return new HttpClient(socketsHttpHandler);
}
}