-
Notifications
You must be signed in to change notification settings - Fork 323
/
TestLoggerManager.cs
656 lines (570 loc) · 22.2 KB
/
TestLoggerManager.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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
// 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.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Xml;
using Microsoft.VisualStudio.TestPlatform.Common.Exceptions;
using Microsoft.VisualStudio.TestPlatform.Common.ExtensionFramework;
using Microsoft.VisualStudio.TestPlatform.Common.Logging;
using Microsoft.VisualStudio.TestPlatform.Common.Telemetry;
using Microsoft.VisualStudio.TestPlatform.Common.Utilities;
using Microsoft.VisualStudio.TestPlatform.ObjectModel;
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client;
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Engine;
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging;
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Utilities;
using Microsoft.VisualStudio.TestPlatform.PlatformAbstractions;
using Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.Interfaces;
using CommonResources = Microsoft.VisualStudio.TestPlatform.Common.Resources.Resources;
namespace Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.Client;
/// <summary>
/// Responsible for managing logger extensions and broadcasting results
/// and error/warning/informational messages to them.
/// </summary>
internal class TestLoggerManager : ITestLoggerManager
{
/// <summary>
/// Keeps track if we are disposed.
/// </summary>
private bool _isDisposed;
/// <summary>
/// Used to keep track of which loggers have been initialized.
/// </summary>
private readonly HashSet<Type> _initializedLoggers = new();
/// <summary>
/// Test run directory.
/// </summary>
private string? _testRunDirectory;
/// <summary>
/// Target framework.
/// </summary>
private string? _targetFramework;
/// <summary>
/// TreatNoTestsAsError value;
/// </summary>
private bool _treatNoTestsAsError;
/// <summary>
/// Test Logger Events instance which will be passed to loggers when they are initialized.
/// </summary>
private readonly InternalTestLoggerEvents _loggerEvents;
/// <summary>
/// Message logger.
/// </summary>
private readonly IMessageLogger _messageLogger;
/// <summary>
/// Request data.
/// </summary>
private readonly IRequestData _requestData;
/// <summary>
/// Logger extension manager.
/// </summary>
private TestLoggerExtensionManager? _testLoggerExtensionManager;
/// <summary>
/// AssemblyLoadContext for current platform
/// </summary>
private readonly IAssemblyLoadContext _assemblyLoadContext;
/// <summary>
/// Test logger manager.
/// </summary>
/// <param name="requestData">Request Data for Providing Common Services/Data for Discovery and Execution.</param>
/// <param name="messageLogger">Message Logger.</param>
/// <param name="loggerEvents">Logger events.</param>
public TestLoggerManager(IRequestData requestData, IMessageLogger messageLogger, InternalTestLoggerEvents loggerEvents) : this(requestData, messageLogger, loggerEvents, new PlatformAssemblyLoadContext())
{
}
/// <summary>
/// Test logger manager.
/// </summary>
/// <param name="requestData"></param>
/// <param name="messageLogger"></param>
/// <param name="loggerEvents"></param>
/// <param name="assemblyLoadContext"></param>
internal TestLoggerManager(IRequestData requestData, IMessageLogger messageLogger,
InternalTestLoggerEvents loggerEvents, IAssemblyLoadContext assemblyLoadContext)
{
_requestData = requestData;
_messageLogger = messageLogger;
_testLoggerExtensionManager = null;
_loggerEvents = loggerEvents;
_assemblyLoadContext = assemblyLoadContext;
}
/// <summary>
/// Loggers initialized flag.
/// </summary>
public bool LoggersInitialized => _initializedLoggers.Count != 0;
private TestLoggerExtensionManager TestLoggerExtensionManager
{
get
{
_testLoggerExtensionManager ??= TestLoggerExtensionManager.Create(_messageLogger);
return _testLoggerExtensionManager;
}
}
/// <summary>
/// Initializes all the loggers passed by user
/// </summary>
public void Initialize(string? runSettings)
{
// Enable logger events
EnableLogging();
// Store test run directory. This runsettings is the final runsettings merging CLI args and runsettings.
_testRunDirectory = GetResultsDirectory(runSettings);
_targetFramework = GetTargetFramework(runSettings)?.Name;
_treatNoTestsAsError = GetTreatNoTestsAsError(runSettings);
var loggers = XmlRunSettingsUtilities.GetLoggerRunSettings(runSettings);
foreach (var logger in loggers?.LoggerSettingsList ?? Enumerable.Empty<LoggerSettings>())
{
// Don't add logger if its disabled.
if (!logger.IsEnabled)
{
continue;
}
var parameters = GetParametersFromConfigurationElement(logger.Configuration);
var loggerInitialized = false;
// Try initializing logger by type.
if (!StringUtils.IsNullOrWhiteSpace(logger.AssemblyQualifiedName))
{
loggerInitialized = InitializeLoggerByType(logger.AssemblyQualifiedName, logger.CodeBase!, parameters);
}
// Try initializing logger by uri.
if (!loggerInitialized &&
!StringUtils.IsNullOrWhiteSpace(logger.Uri?.ToString()))
{
loggerInitialized = InitializeLoggerByUri(logger.Uri, parameters);
}
// Try initializing logger by friendly name.
if (!loggerInitialized &&
TryGetUriFromFriendlyName(logger.FriendlyName, out var loggerUri) &&
loggerUri != null)
{
loggerInitialized = InitializeLoggerByUri(loggerUri, parameters);
}
// Output error if logger is not initialized.
if (!loggerInitialized)
{
var value = !StringUtils.IsNullOrWhiteSpace(logger.AssemblyQualifiedName)
? logger.AssemblyQualifiedName
: !StringUtils.IsNullOrWhiteSpace(logger.Uri?.ToString())
? logger.Uri.ToString()
: logger.FriendlyName;
throw new InvalidLoggerException(
string.Format(CultureInfo.CurrentCulture, CommonResources.LoggerNotFound, value));
}
}
_requestData.MetricsCollection.Add(TelemetryDataConstants.LoggerUsed, string.Join<Type>(",", _initializedLoggers.ToArray()));
}
/// <summary>
/// Handles test run message event.
/// </summary>
/// <param name="e">TestRunMessage event args.</param>
public void HandleTestRunMessage(TestRunMessageEventArgs e)
{
if (_isDisposed)
{
EqtTrace.Warning("TestLoggerManager.HandleTestRunMessage: Ignoring as the object is disposed.");
return;
}
_loggerEvents.RaiseTestRunMessage(e);
}
/// <summary>
/// Handle test run stats change event.
/// </summary>
/// <param name="e">TestRunChanged event args.</param>
public void HandleTestRunStatsChange(TestRunChangedEventArgs e)
{
if (_isDisposed)
{
EqtTrace.Warning("TestLoggerManager.HandleTestRunStatsChange: Ignoring as the object is disposed.");
return;
}
foreach (TestResult result in e.NewTestResults!)
{
_loggerEvents.RaiseTestResult(new TestResultEventArgs(result));
}
}
/// <summary>
/// Handles test run start event.
/// </summary>
/// <param name="e">TestRunStart event args.</param>
public void HandleTestRunStart(TestRunStartEventArgs e)
{
if (_isDisposed)
{
EqtTrace.Warning("TestLoggerManager.HandleTestRunStart: Ignoring as the object is disposed.");
return;
}
_loggerEvents.RaiseTestRunStart(e);
}
/// <summary>
/// Handles test run complete.
/// </summary>
/// <param name="e">TestRunComplete event args.</param>
public void HandleTestRunComplete(TestRunCompleteEventArgs e)
{
if (!_isDisposed)
{
try
{
_loggerEvents.CompleteTestRun(e.TestRunStatistics, e.IsCanceled, e.IsAborted, e.Error,
e.AttachmentSets, e.InvokedDataCollectors, e.ElapsedTimeInRunningTests);
}
finally
{
Dispose();
}
}
else
{
// Note: We are not raising warning in case testLoggerManager is disposed as HandleRawMessage and HandleTestRunComplete both can call HandleTestRunComplete.
EqtTrace.Verbose("TestLoggerManager.HandleTestRunComplete: Ignoring as the object is disposed.");
}
}
/// <summary>
/// Handles discovery message event.
/// </summary>
/// <param name="e">TestRunMessage event args.</param>
public void HandleDiscoveryMessage(TestRunMessageEventArgs e)
{
if (_isDisposed)
{
EqtTrace.Warning("TestLoggerManager.HandleDiscoveryMessage: Ignoring as the object is disposed.");
return;
}
_loggerEvents.RaiseDiscoveryMessage(e);
}
/// <summary>
/// Handle discovered tests.
/// </summary>
/// <param name="e">DiscoveredTests event args.</param>
public void HandleDiscoveredTests(DiscoveredTestsEventArgs e)
{
if (_isDisposed)
{
EqtTrace.Warning("TestLoggerManager.HandleDiscoveredTests: Ignoring as the object is disposed.");
return;
}
_loggerEvents.RaiseDiscoveredTests(e);
}
/// <summary>
/// Handles discovery complete event.
/// </summary>
/// <param name="e">DiscoveryComplete event args.</param>
public void HandleDiscoveryComplete(DiscoveryCompleteEventArgs e)
{
if (!_isDisposed)
{
try
{
_loggerEvents.RaiseDiscoveryComplete(e);
}
finally
{
Dispose();
}
}
else
{
// Note: We are not raising warning in case testLoggerManager is disposed as HandleRawMessage and HandleDiscoveryComplete both can call HandleDiscoveryComplete.
EqtTrace.Verbose("TestLoggerManager.HandleDiscoveryComplete: Ignoring as the object is disposed.");
}
}
/// <summary>
/// Handles discovery start event.
/// </summary>
/// <param name="e">DiscoveryStart event args.</param>
public void HandleDiscoveryStart(DiscoveryStartEventArgs e)
{
if (_isDisposed)
{
EqtTrace.Warning("TestLoggerManager.HandleDiscoveryStart: Ignoring as the object is disposed.");
return;
}
_loggerEvents.RaiseDiscoveryStart(e);
}
/// <summary>
/// Ensure that all pending messages are sent to the loggers.
/// </summary>
public void Dispose()
{
Dispose(true);
// Use SupressFinalize in case a subclass
// of this type implements a finalizer.
GC.SuppressFinalize(this);
}
/// <summary>
/// Initializes logger with the specified URI and parameters.
/// For ex. TfsPublisher takes parameters such as Platform, Flavor etc.
/// </summary>
/// <param name="uri">URI of the logger to add.</param>
/// <param name="parameters">Logger parameters.</param>
/// <returns>Logger Initialized flag.</returns>
internal bool InitializeLoggerByUri(Uri uri, Dictionary<string, string?>? parameters)
{
ValidateArg.NotNull(uri, nameof(uri));
CheckDisposed();
// Look up the extension and initialize it if one is found.
var extensionManager = TestLoggerExtensionManager;
var logger = extensionManager.TryGetTestExtension(uri.AbsoluteUri);
if (logger == null)
{
return false;
}
// If the logger has already been initialized just return.
if (_initializedLoggers.Contains(logger.Value.GetType()))
{
EqtTrace.Verbose("TestLoggerManager: Skipping duplicate logger initialization: {0}", logger.Value.GetType());
return true;
}
// Initialize logger.
var initialized = InitializeLogger(logger.Value, logger.Metadata.ExtensionUri, parameters);
// Add logger in initializedLoggers list.
if (initialized)
{
_initializedLoggers.Add(logger.Value.GetType());
}
return initialized;
}
/// <summary>
/// Tries to get uri of the logger corresponding to the friendly name. If no such logger exists return null.
/// </summary>
/// <param name="friendlyName">The friendly Name.</param>
/// <param name="loggerUri">The logger Uri.</param>
/// <returns><see cref="bool"/></returns>
internal bool TryGetUriFromFriendlyName(string? friendlyName, [NotNullWhen(true)] out Uri? loggerUri)
{
var extensionManager = TestLoggerExtensionManager;
foreach (var extension in extensionManager.TestExtensions)
{
if (!string.Equals(friendlyName, extension.Metadata.FriendlyName, StringComparison.OrdinalIgnoreCase))
{
continue;
}
try
{
loggerUri = new Uri(extension.Metadata.ExtensionUri);
}
catch (UriFormatException)
{
loggerUri = null;
throw new InvalidLoggerException(
string.Format(
CultureInfo.CurrentCulture,
CommonResources.LoggerUriInvalid,
extension.Metadata.ExtensionUri));
}
return true;
}
loggerUri = null;
return false;
}
/// <summary>
/// Gets the test results directory.
/// </summary>
/// <param name="runSettings">Test run settings.</param>
/// <returns>Test results directory</returns>
internal static string? GetResultsDirectory(string? runSettings)
{
string? resultsDirectory = null;
if (runSettings != null)
{
try
{
RunConfiguration runConfiguration = XmlRunSettingsUtilities.GetRunConfigurationNode(runSettings);
resultsDirectory = RunSettingsUtilities.GetTestResultsDirectory(runConfiguration);
}
catch (SettingsException se)
{
EqtTrace.Error("TestLoggerManager.GetResultsDirectory: Unable to get the test results directory: Error {0}", se);
}
}
return resultsDirectory;
}
/// <summary>
/// Gets the target framework of the test run.
/// </summary>
/// <param name="runSettings">Test run settings.</param>
/// <returns>Target framework</returns>
internal static Framework? GetTargetFramework(string? runSettings)
{
Framework? targetFramework = null;
if (runSettings != null)
{
try
{
RunConfiguration runConfiguration = XmlRunSettingsUtilities.GetRunConfigurationNode(runSettings);
targetFramework = RunSettingsUtilities.GetTargetFramework(runConfiguration);
}
catch (SettingsException se)
{
EqtTrace.Error("TestLoggerManager.GetResultsDirectory: Unable to get the target framework: Error {0}", se);
}
}
return targetFramework;
}
/// <summary>
/// Get TreatNoTestsAsError value of the test run
/// </summary>
/// <param name="runSettings"></param>
/// <returns></returns>
internal static bool GetTreatNoTestsAsError(string? runSettings)
{
return RunSettingsUtilities.GetTreatNoTestsAsError(runSettings);
}
/// <summary>
/// Enables sending of events to the loggers which are registered.
/// </summary>
/// <remarks>
/// By default events are disabled and will not be raised until this method is called.
/// This is done because during logger initialization, errors could be sent and we do not
/// want them broadcast out to the loggers until all loggers have been enabled. Without this
/// all loggers would not receive the errors which were sent prior to initialization finishing.
/// </remarks>
internal void EnableLogging()
{
CheckDisposed();
_loggerEvents.EnableEvents();
}
/// <summary>
/// Ensure that all pending messages are sent to the loggers.
/// </summary>
/// <param name="disposing">
/// The disposing.
/// </param>
protected virtual void Dispose(bool disposing)
{
if (!_isDisposed)
{
if (disposing)
{
_loggerEvents.Dispose();
}
_isDisposed = true;
}
}
/// <summary>
/// Get parameters from configuration element.
/// </summary>
/// <param name="configuration"></param>
/// <returns></returns>
private static Dictionary<string, string?> GetParametersFromConfigurationElement(XmlElement? configuration)
{
var configurationManager = new LoggerNameValueConfigurationManager(configuration);
return configurationManager.NameValuePairs;
}
/// <summary>
/// Initialize logger with the specified type and parameters.
/// </summary>
/// <param name="assemblyQualifiedName">Assembly qualified name.</param>
/// <param name="codeBase">Code base.</param>
/// <param name="parameters">Logger parameters.</param>
/// <returns>Logger Initialized flag.</returns>
private bool InitializeLoggerByType(string assemblyQualifiedName, string codeBase, Dictionary<string, string?> parameters)
{
CheckDisposed();
try
{
// Load logger assembly.
Assembly assembly = _assemblyLoadContext.LoadAssemblyFromPath(codeBase);
var loggerType =
assembly?.GetTypes()
.FirstOrDefault(x => string.Equals(x.AssemblyQualifiedName, assemblyQualifiedName));
// Create logger instance
var constructorInfo = loggerType?.GetConstructor(Type.EmptyTypes);
var logger = constructorInfo?.Invoke(new object[] { });
// Handle logger null scenario.
if (logger == null)
{
return false;
}
// If the logger has already been initialized just return.
if (_initializedLoggers.Contains(logger.GetType()))
{
EqtTrace.Verbose("TestLoggerManager: Skipping duplicate logger initialization: {0}", logger.GetType());
return true;
}
// Get Logger instance and initialize.
var initialized = InitializeLogger(logger, null, parameters);
// Add logger in initializedLoggers list.
if (initialized)
{
_initializedLoggers.Add(logger.GetType());
}
return initialized;
}
catch (Exception ex)
{
EqtTrace.Error(
"TestLoggerManager: Error occurred while initializing the Logger assemblyQualifiedName : {0}, codeBase : {1} , Exception Details : {2}", assemblyQualifiedName, codeBase, ex);
return false;
}
}
private bool InitializeLogger(object? logger, string? extensionUri, Dictionary<string, string?>? parameters)
{
if (logger == null)
{
return false;
}
try
{
switch (logger)
{
case ITestLoggerWithParameters _:
((ITestLoggerWithParameters)logger).Initialize(_loggerEvents, UpdateLoggerParameters(parameters));
break;
case ITestLogger _:
((ITestLogger)logger).Initialize(_loggerEvents, _testRunDirectory!);
break;
default:
// If logger is of different type, then logger should not be initialized.
EqtTrace.Error(
"TestLoggerManager: Incorrect logger type: {0}", logger.GetType());
return false;
}
}
catch (Exception ex)
{
var loggerUri = extensionUri.IsNullOrEmpty() ? logger.GetType().ToString() : extensionUri;
EqtTrace.Error(
"TestLoggerManager: Error while initializing logger: {0}, Exception details: {1}", loggerUri, ex);
_messageLogger.SendMessage(
TestMessageLevel.Error,
string.Format(
CultureInfo.CurrentCulture,
CommonResources.LoggerInitializationError,
extensionUri.IsNullOrEmpty() ? "type" : "uri",
extensionUri.IsNullOrEmpty() ? logger.GetType().ToString() : extensionUri,
ex));
throw new InvalidLoggerException($"Error while initializing logger: {loggerUri}, Exception details: {ex.Message}");
}
return true;
}
/// <summary>
/// Populates user supplied and default logger parameters.
/// </summary>
private Dictionary<string, string?> UpdateLoggerParameters(Dictionary<string, string?>? parameters)
{
var loggerParams = parameters is not null
? new Dictionary<string, string?>(parameters, StringComparer.OrdinalIgnoreCase)
: new Dictionary<string, string?>(StringComparer.OrdinalIgnoreCase);
// Add default logger parameters...
loggerParams[DefaultLoggerParameterNames.TestRunDirectory] = _testRunDirectory;
loggerParams[DefaultLoggerParameterNames.TargetFramework] = _targetFramework;
// Add custom logger parameters
if (_treatNoTestsAsError)
{
loggerParams[ObjectModel.Constants.TreatNoTestsAsError] = _treatNoTestsAsError.ToString();
}
return loggerParams;
}
private void CheckDisposed()
{
if (_isDisposed)
{
throw new ObjectDisposedException(typeof(TestLoggerManager).FullName);
}
}
}