CSharpHttpServer/SimpleHttpServerTest/SimpleServerTest.cs
2024-01-13 03:14:22 +01:00

63 lines
2.2 KiB
C#

using SimpleHttpServer;
using System.Net;
using System.Runtime.CompilerServices;
namespace SimpleHttpServerTest;
[TestClass]
public class SimpleServerTest {
const int PORT = 8833;
private HttpServer? activeServer = null;
private HttpClient? activeHttpClient = null;
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<HttpResponseMessage> 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();
if (activeServer != null)
throw new InvalidOperationException("Tried to create another httpserver instance when an existing one was already running.");
Console.WriteLine("Starting server...");
activeServer = new HttpServer(PORT, conf);
activeServer.RegisterEndpointsFromType<TestEndpoints>();
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!");
}
}
}