using SimpleHttpServer; using System.Net; namespace SimpleHttpServerTest; [TestClass] public class SimpleServerTest { const int PORT = 8833; private HttpServer? activeServer = null; private HttpClient? activeHttpClient = null; private bool failOnLogError = true; private static string GetRequestPath(string url) => $"http://localhost:{PORT}/{url.TrimStart('/')}"; private async Task RequestGetStringAsync(string path) => await activeHttpClient!.GetStringAsync(GetRequestPath(path)); private async Task AssertGetStatusCodeAsync(string path, HttpStatusCode statusCode) { var resp = await activeHttpClient!.GetAsync(GetRequestPath(path)); Assert.AreEqual(resp.StatusCode, statusCode); return resp; } [TestInitialize] public void Init() { var conf = new SimpleHttpServerConfiguration() { DisableLogMessagePrinting = false, LogMessageHandler = (LogOutputTopic topic, string message, LogOutputLevel logLevel) => { if (failOnLogError && logLevel is LogOutputLevel.Error or LogOutputLevel.Fatal) Assert.Fail($"An error was thrown in the log output:\n{topic} {message}"); } }; if (activeServer != null) throw new InvalidOperationException("Tried to create another httpserver instance when an existing one was already running."); Console.WriteLine("Starting server..."); failOnLogError = true; activeServer = new HttpServer(PORT, conf); activeServer.RegisterEndpointsFromType(); activeServer.Start(); activeHttpClient = new HttpClient(); Console.WriteLine("Server started."); } [TestCleanup] public async Task Cleanup() { var ctokSrc = new CancellationTokenSource(TimeSpan.FromMinutes(2)); if (activeServer == null) { throw new InvalidOperationException("Tried to shut down server when an existing one wasnt runnign yet"); } await Console.Out.WriteLineAsync("Shutting down server..."); await activeServer.StopAsync(ctokSrc.Token); activeHttpClient?.Dispose(); activeHttpClient = null; await Console.Out.WriteLineAsync("Shutdown finished."); } [TestMethod] public async Task CheckSimpleServe() { await AssertGetStatusCodeAsync("/", HttpStatusCode.OK); } public class TestEndpoints { [HttpEndpoint(HttpRequestType.GET, "/", "index.html", "amogus.html")] public static async Task Index(RequestContext req) { await req.RespWriter.WriteLineAsync("It works!"); } } }