Path: redb-route/tests/redb.Route.Tests.Llm/TestHelpers/LocalHttpServer.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Llm/TestHelpers/LocalHttpServer.cs ---- using System.Net; using System.Text; namespace redb.Route.Tests.Llm.TestHelpers; /// /// Tiny in-process HTTP server backed by . Listens /// on a free localhost port chosen at start time, replies to any request with /// the body / headers configured by the test, and records every request URL /// for assertion. Used as a deterministic target for /// tests so we don't depend on /// the public internet. /// /// HttpListener requires http.sys permission on Windows; binding to /// 127.0.0.1 on a high port works without elevation. /// /// public sealed class LocalHttpServer : IDisposable { private readonly HttpListener _listener; private readonly CancellationTokenSource _cts = new(); private readonly Task _loop; private readonly List _requestPaths = new(); /// Base URL the server listens on (e.g. http://127.0.0.1:34567/). public string BaseUrl { get; } /// Host portion of (e.g. 127.0.0.1). public string Host => "127.0.0.1"; /// Body returned for every request (defaults to a small JSON document). public string ResponseBody { get; set; } = """{"ok":true,"answer":"42"}"""; /// Content-Type for replies. public string ContentType { get; set; } = "application/json"; /// Status code for replies. public int StatusCode { get; set; } = 200; /// Snapshot of request URL paths (with query) the server has received. public IReadOnlyList RequestPaths { get { lock (_requestPaths) return _requestPaths.ToArray(); } } /// Starts a server on a free localhost port. public LocalHttpServer() { var port = PickFreePort(); BaseUrl = $"http://127.0.0.1:{port}/"; _listener = new HttpListener(); _listener.Prefixes.Add(BaseUrl); _listener.Start(); _loop = Task.Run(LoopAsync); } private async Task LoopAsync() { while (!_cts.IsCancellationRequested) { HttpListenerContext ctx; try { ctx = await _listener.GetContextAsync().ConfigureAwait(false); } catch { return; } lock (_requestPaths) _requestPaths.Add(ctx.Request.Url?.PathAndQuery ?? ""); ctx.Response.StatusCode = StatusCode; ctx.Response.ContentType = ContentType; var bytes = Encoding.UTF8.GetBytes(ResponseBody); ctx.Response.ContentLength64 = bytes.LongLength; await ctx.Response.OutputStream.WriteAsync(bytes).ConfigureAwait(false); ctx.Response.Close(); } } private static int PickFreePort() => global::redb.Route.Tests.Shared.TestPorts.Next(); /// public void Dispose() { _cts.Cancel(); try { _listener.Stop(); } catch { /* already stopped */ } try { _loop.Wait(TimeSpan.FromSeconds(2)); } catch { /* ignore */ } _listener.Close(); _cts.Dispose(); } }