-
Notifications
You must be signed in to change notification settings - Fork 353
Expand file tree
/
Copy pathVSTestTask2.cs
More file actions
321 lines (285 loc) · 12.3 KB
/
VSTestTask2.cs
File metadata and controls
321 lines (285 loc) · 12.3 KB
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
// 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;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
namespace Microsoft.TestPlatform.Build.Tasks;
public class VSTestTask2 : ToolTask, ITestTask
{
[Required]
public ITaskItem? TestFileFullPath { get; set; }
public string? VSTestSetting { get; set; }
public ITaskItem[]? VSTestTestAdapterPath { get; set; }
public string? VSTestFramework { get; set; }
public string? VSTestPlatform { get; set; }
public string? VSTestTestCaseFilter { get; set; }
public string[]? VSTestLogger { get; set; }
public bool VSTestListTests { get; set; }
public string? VSTestDiag { get; set; }
public string[]? VSTestCLIRunSettings { get; set; }
[Required]
public ITaskItem? VSTestConsolePath { get; set; }
public ITaskItem? VSTestResultsDirectory { get; set; }
public string? VSTestVerbosity { get; set; }
public string[]? VSTestCollect { get; set; }
public bool VSTestBlame { get; set; }
public bool VSTestBlameCrash { get; set; }
public string? VSTestBlameCrashDumpType { get; set; }
public bool VSTestBlameCrashCollectAlways { get; set; }
public bool VSTestBlameHang { get; set; }
public string? VSTestBlameHangDumpType { get; set; }
public string? VSTestBlameHangTimeout { get; set; }
public ITaskItem? VSTestTraceDataCollectorDirectoryPath { get; set; }
public bool VSTestNoLogo { get; set; }
public string? VSTestArtifactsProcessingMode { get; set; }
public string? VSTestSessionCorrelationId { get; set; }
protected override Encoding StandardErrorEncoding => _disableUtf8ConsoleEncoding ? base.StandardErrorEncoding : Encoding.UTF8;
protected override Encoding StandardOutputEncoding => _disableUtf8ConsoleEncoding ? base.StandardOutputEncoding : Encoding.UTF8;
private readonly string _messageSplitter = "||||";
private readonly string[] _messageSplitterArray = new[] { "||||" };
private readonly bool _disableUtf8ConsoleEncoding;
protected override string? ToolName => RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "dotnet.exe" : "dotnet";
public VSTestTask2()
{
// Unless user opted out, use UTF encoding, which we force in vstest.console.
_disableUtf8ConsoleEncoding = Environment.GetEnvironmentVariable("VSTEST_DISABLE_UTF8_CONSOLE_ENCODING") == "1";
LogStandardErrorAsError = false;
StandardOutputImportance = "Normal";
}
protected override void LogEventsFromTextOutput(string singleLine, MessageImportance messageImportance)
{
var useTerminalLogger = true;
Debug.WriteLine($"VSTESTTASK2: Received output {singleLine}, importance {messageImportance}");
if (TryGetMessage(singleLine, out string name, out string?[] data))
{
// See MSBuildLogger.cs for the messages produced.
switch (name)
{
// Forward the output we receive as messages.
case "output-info":
Log.LogMessage(MessageImportance.Low, data[0]);
break;
case "output-warning":
Log.LogWarning(data[0]);
break;
case "output-error":
Log.LogError(data[0]);
break;
case "run-cancel":
case "run-abort":
Log.LogError(data[0]);
break;
case "run-finish":
// 0 - Localized summary
// 1 - total tests
// 2 - passed tests
// 3 - skipped tests
// 4 - failed tests
// 5 - duration
var summary = data[0];
if (useTerminalLogger)
{
var message = new ExtendedBuildMessageEventArgs("TLTESTFINISH", summary, null, null, MessageImportance.High)
{
ExtendedMetadata = new Dictionary<string, string?>
{
["total"] = data[1],
["passed"] = data[2],
["skipped"] = data[3],
["failed"] = data[4],
["duration"] = data[5],
}
};
BuildEngine.LogMessageEvent(message);
}
else
{
Log.LogMessage(MessageImportance.Low, summary);
}
break;
case "test-passed":
{
// 0 - localized result indicator
// 1 - display name
// 2 - duration
// 3 - outputs
var indicator = data[0];
var displayName = data[1];
var duration = data[2];
var outputs = data[3];
double durationNumber = 0;
_ = duration != null && double.TryParse(duration, out durationNumber);
string? formattedDuration = GetFormattedDurationString(TimeSpan.FromMilliseconds(durationNumber));
var testResultWithTime = !formattedDuration.IsNullOrEmpty() ? $"{indicator} {displayName} [{formattedDuration}]" : $"{indicator} {displayName}";
var n = Environment.NewLine;
var testPassed = StringUtils.IsNullOrWhiteSpace(outputs)
? testResultWithTime
: $"{testResultWithTime}{n}Outputs:{n}{outputs}";
if (useTerminalLogger)
{
var message = new ExtendedBuildMessageEventArgs("TLTESTPASSED", testPassed, null, null, MessageImportance.High)
{
ExtendedMetadata = new Dictionary<string, string?>
{
["localizedResult"] = data[0],
["displayName"] = data[1],
}
};
BuildEngine.LogMessageEvent(message);
}
else
{
Log.LogMessage(MessageImportance.Low, testPassed);
}
}
break;
case "test-skipped":
{
// 0 - localized result indicator
// 1 - display name
var indicator = data[0];
var displayName = data[1];
var testSkipped = $"{indicator} {displayName}";
if (useTerminalLogger)
{
var message = new ExtendedBuildMessageEventArgs("TLTESTSKIPPED", testSkipped, null, null, MessageImportance.High)
{
ExtendedMetadata = new Dictionary<string, string?>
{
["localizedResult"] = data[0],
["displayName"] = data[1],
}
};
BuildEngine.LogMessageEvent(message);
}
else
{
Log.LogMessage(MessageImportance.Low, testSkipped);
}
}
break;
case "test-failed":
{
// 0 - full error
// 1 - file
// 2 - line
var fullErrorMessage = data[0];
var file = data[1];
var line = data[2];
_ = int.TryParse(line, out int lineNumber);
file ??= string.Empty;
// Report error to msbuild.
Log.LogError(null, "VSTEST1", null, file ?? string.Empty, lineNumber, 0, 0, 0, fullErrorMessage, null);
}
break;
default:
// If we get other message, forward it to binary log. In the future we can ignore this or remove the prefix, but now I want to see it.
Log.LogMessage(MessageImportance.Low, $"Unhandled message: {singleLine}");
break;
}
}
else
{
// We will receive output, such as vstest version, forward it to msbuild log.
// DO NOT call the base, it parses out the output, and if it sees "error" in any place it will log it as error
// we don't want this, we only want to log errors from the text messages we receive that start error splitter.
// base.LogEventsFromTextOutput(singleLine, messageImportance);
if (!StringUtils.IsNullOrWhiteSpace(singleLine))
{
Log.LogMessage(MessageImportance.Low, singleLine);
}
}
}
private bool TryGetMessage(string singleLine, out string name, out string?[] data)
{
if (singleLine.StartsWith(_messageSplitter))
{
var parts = singleLine.Split(_messageSplitterArray, StringSplitOptions.None);
name = parts[1];
data = parts.Skip(2).Take(parts.Length).Select(p => p?.Replace("~~~~", "\r").Replace("!!!!", "\n")).ToArray();
return true;
}
name = string.Empty;
data = Array.Empty<string>();
return false;
}
protected override string? GenerateCommandLineCommands()
{
return TestTaskUtils.CreateCommandLineArguments(this);
}
protected override string? GenerateFullPathToTool()
{
if (!ToolPath.IsNullOrEmpty())
{
return Path.Combine(Path.GetDirectoryName(Path.GetFullPath(ToolPath))!, ToolExe);
}
//TODO: https://github.com/dotnet/sdk/issues/20 Need to get the dotnet path from MSBuild?
var dhp = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH");
if (!dhp.IsNullOrEmpty())
{
var path = Path.Combine(Path.GetDirectoryName(Path.GetFullPath(dhp))!, ToolExe);
if (File.Exists(path))
{
return path;
}
}
if (File.Exists(ToolExe))
{
return Path.GetFullPath(ToolExe);
}
var values = Environment.GetEnvironmentVariable("PATH");
foreach (var p in values!.Split(Path.PathSeparator))
{
var fullPath = Path.Combine(p, ToolExe);
if (File.Exists(fullPath))
return fullPath;
}
return null;
}
/// <summary>
/// Converts the time span format to readable string.
/// </summary>
/// <param name="duration"></param>
/// <returns></returns>
internal static string? GetFormattedDurationString(TimeSpan duration)
{
if (duration == default)
{
return null;
}
var time = new List<string>();
if (duration.Days > 0)
{
time.Add("> 1d");
}
else
{
if (duration.Hours > 0)
{
time.Add(duration.Hours + "h");
}
if (duration.Minutes > 0)
{
time.Add(duration.Minutes + "m");
}
if (duration.Hours == 0)
{
if (duration.Seconds > 0)
{
time.Add(duration.Seconds + "s");
}
if (duration.Milliseconds > 0 && duration.Minutes == 0)
{
time.Add(duration.Milliseconds + "ms");
}
}
}
return time.Count == 0 ? "< 1ms" : string.Join(" ", time);
}
}