-
Notifications
You must be signed in to change notification settings - Fork 789
/
XunitTestAssemblyRunner.cs
268 lines (238 loc) · 12 KB
/
XunitTestAssemblyRunner.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
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Security;
using System.Threading;
using System.Threading.Tasks;
using Xunit.Abstractions;
namespace Xunit.Sdk
{
/// <summary>
/// The test assembly runner for xUnit.net v2 tests.
/// </summary>
public class XunitTestAssemblyRunner : TestAssemblyRunner<IXunitTestCase>
{
IAttributeInfo collectionBehaviorAttribute;
bool disableParallelization;
bool initialized;
int maxParallelThreads;
SynchronizationContext originalSyncContext;
MaxConcurrencySyncContext syncContext;
/// <summary>
/// Initializes a new instance of the <see cref="XunitTestAssemblyRunner"/> class.
/// </summary>
/// <param name="testAssembly">The assembly that contains the tests to be run.</param>
/// <param name="testCases">The test cases to be run.</param>
/// <param name="diagnosticMessageSink">The message sink to report diagnostic messages to.</param>
/// <param name="executionMessageSink">The message sink to report run status to.</param>
/// <param name="executionOptions">The user's requested execution options.</param>
public XunitTestAssemblyRunner(ITestAssembly testAssembly,
IEnumerable<IXunitTestCase> testCases,
IMessageSink diagnosticMessageSink,
IMessageSink executionMessageSink,
ITestFrameworkExecutionOptions executionOptions)
: base(testAssembly, testCases, diagnosticMessageSink, executionMessageSink, executionOptions)
{ }
/// <inheritdoc/>
public override void Dispose()
{
var disposable = syncContext as IDisposable;
if (disposable != null)
disposable.Dispose();
}
/// <inheritdoc/>
protected override string GetTestFrameworkDisplayName()
=> XunitTestFrameworkDiscoverer.DisplayName;
/// <inheritdoc/>
protected override string GetTestFrameworkEnvironment()
{
Initialize();
var testCollectionFactory = ExtensibilityPointFactory.GetXunitTestCollectionFactory(DiagnosticMessageSink, collectionBehaviorAttribute, TestAssembly);
var threadCountText = maxParallelThreads < 0 ? "unlimited" : maxParallelThreads.ToString(CultureInfo.CurrentCulture);
return string.Format(
CultureInfo.CurrentCulture,
"{0} [{1}, {2}]",
base.GetTestFrameworkEnvironment(),
testCollectionFactory.DisplayName,
disableParallelization ? "non-parallel" : string.Format(CultureInfo.CurrentCulture, "parallel ({0} threads)", threadCountText)
);
}
/// <summary>
/// Gets the synchronization context used when potentially running tests in parallel.
/// If <paramref name="maxParallelThreads"/> is greater than 0, it creates
/// and uses an instance of <see cref="T:Xunit.Sdk.MaxConcurrencySyncContext"/>.
/// </summary>
/// <param name="maxParallelThreads">The maximum number of parallel threads.</param>
protected virtual void SetupSyncContext(int maxParallelThreads)
{
if (MaxConcurrencySyncContext.IsSupported && maxParallelThreads > 0)
{
syncContext = new MaxConcurrencySyncContext(maxParallelThreads);
SetSynchronizationContext(syncContext);
}
}
/// <summary>
/// Ensures the assembly runner is initialized (sets up the collection behavior,
/// parallelization options, and test orderers from their assembly attributes).
/// </summary>
protected void Initialize()
{
if (initialized)
return;
collectionBehaviorAttribute = TestAssembly.Assembly.GetCustomAttributes(typeof(CollectionBehaviorAttribute)).SingleOrDefault();
if (collectionBehaviorAttribute != null)
{
disableParallelization = collectionBehaviorAttribute.GetNamedArgument<bool>("DisableTestParallelization");
maxParallelThreads = collectionBehaviorAttribute.GetNamedArgument<int>("MaxParallelThreads");
}
disableParallelization = ExecutionOptions.DisableParallelization() ?? disableParallelization;
maxParallelThreads = ExecutionOptions.MaxParallelThreads() ?? maxParallelThreads;
if (maxParallelThreads == 0)
maxParallelThreads = Environment.ProcessorCount;
var testCaseOrdererAttribute = TestAssembly.Assembly.GetCustomAttributes(typeof(TestCaseOrdererAttribute)).SingleOrDefault();
if (testCaseOrdererAttribute != null)
{
try
{
var testCaseOrderer = ExtensibilityPointFactory.GetTestCaseOrderer(DiagnosticMessageSink, testCaseOrdererAttribute);
if (testCaseOrderer != null)
TestCaseOrderer = testCaseOrderer;
else
{
var args = testCaseOrdererAttribute.GetConstructorArguments().Cast<string>().ToList();
DiagnosticMessageSink.OnMessage(new DiagnosticMessage("Could not find type '{0}' in {1} for assembly-level test case orderer", args[0], args[1]));
}
}
catch (Exception ex)
{
var innerEx = ex.Unwrap();
var args = testCaseOrdererAttribute.GetConstructorArguments().Cast<string>().ToList();
DiagnosticMessageSink.OnMessage(
new DiagnosticMessage(
"Assembly-level test case orderer '{0}' threw '{1}' during construction: {2}{3}{4}",
args[0],
innerEx.GetType().FullName,
innerEx.Message,
Environment.NewLine,
innerEx.StackTrace
)
);
}
}
var testCollectionOrdererAttribute = TestAssembly.Assembly.GetCustomAttributes(typeof(TestCollectionOrdererAttribute)).SingleOrDefault();
if (testCollectionOrdererAttribute != null)
{
try
{
var testCollectionOrderer = ExtensibilityPointFactory.GetTestCollectionOrderer(DiagnosticMessageSink, testCollectionOrdererAttribute);
if (testCollectionOrderer != null)
TestCollectionOrderer = testCollectionOrderer;
else
{
var args = testCollectionOrdererAttribute.GetConstructorArguments().Cast<string>().ToList();
DiagnosticMessageSink.OnMessage(new DiagnosticMessage("Could not find type '{0}' in {1} for assembly-level test collection orderer", args[0], args[1]));
}
}
catch (Exception ex)
{
var innerEx = ex.Unwrap();
var args = testCollectionOrdererAttribute.GetConstructorArguments().Cast<string>().ToList();
DiagnosticMessageSink.OnMessage(
new DiagnosticMessage(
"Assembly-level test collection orderer '{0}' threw '{1}' during construction: {2}{3}{4}",
args[0],
innerEx.GetType().FullName,
innerEx.Message,
Environment.NewLine,
innerEx.StackTrace
)
);
}
}
initialized = true;
}
/// <inheritdoc/>
protected override Task AfterTestAssemblyStartingAsync()
{
Initialize();
return CommonTasks.Completed;
}
/// <inheritdoc/>
protected override Task BeforeTestAssemblyFinishedAsync()
{
SetSynchronizationContext(originalSyncContext);
return CommonTasks.Completed;
}
/// <inheritdoc/>
protected override async Task<RunSummary> RunTestCollectionsAsync(IMessageBus messageBus, CancellationTokenSource cancellationTokenSource)
{
originalSyncContext = SynchronizationContext.Current;
if (disableParallelization)
return await base.RunTestCollectionsAsync(messageBus, cancellationTokenSource);
SetupSyncContext(maxParallelThreads);
Func<Func<Task<RunSummary>>, Task<RunSummary>> taskRunner;
if (SynchronizationContext.Current != null)
{
var scheduler = TaskScheduler.FromCurrentSynchronizationContext();
taskRunner = code => Task.Factory.StartNew(code, cancellationTokenSource.Token, TaskCreationOptions.DenyChildAttach | TaskCreationOptions.HideScheduler, scheduler).Unwrap();
}
else
taskRunner = code => Task.Run(code, cancellationTokenSource.Token);
List<Task<RunSummary>> parallel = null;
List<Func<Task<RunSummary>>> nonParallel = null;
var summaries = new List<RunSummary>();
foreach (var collection in OrderTestCollections())
{
Func<Task<RunSummary>> task = () => RunTestCollectionAsync(messageBus, collection.Item1, collection.Item2, cancellationTokenSource);
// attr is null here from our new unit test, but I'm not sure if that's expected or there's a cheaper approach here
// Current approach is trying to avoid any changes to the abstractions at all
var attr = collection.Item1.CollectionDefinition?.GetCustomAttributes(typeof(CollectionDefinitionAttribute)).SingleOrDefault();
if (attr?.GetNamedArgument<bool>(nameof(CollectionDefinitionAttribute.DisableParallelization)) == true)
{
(nonParallel ?? (nonParallel = new List<Func<Task<RunSummary>>>())).Add(task);
}
else
{
(parallel ?? (parallel = new List<Task<RunSummary>>())).Add(taskRunner(task));
}
}
if (parallel?.Count > 0)
{
foreach (var task in parallel)
{
try
{
summaries.Add(await task);
}
catch (TaskCanceledException) { }
}
}
if (nonParallel?.Count > 0)
{
foreach (var task in nonParallel)
{
try
{
summaries.Add(await taskRunner(task));
if (cancellationTokenSource.IsCancellationRequested)
break;
}
catch (TaskCanceledException) { }
}
}
return new RunSummary()
{
Total = summaries.Sum(s => s.Total),
Failed = summaries.Sum(s => s.Failed),
Skipped = summaries.Sum(s => s.Skipped)
};
}
/// <inheritdoc/>
protected override Task<RunSummary> RunTestCollectionAsync(IMessageBus messageBus, ITestCollection testCollection, IEnumerable<IXunitTestCase> testCases, CancellationTokenSource cancellationTokenSource)
=> new XunitTestCollectionRunner(testCollection, testCases, DiagnosticMessageSink, messageBus, TestCaseOrderer, new ExceptionAggregator(Aggregator), cancellationTokenSource).RunAsync();
[SecuritySafeCritical]
static void SetSynchronizationContext(SynchronizationContext context)
=> SynchronizationContext.SetSynchronizationContext(context);
}
}