2020-06-29 04:44:35 +02:00
|
|
|
using System;
|
2020-05-16 22:07:24 +02:00
|
|
|
using System.Linq;
|
|
|
|
using System.Threading;
|
2020-06-28 10:55:27 +02:00
|
|
|
using System.Threading.Channels;
|
2020-05-16 22:07:24 +02:00
|
|
|
using System.Threading.Tasks;
|
|
|
|
using Microsoft.AspNetCore.Builder;
|
|
|
|
using Microsoft.AspNetCore.Hosting;
|
|
|
|
using Microsoft.AspNetCore.Hosting.Server.Features;
|
|
|
|
using Microsoft.AspNetCore.Http;
|
|
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
|
|
using Microsoft.Extensions.Hosting;
|
|
|
|
|
|
|
|
namespace BTCPayServer.Tests
|
|
|
|
{
|
|
|
|
public class FakeServer : IDisposable
|
|
|
|
{
|
|
|
|
IWebHost webHost;
|
2020-06-29 05:07:48 +02:00
|
|
|
readonly SemaphoreSlim semaphore;
|
|
|
|
readonly CancellationTokenSource cts = new CancellationTokenSource();
|
2020-05-16 22:07:24 +02:00
|
|
|
public FakeServer()
|
|
|
|
{
|
|
|
|
_channel = Channel.CreateUnbounded<HttpContext>();
|
|
|
|
semaphore = new SemaphoreSlim(0);
|
|
|
|
}
|
|
|
|
|
2020-06-29 05:07:48 +02:00
|
|
|
readonly Channel<HttpContext> _channel;
|
2020-05-16 22:07:24 +02:00
|
|
|
public async Task Start()
|
|
|
|
{
|
|
|
|
webHost = new WebHostBuilder()
|
|
|
|
.UseKestrel()
|
|
|
|
.UseUrls("http://127.0.0.1:0")
|
|
|
|
.Configure(appBuilder =>
|
|
|
|
{
|
|
|
|
appBuilder.Run(async ctx =>
|
|
|
|
{
|
|
|
|
await _channel.Writer.WriteAsync(ctx);
|
|
|
|
await semaphore.WaitAsync(cts.Token);
|
|
|
|
});
|
|
|
|
})
|
|
|
|
.Build();
|
|
|
|
await webHost.StartAsync();
|
|
|
|
var port = new Uri(webHost.ServerFeatures.Get<IServerAddressesFeature>().Addresses.First(), UriKind.Absolute)
|
|
|
|
.Port;
|
|
|
|
ServerUri = new Uri($"http://127.0.0.1:{port}/");
|
|
|
|
}
|
|
|
|
|
|
|
|
public Uri ServerUri { get; set; }
|
|
|
|
|
|
|
|
public void Done()
|
|
|
|
{
|
|
|
|
semaphore.Release();
|
|
|
|
}
|
|
|
|
|
|
|
|
public async Task Stop()
|
|
|
|
{
|
|
|
|
await webHost.StopAsync();
|
|
|
|
}
|
|
|
|
public void Dispose()
|
|
|
|
{
|
|
|
|
cts.Dispose();
|
|
|
|
webHost?.Dispose();
|
|
|
|
semaphore.Dispose();
|
|
|
|
}
|
|
|
|
|
|
|
|
public async Task<HttpContext> GetNextRequest()
|
|
|
|
{
|
|
|
|
return await _channel.Reader.ReadAsync();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|