Skip to content

Instantly share code, notes, and snippets.

@atwayne
Last active November 3, 2021 15:42
Show Gist options
  • Save atwayne/f3aa7172eb08b8248593aa1ec06fd861 to your computer and use it in GitHub Desktop.
Save atwayne/f3aa7172eb08b8248593aa1ec06fd861 to your computer and use it in GitHub Desktop.
An in-memory HTTP server. Created for unit test
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace TetraPak.PIExecution.Subscriber.Clients.Tests
{
public static class EmbeddedHttpServer
{
public static string GetLocalhostAddress()
{
var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
var port = ((IPEndPoint)listener.LocalEndpoint).Port;
listener.Stop();
return $"http://localhost:{port}/";
}
public static Task BasicHttpServer(string url, string output, string pattern = null)
{
return Task.Run(() =>
{
var listener = new HttpListener();
listener.Prefixes.Add(url);
listener.Start();
var context = listener.GetContext();
var requestUrl = context.Request.Url.ToString();
var response = context.Response;
if (pattern != null && !Regex.IsMatch(requestUrl, pattern))
{
response.Abort();
return;
}
var stream = response.OutputStream;
var writer = new StreamWriter(stream);
writer.Write(output);
writer.Close();
});
}
}
}
var baseUrl = EmbeddedHttpServer.GetLocalhostAddress();
var client = new SmartClient(new Uri(baseUrl));
var emptyResponse = "{}";
using(EmbeddedHttpServer.BasicHttpServer(baseUrl, emptyResponse))
{

}
var baseUrl = EmbeddedHttpServer.GetLocalhostAddress();
var client = new SmartClient(new Uri(baseUrl));
var emptyResponse = "{}";
var expectedPattern = $"\\?id=42$";
using(EmbeddedHttpServer.BasicHttpServer(baseUrl, emptyResponse, expectedPattern)
{

}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment