-
Notifications
You must be signed in to change notification settings - Fork 1k
/
AkkaSpec.cs
344 lines (297 loc) · 14.5 KB
/
AkkaSpec.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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
//-----------------------------------------------------------------------
// <copyright file="AkkaSpec.cs" company="Akka.NET Project">
// Copyright (C) 2009-2024 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2024 .NET Foundation <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Akka.Actor;
using Akka.Actor.Setup;
using Akka.Configuration;
using Akka.TestKit.Internal.StringMatcher;
using Akka.TestKit.TestEvent;
using Akka.Util;
using Akka.Util.Internal;
using FluentAssertions;
using Xunit;
using Xunit.Abstractions;
using Xunit.Sdk;
using static FluentAssertions.FluentActions;
// ReSharper disable once CheckNamespace
namespace Akka.TestKit
{
public abstract class AkkaSpec : Xunit2.TestKit //AkkaSpec is not part of TestKit
{
private static Regex _nameReplaceRegex = new("[^a-zA-Z0-9]", RegexOptions.Compiled);
private static readonly Config _akkaSpecConfig = ConfigurationFactory.ParseString(@"
akka {
loglevel = WARNING
stdout-loglevel = WARNING
serialize-messages = on
actor {
ask-timeout = 20s
#default-dispatcher {
# executor = fork-join-executor
# fork-join-executor {
# parallelism-min = 8
# parallelism-factor = 2.0
# parallelism-max = 8
# }
#}
}
}
# use random ports to avoid race conditions with binding contention
akka.remote.dot-netty.tcp.port = 0");
private static int _systemNumber = 0;
private static ActorSystemSetup FromActorSystemSetup(ActorSystemSetup setup)
{
var bootstrapOptions = setup.Get<BootstrapSetup>();
var bootstrap = bootstrapOptions.HasValue ? bootstrapOptions.Value : BootstrapSetup.Create();
bootstrap = bootstrap.WithConfigFallback(_akkaSpecConfig);
return setup.And(bootstrap);
}
public AkkaSpec(string config, ITestOutputHelper output = null)
: this(ConfigurationFactory.ParseString(config).WithFallback(_akkaSpecConfig), output)
{
}
public AkkaSpec(Config config = null, ITestOutputHelper output = null)
: base(config.SafeWithFallback(_akkaSpecConfig), GetCallerName(), output)
{
BeforeAll();
}
public AkkaSpec(ActorSystemSetup setup, ITestOutputHelper output = null)
: base(FromActorSystemSetup(setup), GetCallerName(), output)
{
BeforeAll();
}
public AkkaSpec(ITestOutputHelper output, Config config = null)
: base(config.SafeWithFallback(_akkaSpecConfig), GetCallerName(), output)
{
BeforeAll();
}
public AkkaSpec(ActorSystem system, ITestOutputHelper output = null)
: base(system, output)
{
BeforeAll();
}
private void BeforeAll()
{
GC.Collect();
AtStartup();
}
protected override void AfterAll()
{
BeforeTermination();
base.AfterAll();
AfterTermination();
}
protected virtual void AtStartup() { }
protected virtual void BeforeTermination()
{
}
protected virtual void AfterTermination()
{
}
private static string GetCallerName()
{
var systemNumber = Interlocked.Increment(ref _systemNumber);
var stackTrace = new StackTrace(0);
var name = stackTrace.GetFrames()?
.Select(f => f.GetMethod())
.Where(m => m.DeclaringType != null)
.SkipWhile(m => m.DeclaringType.Name == "AkkaSpec")
.Select(m => _nameReplaceRegex.Replace(m.DeclaringType.Name + "-" + systemNumber, "-"))
.FirstOrDefault() ?? "test";
return name;
}
public static Config AkkaSpecConfig { get { return _akkaSpecConfig; } }
protected T ExpectMsgOf<T>(
TimeSpan? timeout,
string hint,
Func<object, T> function,
CancellationToken cancellationToken = default)
=> ExpectMsgOfAsync(timeout, hint, this, function, cancellationToken)
.ConfigureAwait(false).GetAwaiter().GetResult();
protected async Task<T> ExpectMsgOfAsync<T>(
TimeSpan? timeout,
string hint,
Func<object, T> function,
CancellationToken cancellationToken = default)
=> await ExpectMsgOfAsync(timeout, hint, this, function, cancellationToken)
.ConfigureAwait(false);
protected async Task<T> ExpectMsgOfAsync<T>(
TimeSpan? timeout,
string hint,
Func<object, Task<T>> function,
CancellationToken cancellationToken = default)
=> await ExpectMsgOfAsync(timeout, hint, this, function, cancellationToken)
.ConfigureAwait(false);
protected T ExpectMsgOf<T>(
TimeSpan? timeout,
string hint,
TestKitBase probe,
Func<object, T> function,
CancellationToken cancellationToken = default)
=> ExpectMsgOfAsync(timeout, hint, probe, function, cancellationToken)
.ConfigureAwait(false).GetAwaiter().GetResult();
protected async Task<T> ExpectMsgOfAsync<T>(
TimeSpan? timeout,
string hint,
TestKitBase probe,
Func<object, T> function,
CancellationToken cancellationToken = default)
=> await ExpectMsgOfAsync(timeout, hint, probe, o => Task.FromResult(function(o)), cancellationToken)
.ConfigureAwait(false);
protected async Task<T> ExpectMsgOfAsync<T>(
TimeSpan? timeout,
string hint,
TestKitBase probe,
Func<object, Task<T>> function,
CancellationToken cancellationToken = default)
{
var (success, envelope) = await probe.TryReceiveOneAsync(timeout, cancellationToken)
.ConfigureAwait(false);
if(!success)
Assertions.Fail($"expected message of type {typeof(T)} but timed out after {GetTimeoutOrDefault(timeout)}");
var message = envelope.Message;
Assertions.AssertTrue(message != null, $"expected {hint} but got null message");
//TODO: Check next line.
Assertions.AssertTrue(
function.GetMethodInfo().GetParameters().Any(x => x.ParameterType.IsInstanceOfType(message)),
$"expected {hint} but got {message} instead");
return await function(message).ConfigureAwait(false);
}
protected T ExpectMsgOf<T>(
string hint,
TestKitBase probe,
Func<object, T> pf,
CancellationToken cancellationToken = default)
=> ExpectMsgOfAsync(hint, probe, pf, cancellationToken)
.ConfigureAwait(false).GetAwaiter().GetResult();
protected async Task<T> ExpectMsgOfAsync<T>(
string hint,
TestKitBase probe,
Func<object, T> pf,
CancellationToken cancellationToken = default)
=> await ExpectMsgOfAsync(hint, probe, o => Task.FromResult(pf(o)), cancellationToken)
.ConfigureAwait(false);
protected async Task<T> ExpectMsgOfAsync<T>(
string hint,
TestKitBase probe,
Func<object, Task<T>> pf,
CancellationToken cancellationToken = default)
{
var t = await probe.ExpectMsgAsync<T>(cancellationToken: cancellationToken)
.ConfigureAwait(false);
//TODO: Check if this really is needed:
Assertions.AssertTrue(pf.GetMethodInfo().GetParameters().Any(x => x.ParameterType.IsInstanceOfType(t)),
$"expected {hint} but got {t} instead");
return await pf(t);
}
protected T ExpectMsgOf<T>(
string hint,
Func<object, T> pf,
CancellationToken cancellationToken = default)
=> ExpectMsgOfAsync(hint, this, pf, cancellationToken)
.ConfigureAwait(false).GetAwaiter().GetResult();
protected async Task<T> ExpectMsgOfAsync<T>(
string hint,
Func<object, T> pf,
CancellationToken cancellationToken = default)
=> await ExpectMsgOfAsync(hint, this, pf, cancellationToken)
.ConfigureAwait(false);
protected async Task<T> ExpectMsgOfAsync<T>(
string hint,
Func<object, Task<T>> pf,
CancellationToken cancellationToken = default)
=> await ExpectMsgOfAsync(hint, this, pf, cancellationToken)
.ConfigureAwait(false);
[Obsolete("Method name typo, please use ExpectMsgOf instead")]
protected T ExpectMsgPf<T>(TimeSpan? timeout, string hint, Func<object, T> function)
=> ExpectMsgOf(timeout, hint, this, function);
[Obsolete("Method name typo, please use ExpectMsgOf instead")]
protected T ExpectMsgPf<T>(TimeSpan? timeout, string hint, TestKitBase probe, Func<object, T> function)
=> ExpectMsgOf(timeout, hint, probe, function);
[Obsolete("Method name typo, please use ExpectMsgOf instead")]
protected T ExpectMsgPf<T>(string hint, Func<object, T> pf)
=> ExpectMsgOf(hint, this, pf);
[Obsolete("Method name typo, please use ExpectMsgOf instead")]
protected T ExpectMsgPf<T>(string hint, TestKitBase probe, Func<object, T> pf)
=> ExpectMsgOf(hint, probe, pf);
/// <summary>
/// Intercept and return an exception that's expected to be thrown by the passed function value. The thrown
/// exception must be an instance of the type specified by the type parameter of this method. This method
/// invokes the passed function. If the function throws an exception that's an instance of the specified type,
/// this method returns that exception. Else, whether the passed function returns normally or completes abruptly
/// with a different exception, this method throws <see cref="ThrowsException"/>.
/// <para>
/// Also note that the difference between this method and <seealso cref="AssertThrows{T}"/> is that this method
/// returns the expected exception, so it lets you perform further assertions on that exception. By contrast,
/// the <seealso cref="AssertThrows{T}"/> indicates to the reader of the code that nothing further is expected
/// about the thrown exception other than its type. The recommended usage is to use <seealso cref="AssertThrows{T}"/>
/// by default, intercept only when you need to inspect the caught exception further.
/// </para>
/// </summary>
/// <param name="actionThatThrows">The action that should throw the expected exception</param>
/// <returns>The intercepted exception, if it is of the expected type</returns>
/// <exception cref="ThrowsException">If the passed action does not complete abruptly with an exception that's an instance of the specified type.</exception>
protected T Intercept<T>(Action actionThatThrows) where T : Exception
{
return Invoking(actionThatThrows)
.Should().ThrowExactly<T>().And;
}
protected async Task<T> InterceptAsync<T>(Func<Task> funcThatThrows) where T : Exception
{
return (await funcThatThrows.Should().ThrowExactlyAsync<T>()).And;
}
/// <summary>
/// Ensure that an expected exception is thrown by the passed function value. The thrown exception must be an
/// instance of the type specified by the type parameter of this method. This method invokes the passed
/// function. If the function throws an exception that's an instance of the specified type, this method returns
/// void. Else, whether the passed function returns normally or completes abruptly with a different
/// exception, this method throws <see cref="ThrowsException"/>.
/// <para>
/// Also note that the difference between this method and <seealso cref="Intercept{T}"/> is that this method
/// does not return the expected exception, so it does not let you perform further assertions on that exception.
/// It also indicates to the reader of the code that nothing further is expected about the thrown exception
/// other than its type. The recommended usage is to use <see cref="AssertThrows{T}"/> by default,
/// <seealso cref="Intercept{T}"/> only when you need to inspect the caught exception further.
/// </para>
/// </summary>
/// <param name="actionThatThrows">The action that should throw the expected exception</param>
/// <exception cref="ThrowsException">If the passed action does not complete abruptly with an exception that's an instance of the specified type.</exception>
protected void AssertThrows<T>(Action actionThatThrows) where T : Exception
{
Intercept<T>(actionThatThrows);
}
[Obsolete("Use AssertThrows instead.")]
protected void Intercept(Action actionThatThrows)
{
Invoking(actionThatThrows).Should().Throw<Exception>();
}
protected void MuteDeadLetters(params Type[] messageClasses)
=> MuteDeadLetters(Sys, messageClasses);
protected void MuteDeadLetters(ActorSystem sys, params Type[] messageClasses)
{
if (!sys.Log.IsDebugEnabled)
return;
Action<Type> mute =
clazz =>
sys.EventStream.Publish(
new Mute(new DeadLettersFilter(new PredicateMatcher(_ => true),
new PredicateMatcher(_ => true),
letter => clazz == typeof(object) || letter.Message.GetType() == clazz)));
if (messageClasses.Length == 0)
mute(typeof(object));
else
messageClasses.ForEach(mute);
}
}
// ReSharper disable once InconsistentNaming
}