-
Notifications
You must be signed in to change notification settings - Fork 12
/
TestKit.cs
248 lines (214 loc) · 8.65 KB
/
TestKit.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
// -----------------------------------------------------------------------
// <copyright file="HostingSpec.cs" company="Akka.NET Project">
// Copyright (C) 2013-2022 .NET Foundation <https://github.com/akkadotnet/akka.net>
// </copyright>
// -----------------------------------------------------------------------
using System;
using System.Threading;
using System.Threading.Tasks;
using Akka.Actor;
using Akka.Actor.Internal;
using Akka.Actor.Setup;
using Akka.Annotations;
using Akka.Configuration;
using Akka.Event;
using Akka.Hosting.Logging;
using Akka.Hosting.TestKit.Internals;
using Akka.TestKit;
using Akka.TestKit.Xunit2;
using Akka.TestKit.Xunit2.Internals;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Xunit;
using Xunit.Abstractions;
using Xunit.Sdk;
using LogLevel = Microsoft.Extensions.Logging.LogLevel;
namespace Akka.Hosting.TestKit
{
public abstract class TestKit: TestKitBase, IAsyncLifetime
{
/// <summary>
/// Commonly used assertions used throughout the testkit.
/// </summary>
protected static XunitAssertions Assertions { get; } = new XunitAssertions();
private IHost? _host;
public IHost Host
{
get
{
if(_host is null)
throw new XunitException("Test has not been initialized yet");
return _host;
}
}
public ActorRegistry ActorRegistry => Host.Services.GetRequiredService<ActorRegistry>();
public TimeSpan StartupTimeout { get; }
public string ActorSystemName { get; }
public ITestOutputHelper? Output { get; }
public LogLevel LogLevel { get; }
private readonly TaskCompletionSource<Done> _initialized = new TaskCompletionSource<Done>();
protected TestKit(string? actorSystemName = null, ITestOutputHelper? output = null, TimeSpan? startupTimeout = null, LogLevel logLevel = LogLevel.Information)
: base(Assertions)
{
ActorSystemName = actorSystemName ?? "test";
Output = output;
LogLevel = logLevel;
StartupTimeout = startupTimeout ?? TimeSpan.FromSeconds(10);
}
protected virtual void ConfigureHostConfiguration(IConfigurationBuilder builder)
{ }
protected virtual void ConfigureAppConfiguration(HostBuilderContext context, IConfigurationBuilder builder)
{ }
protected virtual void ConfigureServices(HostBuilderContext context, IServiceCollection services)
{ }
private void InternalConfigureServices(HostBuilderContext context, IServiceCollection services)
{
ConfigureServices(context, services);
services.AddAkka(ActorSystemName, (builder, provider) =>
{
builder.AddHocon(DefaultConfig, HoconAddMode.Prepend);
if (Config is { })
builder.AddHocon(Config, HoconAddMode.Prepend);
builder.ConfigureLoggers(logger =>
{
logger.LogLevel = ToAkkaLogLevel(LogLevel);
logger.ClearLoggers();
logger.AddLogger<TestEventListener>();
});
if (Output is { })
{
builder.StartActors(async (system, registry) =>
{
await LoggerHook(system, registry);
});
}
ConfigureAkka(builder, provider);
builder.AddStartup((system, _) =>
{
try
{
base.InitializeTest(system, (ActorSystemSetup)null!, null, null);
_initialized.SetResult(Done.Instance);
}
catch (Exception e)
{
_initialized.SetException(e);
}
});
});
}
internal virtual async Task LoggerHook(ActorSystem system, IActorRegistry registry)
{
var extSystem = (ExtendedActorSystem)system;
var logger = extSystem.SystemActorOf(Props.Create(() => new TestKitLoggerFactoryLogger()), "log-test");
await logger.Ask<LoggerInitialized>(new InitializeLogger(system.EventStream));
}
protected virtual Config? Config { get; } = null;
protected virtual void ConfigureLogging(ILoggingBuilder builder)
{ }
protected abstract void ConfigureAkka(AkkaConfigurationBuilder builder, IServiceProvider provider);
[InternalApi]
public async Task InitializeAsync()
{
var hostBuilder = new HostBuilder();
if (Output != null)
hostBuilder.ConfigureLogging(logger =>
{
logger.ClearProviders();
logger.AddProvider(new XUnitLoggerProvider(Output, LogLevel));
logger.AddFilter("Akka.*", LogLevel);
ConfigureLogging(logger);
});
hostBuilder
.ConfigureHostConfiguration(ConfigureHostConfiguration)
.ConfigureAppConfiguration(ConfigureAppConfiguration)
.ConfigureServices(InternalConfigureServices);
_host = hostBuilder.Build();
var cts = new CancellationTokenSource(StartupTimeout);
cts.Token.Register(() =>
throw new TimeoutException($"Host failed to start within {StartupTimeout.Seconds} seconds"));
try
{
await _host.StartAsync(cts.Token);
}
finally
{
cts.Dispose();
}
await _initialized.Task;
if (this is not INoImplicitSender && InternalCurrentActorCellKeeper.Current is null)
InternalCurrentActorCellKeeper.Current = (ActorCell)((ActorRefWithCell)TestActor).Underlying;
await BeforeTestStart();
}
protected sealed override void InitializeTest(ActorSystem system, ActorSystemSetup config, string actorSystemName, string testActorName)
{
// no-op, deferring InitializeTest after Host have ran
}
protected virtual Task BeforeTestStart()
{
return Task.CompletedTask;
}
/// <summary>
/// This method is called when a test ends.
///
/// <remarks>
/// If you override this, then make sure you either call base.AfterAllAsync()
/// to shut down the system. Otherwise a memory leak will occur.
/// </remarks>
/// </summary>
protected virtual Task AfterAllAsync()
{
return Task.CompletedTask;
}
public async Task DisposeAsync()
{
Exception? exception = null;
try
{
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
await Task.WhenAny(Task.Delay(Timeout.Infinite, cts.Token), AfterAllAsync());
if (cts.IsCancellationRequested)
throw new TimeoutException($"{nameof(AfterAllAsync)} took more than 5 seconds to execute, aborting.");
}
catch (Exception e)
{
exception = e;
}
finally
{
try
{
Shutdown();
if (_host != null)
{
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
await _host.StopAsync(cts.Token);
}
}
catch
{
// no-op
}
finally
{
_host?.Dispose();
}
if (exception is { })
throw exception;
}
}
private static Event.LogLevel ToAkkaLogLevel(LogLevel logLevel)
=> logLevel switch
{
LogLevel.Trace => Event.LogLevel.DebugLevel,
LogLevel.Debug => Event.LogLevel.DebugLevel,
LogLevel.Information => Event.LogLevel.InfoLevel,
LogLevel.Warning => Event.LogLevel.WarningLevel,
LogLevel.Error => Event.LogLevel.ErrorLevel,
LogLevel.Critical => Event.LogLevel.ErrorLevel,
_ => Event.LogLevel.ErrorLevel
};
}
}