/
DevHostServerFixture.cs
91 lines (77 loc) · 2.64 KB
/
DevHostServerFixture.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.ExceptionServices;
using System.Threading;
using VnetCapacityPlanner.Tests.BlazorDevServer;
namespace VnetCapacityPlanner.Tests
{
// Based on https://github.com/dotnet/aspnetcore/blob/master/src/Components/test/E2ETest/Infrastructure/ServerFixtures/DevHostServerFixture.cs
public class DevHostServerFixture : IDisposable
{
private readonly Lazy<Uri> _rootUriInitializer;
public DevHostServerFixture()
{
_rootUriInitializer = new Lazy<Uri>(() => new Uri(StartAndGetRootUri()));
}
public Uri RootUri => _rootUriInitializer.Value;
public IHost Host { get; set; }
public string PathBase { get; set; }
public string ContentRoot { get; set; }
protected string StartAndGetRootUri()
{
Host = CreateWebHost();
RunInBackgroundThread(Host.Start);
return Host.Services.GetRequiredService<IServer>().Features
.Get<IServerAddressesFeature>()
.Addresses.Single();
}
protected IHost CreateWebHost()
{
var host = "127.0.0.1";
var args = new List<string>
{
"--urls", $"http://{host}:0",
"--contentroot", ContentRoot,
"--pathbase", PathBase,
};
return DevServer.BuildWebHost(args.ToArray());
}
protected static void RunInBackgroundThread(Action action)
{
var isDone = new ManualResetEvent(false);
ExceptionDispatchInfo edi = null;
new Thread(() =>
{
try
{
action();
}
catch (Exception ex)
{
edi = ExceptionDispatchInfo.Capture(ex);
}
isDone.Set();
}).Start();
if (!isDone.WaitOne(TimeSpan.FromSeconds(10)))
{
throw new TimeoutException("Timed out waiting for: " + action);
}
if (edi != null)
{
throw edi.SourceException;
}
}
public void Dispose()
{
// This can be null if creating the webhost throws, we don't want to throw here and hide
// the original exception.
Host?.Dispose();
Host?.StopAsync();
}
}
}