-
Notifications
You must be signed in to change notification settings - Fork 253
/
MSBuildConsumer.cs
228 lines (190 loc) · 10.5 KB
/
MSBuildConsumer.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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Globalization;
using System.Text;
using Microsoft.Testing.Platform.CommandLine;
using Microsoft.Testing.Platform.Extensions.Messages;
using Microsoft.Testing.Platform.Extensions.TestHost;
using Microsoft.Testing.Platform.Helpers;
using Microsoft.Testing.Platform.IPC.Models;
using Microsoft.Testing.Platform.MSBuild.TestPlatformExtensions.Serializers;
using Microsoft.Testing.Platform.Services;
using Microsoft.Testing.Platform.TestHost;
namespace Microsoft.Testing.Platform.MSBuild.TestPlatformExtensions;
internal class MSBuildConsumer : IDataConsumer, ITestSessionLifetimeHandler
{
private readonly IServiceProvider _serviceProvider;
private readonly ICommandLineOptions _commandLineOptions;
private MSBuildTestApplicationLifecycleCallbacks? _msBuildTestApplicationLifecycleCallbacks;
private bool _sessionEnded;
private int _totalTests;
private int _totalFailedTests;
private int _totalPassedTests;
private int _totalSkippedTests;
public MSBuildConsumer(IServiceProvider serviceProvider, ICommandLineOptions commandLineOptions)
{
_serviceProvider = serviceProvider;
_commandLineOptions = commandLineOptions;
}
public Type[] DataTypesConsumed { get; } =
[
typeof(TestNodeUpdateMessage),
typeof(TestRequestExecutionTimeInfo),
];
public string Uid => nameof(MSBuildConsumer);
public string Version => AppVersion.DefaultSemVer;
public string DisplayName => nameof(MSBuildConsumer);
public string Description => Resources.MSBuildResources.MSBuildExtensionsDescription;
public Task<bool> IsEnabledAsync()
=> Task.FromResult(_commandLineOptions.IsOptionSet(MSBuildCommandLineProvider.MSBuildNodeOptionKey));
public Task OnTestSessionStartingAsync(SessionUid sessionUid, CancellationToken cancellationToken)
{
// We get the pipe from the MSBuildTestApplicationLifecycleCallbacks only if we're enabled.
_msBuildTestApplicationLifecycleCallbacks = _serviceProvider.GetRequiredService<MSBuildTestApplicationLifecycleCallbacks>();
return Task.CompletedTask;
}
public Task OnTestSessionFinishingAsync(SessionUid sessionUid, CancellationToken cancellationToken)
{
_sessionEnded = true;
return Task.CompletedTask;
}
public async Task ConsumeAsync(IDataProducer dataProducer, IData value, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return;
}
// Avoid processing messages if the session has ended.
if (_sessionEnded)
{
return;
}
switch (value)
{
case TestNodeUpdateMessage testNodeStateChanged:
TimingProperty? timingProperty = testNodeStateChanged.TestNode.Properties.SingleOrDefault<TimingProperty>();
string? duration = timingProperty is null ? null :
ToHumanReadableDuration(timingProperty.GlobalTiming.Duration.TotalMilliseconds);
TestFileLocationProperty? testFileLocationProperty = testNodeStateChanged.TestNode.Properties.SingleOrDefault<TestFileLocationProperty>();
switch (testNodeStateChanged.TestNode.Properties.SingleOrDefault<TestNodeStateProperty>())
{
case ErrorTestNodeStateProperty errorState:
await HandleFailuresAsync(
testNodeStateChanged.TestNode.DisplayName,
isCanceled: false,
duration: duration,
errorMessage: errorState.Exception?.Message ?? errorState.Explanation,
errorStackTrace: errorState.Exception?.StackTrace,
expected: null,
actual: null,
testFileLocationProperty?.FilePath,
testFileLocationProperty?.LineSpan.Start.Line ?? 0,
cancellationToken);
break;
case FailedTestNodeStateProperty failedState:
await HandleFailuresAsync(
testNodeStateChanged.TestNode.DisplayName,
isCanceled: false,
duration: duration,
errorMessage: failedState.Exception?.Message ?? failedState.Explanation,
errorStackTrace: failedState.Exception?.StackTrace,
expected: failedState.Exception?.Data["assert.expected"] as string,
actual: failedState.Exception?.Data["assert.actual"] as string,
testFileLocationProperty?.FilePath,
testFileLocationProperty?.LineSpan.Start.Line ?? 0,
cancellationToken);
break;
case TimeoutTestNodeStateProperty timeoutState:
await HandleFailuresAsync(
testNodeStateChanged.TestNode.DisplayName,
isCanceled: true,
duration: duration,
errorMessage: timeoutState.Exception?.Message ?? timeoutState.Explanation,
errorStackTrace: timeoutState.Exception?.StackTrace,
expected: null,
actual: null,
testFileLocationProperty?.FilePath,
testFileLocationProperty?.LineSpan.Start.Line ?? 0,
cancellationToken);
break;
case CancelledTestNodeStateProperty canceledState:
await HandleFailuresAsync(
testNodeStateChanged.TestNode.DisplayName,
isCanceled: true,
duration: duration,
errorMessage: canceledState.Exception?.Message ?? canceledState.Explanation,
errorStackTrace: canceledState.Exception?.StackTrace,
expected: null,
actual: null,
testFileLocationProperty?.FilePath,
testFileLocationProperty?.LineSpan.Start.Line ?? 0,
cancellationToken);
break;
case PassedTestNodeStateProperty:
_totalTests++;
_totalPassedTests++;
break;
case SkippedTestNodeStateProperty:
_totalTests++;
_totalSkippedTests++;
break;
}
break;
case TestRequestExecutionTimeInfo testRequestExecutionTimeInfo:
await HandleSummaryAsync(testRequestExecutionTimeInfo, cancellationToken);
break;
}
}
private async Task HandleFailuresAsync(string testDisplayName, bool isCanceled, string? duration, string? errorMessage, string? errorStackTrace, string? expected, string? actual, string? codeFilePath, int lineNumber, CancellationToken cancellationToken)
{
_totalTests++;
_totalFailedTests++;
ApplicationStateGuard.Ensure(_msBuildTestApplicationLifecycleCallbacks != null);
ApplicationStateGuard.Ensure(_msBuildTestApplicationLifecycleCallbacks.PipeClient != null);
var failedTestInfoRequest = new FailedTestInfoRequest(testDisplayName, isCanceled, duration, errorMessage, errorStackTrace, expected, actual, codeFilePath, lineNumber);
await _msBuildTestApplicationLifecycleCallbacks.PipeClient.RequestReplyAsync<FailedTestInfoRequest, VoidResponse>(failedTestInfoRequest, cancellationToken);
}
private async Task HandleSummaryAsync(TestRequestExecutionTimeInfo timeInfo, CancellationToken cancellationToken)
{
string? duration = ToHumanReadableDuration(timeInfo.TimingInfo.Duration.TotalMilliseconds);
ApplicationStateGuard.Ensure(_msBuildTestApplicationLifecycleCallbacks != null);
ApplicationStateGuard.Ensure(_msBuildTestApplicationLifecycleCallbacks.PipeClient != null);
var runSummaryInfoRequest = new RunSummaryInfoRequest(_totalTests, _totalFailedTests, _totalPassedTests, _totalSkippedTests, duration);
await _msBuildTestApplicationLifecycleCallbacks.PipeClient.RequestReplyAsync<RunSummaryInfoRequest, VoidResponse>(runSummaryInfoRequest, cancellationToken);
}
private static string? ToHumanReadableDuration(double? durationInMs)
{
if (durationInMs is null or < 0)
{
return null;
}
var time = TimeSpan.FromMilliseconds(durationInMs.Value);
StringBuilder stringBuilder = new();
bool hasParentValue = false;
if (time.Days > 0)
{
stringBuilder.Append(CultureInfo.InvariantCulture, $"{time.Days}d");
hasParentValue = true;
}
if (time.Hours > 0 || hasParentValue)
{
stringBuilder.Append(CultureInfo.InvariantCulture, $"{(hasParentValue ? " " : string.Empty)}{(hasParentValue ? time.Hours.ToString(CultureInfo.InvariantCulture).PadLeft(2, '0') : time.Hours.ToString(CultureInfo.InvariantCulture))}h");
hasParentValue = true;
}
if (time.Minutes > 0 || hasParentValue)
{
stringBuilder.Append(CultureInfo.InvariantCulture, $"{(hasParentValue ? " " : string.Empty)}{(hasParentValue ? time.Minutes.ToString(CultureInfo.InvariantCulture).PadLeft(2, '0') : time.Minutes.ToString(CultureInfo.InvariantCulture))}m");
hasParentValue = true;
}
if (time.Seconds > 0 || hasParentValue)
{
stringBuilder.Append(CultureInfo.InvariantCulture, $"{(hasParentValue ? " " : string.Empty)}{(hasParentValue ? time.Seconds.ToString(CultureInfo.InvariantCulture).PadLeft(2, '0') : time.Seconds.ToString(CultureInfo.InvariantCulture))}s");
hasParentValue = true;
}
if (time.Milliseconds >= 0 || hasParentValue)
{
stringBuilder.Append(CultureInfo.InvariantCulture, $"{(hasParentValue ? " " : string.Empty)}{(hasParentValue ? time.Milliseconds.ToString(CultureInfo.InvariantCulture).PadLeft(3, '0') : time.Milliseconds.ToString(CultureInfo.InvariantCulture))}ms");
}
return stringBuilder.ToString();
}
}