-
Notifications
You must be signed in to change notification settings - Fork 323
/
TestRequestManager.cs
1653 lines (1448 loc) · 69.7 KB
/
TestRequestManager.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
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
extern alias Abstraction;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.XPath;
using Microsoft.VisualStudio.TestPlatform.Client;
using Microsoft.VisualStudio.TestPlatform.Client.RequestHelper;
using Microsoft.VisualStudio.TestPlatform.CommandLine.Internal;
using Microsoft.VisualStudio.TestPlatform.CommandLine.Processors.Utilities;
using Microsoft.VisualStudio.TestPlatform.CommandLine.Publisher;
using Microsoft.VisualStudio.TestPlatform.CommandLineUtilities;
using Microsoft.VisualStudio.TestPlatform.Common;
using Microsoft.VisualStudio.TestPlatform.Common.Interfaces;
using Microsoft.VisualStudio.TestPlatform.Common.Telemetry;
using Microsoft.VisualStudio.TestPlatform.Common.Utilities;
using Microsoft.VisualStudio.TestPlatform.CoreUtilities.Helpers;
using Microsoft.VisualStudio.TestPlatform.CoreUtilities.Tracing;
using Microsoft.VisualStudio.TestPlatform.CoreUtilities.Tracing.Interfaces;
using Microsoft.VisualStudio.TestPlatform.CrossPlatEngine;
using Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.TestRunAttachmentsProcessing;
using Microsoft.VisualStudio.TestPlatform.ObjectModel;
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client;
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client.Interfaces;
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client.Payloads;
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Engine;
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Utilities;
using Abstraction::Microsoft.VisualStudio.TestPlatform.PlatformAbstractions;
using Abstraction::Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.Interfaces;
using Microsoft.VisualStudio.TestPlatform.Utilities;
using Microsoft.VisualStudio.TestPlatform.Utilities.Helpers;
using Microsoft.VisualStudio.TestPlatform.Utilities.Helpers.Interfaces;
namespace Microsoft.VisualStudio.TestPlatform.CommandLine.TestPlatformHelpers;
/// <summary>
/// Defines the test request manger which can fire off discovery and test run requests.
/// </summary>
internal class TestRequestManager : ITestRequestManager
{
private static ITestRequestManager? s_testRequestManagerInstance;
private readonly ITestPlatform _testPlatform;
private readonly ITestPlatformEventSource _testPlatformEventSource;
// TODO: No idea what is Task supposed to buy us, Tasks start immediately on instantiation
// and the work done to produce the metrics publisher is minimal.
private readonly Task<IMetricsPublisher> _metricsPublisher;
private readonly object _syncObject = new();
private bool _isDisposed;
private bool _telemetryOptedIn;
private readonly CommandLineOptions _commandLineOptions;
private readonly TestRunResultAggregator _testRunResultAggregator;
private readonly InferHelper _inferHelper;
private readonly IProcessHelper _processHelper;
private readonly ITestRunAttachmentsProcessingManager _attachmentsProcessingManager;
private readonly IEnvironment _environment;
private readonly IEnvironmentVariableHelper _environmentVariableHelper;
/// <summary>
/// Maintains the current active execution request.
/// Assumption: There can only be one active execution request.
/// </summary>
private ITestRunRequest? _currentTestRunRequest;
/// <summary>
/// Maintains the current active discovery request.
/// Assumption: There can only be one active discovery request.
/// </summary>
private IDiscoveryRequest? _currentDiscoveryRequest;
/// <summary>
/// Guards cancellation of the current discovery request, by resetting when the request is received,
/// because the request needs time to setup and populate the _currentTestRunRequest. This might take a relatively
/// long time when the machine is slow, because the setup is called as an async task, so it needs to be processed by thread pool
/// and there might be a queue of existing tasks.
/// </summary>
private readonly ManualResetEvent _discoveryStarting = new(true);
/// <summary>
/// Maintains the current active test run attachments processing cancellation token source.
/// Assumption: There can only be one active attachments processing request.
/// </summary>
private CancellationTokenSource? _currentAttachmentsProcessingCancellationTokenSource;
/// <summary>
/// Initializes a new instance of the <see cref="TestRequestManager"/> class.
/// </summary>
public TestRequestManager()
: this(
CommandLineOptions.Instance,
TestPlatformFactory.GetTestPlatform(),
TestRunResultAggregator.Instance,
TestPlatformEventSource.Instance,
new InferHelper(AssemblyMetadataProvider.Instance),
MetricsPublisherFactory.GetMetricsPublisher(
IsTelemetryOptedIn(),
CommandLineOptions.Instance.IsDesignMode),
new ProcessHelper(),
new TestRunAttachmentsProcessingManager(TestPlatformEventSource.Instance, new DataCollectorAttachmentsProcessorsFactory()),
new PlatformEnvironment(),
new EnvironmentVariableHelper())
{
}
internal TestRequestManager(
CommandLineOptions commandLineOptions,
ITestPlatform testPlatform,
TestRunResultAggregator testRunResultAggregator,
ITestPlatformEventSource testPlatformEventSource,
InferHelper inferHelper,
Task<IMetricsPublisher> metricsPublisher,
IProcessHelper processHelper,
ITestRunAttachmentsProcessingManager attachmentsProcessingManager,
IEnvironment environment,
IEnvironmentVariableHelper environmentVariableHelper)
{
_testPlatform = testPlatform;
_commandLineOptions = commandLineOptions;
_testRunResultAggregator = testRunResultAggregator;
_testPlatformEventSource = testPlatformEventSource;
_inferHelper = inferHelper;
_metricsPublisher = metricsPublisher;
_processHelper = processHelper;
_attachmentsProcessingManager = attachmentsProcessingManager;
_environment = environment;
_environmentVariableHelper = environmentVariableHelper;
}
/// <summary>
/// Gets the test request manager instance.
/// </summary>
public static ITestRequestManager Instance
=> s_testRequestManagerInstance ??= new TestRequestManager();
#region ITestRequestManager
/// <inheritdoc />
public void InitializeExtensions(
IEnumerable<string>? pathToAdditionalExtensions,
bool skipExtensionFilters)
{
// It is possible for an Editor/IDE to keep running the runner in design mode for long
// duration. We clear the extensions cache to ensure the extensions don't get reused
// across discovery/run requests.
EqtTrace.Info("TestRequestManager.InitializeExtensions: Initialize extensions started.");
_testPlatform.ClearExtensions();
_testPlatform.UpdateExtensions(pathToAdditionalExtensions, skipExtensionFilters);
EqtTrace.Info("TestRequestManager.InitializeExtensions: Initialize extensions completed.");
}
/// <inheritdoc />
public void ResetOptions()
{
CommandLineOptions.Reset();
}
/// <inheritdoc />
public void DiscoverTests(
DiscoveryRequestPayload discoveryPayload,
ITestDiscoveryEventsRegistrar discoveryEventsRegistrar,
ProtocolConfig protocolConfig)
{
try
{
// Flag that that discovery is being initialized, so all requests to cancel discovery will wait till we set the discovery up.
_discoveryStarting.Reset();
// Make sure to run the run request inside a lock as the below section is not thread-safe.
// There can be only one discovery or execution request at a given point in time.
lock (_syncObject)
{
EqtTrace.Info("TestRequestManager.DiscoverTests: Discovery tests started.");
// TODO: Normalize rest of the data on the request as well
discoveryPayload.Sources = KnownPlatformSourceFilter.FilterKnownPlatformSources(discoveryPayload.Sources?.Distinct().ToList());
discoveryPayload.RunSettings ??= "<RunSettings></RunSettings>";
var runsettings = discoveryPayload.RunSettings;
if (discoveryPayload.TestPlatformOptions != null)
{
_telemetryOptedIn = discoveryPayload.TestPlatformOptions.CollectMetrics;
}
var requestData = GetRequestData(protocolConfig);
if (UpdateRunSettingsIfRequired(
runsettings,
discoveryPayload.Sources.ToList(),
discoveryEventsRegistrar,
isDiscovery: true,
out string updatedRunsettings,
out IDictionary<string, Architecture> sourceToArchitectureMap,
out IDictionary<string, Framework> sourceToFrameworkMap))
{
runsettings = updatedRunsettings;
}
var sourceToSourceDetailMap = discoveryPayload.Sources.Select(source => new SourceDetail
{
Source = source,
Architecture = sourceToArchitectureMap[source],
Framework = sourceToFrameworkMap[source],
}).ToDictionary(k => k.Source!);
var runConfiguration = XmlRunSettingsUtilities.GetRunConfigurationNode(runsettings);
var batchSize = runConfiguration.BatchSize;
var testCaseFilterFromRunsettings = runConfiguration.TestCaseFilter;
if (requestData.IsTelemetryOptedIn)
{
// Collect metrics.
CollectMetrics(requestData, runConfiguration);
// Collect commands.
LogCommandsTelemetryPoints(requestData);
}
// Create discovery request.
var criteria = new DiscoveryCriteria(
discoveryPayload.Sources,
batchSize,
_commandLineOptions.TestStatsEventTimeout,
runsettings,
discoveryPayload.TestSessionInfo)
{
TestCaseFilter = _commandLineOptions.TestCaseFilterValue
?? testCaseFilterFromRunsettings
};
try
{
EqtTrace.Info("TestRequestManager.DiscoverTests: Synchronization context taken");
_currentDiscoveryRequest = _testPlatform.CreateDiscoveryRequest(
requestData,
criteria,
discoveryPayload.TestPlatformOptions,
sourceToSourceDetailMap,
new EventRegistrarToWarningLoggerAdapter(discoveryEventsRegistrar));
// Discovery started, allow cancellations to proceed.
_currentDiscoveryRequest.OnDiscoveryStart += (s, e) => _discoveryStarting.Set();
discoveryEventsRegistrar?.RegisterDiscoveryEvents(_currentDiscoveryRequest);
// Notify start of discovery start.
_testPlatformEventSource.DiscoveryRequestStart();
// Start the discovery of tests and wait for completion.
_currentDiscoveryRequest.DiscoverAsync();
_currentDiscoveryRequest.WaitForCompletion();
}
finally
{
if (_currentDiscoveryRequest != null)
{
// Dispose the discovery request and unregister for events.
discoveryEventsRegistrar?.UnregisterDiscoveryEvents(_currentDiscoveryRequest);
_currentDiscoveryRequest.Dispose();
_currentDiscoveryRequest = null;
}
EqtTrace.Info("TestRequestManager.DiscoverTests: Discovery tests completed.");
_testPlatformEventSource.DiscoveryRequestStop();
// Posts the discovery complete event.
_metricsPublisher.Result.PublishMetrics(
TelemetryDataConstants.TestDiscoveryCompleteEvent,
requestData.MetricsCollection.Metrics!);
}
}
}
finally
{
_discoveryStarting.Set();
}
}
/// <inheritdoc />
public void RunTests(
TestRunRequestPayload testRunRequestPayload,
ITestHostLauncher3? testHostLauncher,
ITestRunEventsRegistrar testRunEventsRegistrar,
ProtocolConfig protocolConfig)
{
EqtTrace.Info("TestRequestManager.RunTests: run tests started.");
testRunRequestPayload.RunSettings ??= "<RunSettings></RunSettings>";
if (testRunRequestPayload.Sources != null)
{
testRunRequestPayload.Sources = KnownPlatformSourceFilter.FilterKnownPlatformSources(testRunRequestPayload.Sources);
}
var runsettings = testRunRequestPayload.RunSettings;
if (testRunRequestPayload.TestPlatformOptions != null)
{
_telemetryOptedIn = testRunRequestPayload.TestPlatformOptions.CollectMetrics;
}
var requestData = GetRequestData(protocolConfig);
// Get sources to auto detect fx and arch for both run selected or run all scenario.
var sources = GetSources(testRunRequestPayload);
if (UpdateRunSettingsIfRequired(
runsettings!,
sources!,
testRunEventsRegistrar,
isDiscovery: false,
out string updatedRunsettings,
out IDictionary<string, Architecture> sourceToArchitectureMap,
out IDictionary<string, Framework> sourceToFrameworkMap))
{
runsettings = updatedRunsettings;
}
var sourceToSourceDetailMap = sources.Select(source => new SourceDetail
{
Source = source,
Architecture = sourceToArchitectureMap[source!],
Framework = sourceToFrameworkMap[source!],
}).ToDictionary(k => k.Source!);
if (InferRunSettingsHelper.AreRunSettingsCollectorsIncompatibleWithTestSettings(runsettings))
{
throw new SettingsException(
string.Format(
CultureInfo.CurrentCulture,
Resources.Resources.RunsettingsWithDCErrorMessage,
runsettings));
}
TPDebug.Assert(runsettings is not null, "runSettings is null");
var runConfiguration = XmlRunSettingsUtilities.GetRunConfigurationNode(runsettings);
var batchSize = runConfiguration.BatchSize;
if (requestData.IsTelemetryOptedIn)
{
// Collect metrics.
CollectMetrics(requestData, runConfiguration);
// Collect commands.
LogCommandsTelemetryPoints(requestData);
// Collect data for legacy settings.
LogTelemetryForLegacySettings(requestData, runsettings);
}
// Get Fakes data collector settings.
runsettings = AddFakesConfigurationToRunsettings(sources, runsettings);
// We can have either a run that contains string as test container (usually a DLL), which is later resolved to the actual path
// and all tests that match filter are run from that container.
//
// OR we already did discovery and have a list of TestCases that have concrete test method information
// and so we only pass those. TestCase also has the test container path (usually a DLL).
TPDebug.Assert(testRunRequestPayload.Sources != null || testRunRequestPayload.TestCases != null, "testRunRequestPayload.Sources or testRunRequestPayload.TestCases is null");
TestRunCriteria runCriteria = testRunRequestPayload.Sources != null && testRunRequestPayload.Sources.Count != 0
? new TestRunCriteria(
testRunRequestPayload.Sources,
batchSize,
testRunRequestPayload.KeepAlive,
runsettings,
_commandLineOptions.TestStatsEventTimeout,
testHostLauncher,
testRunRequestPayload.TestPlatformOptions?.TestCaseFilter,
testRunRequestPayload.TestPlatformOptions?.FilterOptions,
testRunRequestPayload.TestSessionInfo,
debugEnabledForTestSession: testRunRequestPayload.TestSessionInfo != null
&& testRunRequestPayload.DebuggingEnabled)
: new TestRunCriteria(
testRunRequestPayload.TestCases!,
batchSize,
testRunRequestPayload.KeepAlive,
runsettings,
_commandLineOptions.TestStatsEventTimeout,
testHostLauncher,
testRunRequestPayload.TestSessionInfo,
debugEnabledForTestSession: testRunRequestPayload.TestSessionInfo != null
&& testRunRequestPayload.DebuggingEnabled);
// Run tests.
try
{
RunTests(
requestData,
runCriteria,
testRunEventsRegistrar,
testRunRequestPayload.TestPlatformOptions,
sourceToSourceDetailMap);
EqtTrace.Info("TestRequestManager.RunTests: run tests completed.");
}
finally
{
_testPlatformEventSource.ExecutionRequestStop();
// Post the run complete event
_metricsPublisher.Result.PublishMetrics(
TelemetryDataConstants.TestExecutionCompleteEvent,
requestData.MetricsCollection.Metrics!);
}
}
/// <inheritdoc/>
public void ProcessTestRunAttachments(
TestRunAttachmentsProcessingPayload attachmentsProcessingPayload,
ITestRunAttachmentsProcessingEventsHandler attachmentsProcessingEventsHandler,
ProtocolConfig protocolConfig)
{
EqtTrace.Info("TestRequestManager.ProcessTestRunAttachments: Test run attachments processing started.");
_telemetryOptedIn = attachmentsProcessingPayload.CollectMetrics;
var requestData = GetRequestData(protocolConfig);
// Make sure to run the run request inside a lock as the below section is not thread-safe.
// There can be only one discovery, execution or attachments processing request at a given
// point in time.
lock (_syncObject)
{
try
{
EqtTrace.Info("TestRequestManager.ProcessTestRunAttachments: Synchronization context taken.");
_testPlatformEventSource.TestRunAttachmentsProcessingRequestStart();
_currentAttachmentsProcessingCancellationTokenSource = new CancellationTokenSource();
Task task = _attachmentsProcessingManager.ProcessTestRunAttachmentsAsync(
attachmentsProcessingPayload.RunSettings,
requestData,
attachmentsProcessingPayload.Attachments!,
attachmentsProcessingPayload.InvokedDataCollectors,
attachmentsProcessingEventsHandler,
_currentAttachmentsProcessingCancellationTokenSource.Token);
task.Wait();
}
finally
{
if (_currentAttachmentsProcessingCancellationTokenSource != null)
{
_currentAttachmentsProcessingCancellationTokenSource.Dispose();
_currentAttachmentsProcessingCancellationTokenSource = null;
}
EqtTrace.Info("TestRequestManager.ProcessTestRunAttachments: Test run attachments processing completed.");
_testPlatformEventSource.TestRunAttachmentsProcessingRequestStop();
// Post the attachments processing complete event.
_metricsPublisher.Result.PublishMetrics(
TelemetryDataConstants.TestAttachmentsProcessingCompleteEvent,
requestData.MetricsCollection.Metrics!);
}
}
}
/// <inheritdoc/>
public void StartTestSession(
StartTestSessionPayload payload,
ITestHostLauncher3? testHostLauncher,
ITestSessionEventsHandler eventsHandler,
ProtocolConfig protocolConfig)
{
EqtTrace.Info("TestRequestManager.StartTestSession: Starting test session.");
if (payload.TestPlatformOptions != null)
{
_telemetryOptedIn = payload.TestPlatformOptions.CollectMetrics;
}
payload.Sources ??= new List<string>();
payload.RunSettings ??= "<RunSettings></RunSettings>";
if (UpdateRunSettingsIfRequired(
payload.RunSettings,
payload.Sources,
registrar: null,
isDiscovery: false,
out string updatedRunsettings,
out IDictionary<string, Architecture> sourceToArchitectureMap,
out IDictionary<string, Framework> sourceToFrameworkMap))
{
payload.RunSettings = updatedRunsettings;
}
var sourceToSourceDetailMap = payload.Sources.Select(source => new SourceDetail
{
Source = source,
Architecture = sourceToArchitectureMap[source],
Framework = sourceToFrameworkMap[source],
}).ToDictionary(k => k.Source!);
if (InferRunSettingsHelper.AreRunSettingsCollectorsIncompatibleWithTestSettings(payload.RunSettings))
{
throw new SettingsException(
string.Format(
CultureInfo.CurrentCulture,
Resources.Resources.RunsettingsWithDCErrorMessage,
payload.RunSettings));
}
var runConfiguration = XmlRunSettingsUtilities.GetRunConfigurationNode(payload.RunSettings);
var requestData = GetRequestData(protocolConfig);
// Collect metrics & commands.
CollectMetrics(requestData, runConfiguration);
LogCommandsTelemetryPoints(requestData);
// Get Fakes data collector settings.
payload.RunSettings = AddFakesConfigurationToRunsettings(payload.Sources, payload.RunSettings);
// Data collection is not supported yet, so no test session is spawned.
if (XmlRunSettingsUtilities.IsDataCollectionEnabled(payload.RunSettings))
{
eventsHandler.HandleStartTestSessionComplete(new()
{
TestSessionInfo = null,
Metrics = null,
});
return;
}
lock (_syncObject)
{
try
{
EqtTrace.Info("TestRequestManager.StartTestSession: Synchronization context taken.");
_testPlatformEventSource.StartTestSessionStart();
var criteria = new StartTestSessionCriteria()
{
Sources = payload.Sources,
RunSettings = payload.RunSettings,
TestHostLauncher = testHostLauncher
};
var testSessionStarted = _testPlatform.StartTestSession(requestData, criteria, eventsHandler, sourceToSourceDetailMap, new NullWarningLogger());
if (!testSessionStarted)
{
// Note: We need to send back a TestSessionComplete event, so that the caller
// completes a session start request.
// StartTestSession will invoke the HandleStartTestSessionComplete event
// if the test session is started successfully. However, if it is not started,
// HandleStartTestSessionComplete will not send an event. That's why we need
// to do it here.
eventsHandler.HandleStartTestSessionComplete(new());
EqtTrace.Warning("TestRequestManager.StartTestSession: Unable to start test session.");
}
}
finally
{
EqtTrace.Info("TestRequestManager.StartTestSession: Starting test session completed.");
_testPlatformEventSource.StartTestSessionStop();
// Post the attachments processing complete event.
_metricsPublisher.Result.PublishMetrics(
TelemetryDataConstants.StartTestSessionCompleteEvent,
requestData.MetricsCollection.Metrics!);
}
}
}
/// <inheritdoc/>
public void StopTestSession(
StopTestSessionPayload payload,
ITestSessionEventsHandler eventsHandler,
ProtocolConfig protocolConfig)
{
EqtTrace.Info("TestRequestManager.StopTestSession: Stopping test session.");
_telemetryOptedIn = payload.CollectMetrics;
var requestData = GetRequestData(protocolConfig);
lock (_syncObject)
{
try
{
EqtTrace.Info("TestRequestManager.StopTestSession: Synchronization context taken.");
_testPlatformEventSource.StopTestSessionStart();
var stopped = TestSessionPool.Instance.KillSession(payload.TestSessionInfo!, requestData);
eventsHandler.HandleStopTestSessionComplete(
new()
{
TestSessionInfo = payload.TestSessionInfo,
Metrics = stopped ? requestData.MetricsCollection.Metrics : null,
IsStopped = stopped
});
if (!stopped)
{
EqtTrace.Warning("TestRequestManager.StopTestSession: Unable to stop test session.");
}
}
finally
{
EqtTrace.Info("TestRequestManager.StopTestSession: Stopping test session completed.");
_testPlatformEventSource.StopTestSessionStop();
// Post the attachments processing complete event.
_metricsPublisher.Result.PublishMetrics(
TelemetryDataConstants.StopTestSessionCompleteEvent,
requestData.MetricsCollection.Metrics!);
}
}
}
private static void LogTelemetryForLegacySettings(IRequestData requestData, string runsettings)
{
requestData.MetricsCollection.Add(
TelemetryDataConstants.TestSettingsUsed,
InferRunSettingsHelper.IsTestSettingsEnabled(runsettings));
if (InferRunSettingsHelper.TryGetLegacySettingElements(
runsettings,
out Dictionary<string, string> legacySettingsTelemetry))
{
foreach (var ciData in legacySettingsTelemetry)
{
// We are collecting telemetry for the legacy nodes and attributes used in the runsettings.
requestData.MetricsCollection.Add(
$"{TelemetryDataConstants.LegacySettingPrefix}.{ciData.Key}",
ciData.Value);
}
}
}
/// <inheritdoc />
public void CancelTestRun()
{
EqtTrace.Info("TestRequestManager.CancelTestRun: Sending cancel request.");
_currentTestRunRequest?.CancelAsync();
}
/// <inheritdoc />
public void CancelDiscovery()
{
EqtTrace.Info("TestRequestManager.CancelDiscovery: Sending cancel request.");
// Wait for discovery request to initialize, before cancelling it, otherwise the
// _currentDiscoveryRequest might be null, because discovery did not have enough time to
// initialize and did not manage to populate _currentDiscoveryRequest yet, leading to hanging run
// that "ignores" the cancellation.
_discoveryStarting.WaitOne(3000);
_currentDiscoveryRequest?.Abort();
}
/// <inheritdoc />
public void AbortTestRun()
{
EqtTrace.Info("TestRequestManager.AbortTestRun: Sending abort request.");
_currentTestRunRequest?.Abort();
}
/// <inheritdoc/>
public void CancelTestRunAttachmentsProcessing()
{
EqtTrace.Info("TestRequestManager.CancelTestRunAttachmentsProcessing: Sending cancel request.");
_currentAttachmentsProcessingCancellationTokenSource?.Cancel();
}
#endregion
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (_isDisposed)
{
return;
}
if (disposing)
{
_metricsPublisher.Result.Dispose();
}
_isDisposed = true;
}
private bool UpdateRunSettingsIfRequired(
string runsettingsXml,
IList<string>? sources,
IBaseTestEventsRegistrar? registrar,
bool isDiscovery,
out string updatedRunSettingsXml,
out IDictionary<string, Architecture> sourceToArchitectureMap,
out IDictionary<string, Framework> sourceToFrameworkMap)
{
bool settingsUpdated = false;
updatedRunSettingsXml = runsettingsXml ?? throw new ArgumentNullException(nameof(runsettingsXml));
// TargetFramework is full CLR. Set DesignMode based on current context.
using var stream = new StringReader(runsettingsXml);
using var reader = XmlReader.Create(
stream,
XmlRunSettingsUtilities.ReaderSettings);
var document = new XmlDocument();
document.Load(reader);
var navigator = document.CreateNavigator()!;
var runConfiguration = XmlRunSettingsUtilities.GetRunConfigurationNode(runsettingsXml);
var loggerRunSettings = XmlRunSettingsUtilities.GetLoggerRunSettings(runsettingsXml)
?? new LoggerRunSettings();
// True when runsettings don't set target framework. False when runsettings force target framework
// in both cases the sourceToFrameworkMap is populated with the real frameworks as we inferred them
// from dlls. For sources like .js, we return the default framework.
var frameworkWasAutodetected = UpdateFrameworkInRunSettingsIfRequired(
document,
navigator,
sources!,
registrar,
out Framework? chosenFramework,
out sourceToFrameworkMap);
settingsUpdated |= frameworkWasAutodetected;
var frameworkSetByRunsettings = !frameworkWasAutodetected;
// Before MULTI_TFM feature the sourceToArchitectureMap and sourceToFrameworkMap were only used as informational
// to be able to do this compatibility check and print warning. And in the later steps only chosenPlatform, chosenFramework
// were used, that represented the single architecture and framework to be used.
//
// After MULTI_TFM sourceToArchitectureMap and sourceToFrameworkMap are the source of truth, and are propagated forward,
// so when we want to revert to the older behavior we need to re-enable the check, and unify all the architecture and
// framework entries to the same chosen value.
var disableMultiTfm = FeatureFlag.Instance.IsSet(FeatureFlag.VSTEST_DISABLE_MULTI_TFM_RUN);
// Choose default architecture based on the framework.
// For a run with mixed tfms enabled, or .NET "Core", the default platform architecture should be based on the process.
// This will choose x64 by default for both .NET and .NET Framework, and avoids choosing x86 for a mixed
// run, so we will run via .NET testhost.exe, and not via dotnet testhost.dll.
Architecture defaultArchitecture = Architecture.X86;
if (!disableMultiTfm
|| chosenFramework!.Name.IndexOf("netstandard", StringComparison.OrdinalIgnoreCase) >= 0
|| chosenFramework.Name.IndexOf("netcoreapp", StringComparison.OrdinalIgnoreCase) >= 0
// This is a special case for 1 version of Nuget.Frameworks that was shipped with using identifier NET5 instead of NETCoreApp5 for .NET 5.
|| chosenFramework.Name.IndexOf("net5", StringComparison.OrdinalIgnoreCase) >= 0)
{
// We are running in vstest.console that is either started via dotnet
// or via vstest.console.exe. The architecture of the current process
// determines the default architecture to use for AnyCPU dlls
// and other sources that don't dictate architecture (e.g. js files).
// This way starting 32-bit dotnet will try to run as 32-bit testhost
// using the runtime that was installed with that 32-bit dotnet SDK.
// Similarly ARM64 vstest.console will start ARM64 testhost, making sure
// that we choose the architecture that we already know we can run as.
// 64-bit SDK when running from 64-bit dotnet process.
// As default architecture we specify the expected test host architecture,
// it can be specified by user on the command line with --arch or through runsettings.
// If it's not specified by user will be filled by current processor architecture;
// should be the same as SDK.
defaultArchitecture = GetDefaultArchitecture(runConfiguration);
}
else
{
if (_environment.Architecture == PlatformArchitecture.ARM64 && _environment.OperatingSystem == PlatformOperatingSystem.Windows)
{
// For non .NET Core containers only on win ARM64 we want to run AnyCPU using current process architecture as a default
// for both vstest.console.exe and design mode scenario.
// As default architecture we specify the expected test host architecture,
// it can be specified by user on the command line with /Platform or through runsettings.
// If it's not specified by user will be filled by current processor architecture.
defaultArchitecture = GetDefaultArchitecture(runConfiguration);
}
// Other scenarios, most notably .NET Framework with MultiTFM disabled, will use the old default X86 architecture.
}
EqtTrace.Verbose($"TestRequestManager.UpdateRunSettingsIfRequired: Default architecture: {defaultArchitecture} IsDefaultTargetArchitecture: {RunSettingsHelper.Instance.IsDefaultTargetArchitecture}, Current process architecture: {_processHelper.GetCurrentProcessArchitecture()} OperatingSystem: {_environment.OperatingSystem}.");
// True when runsettings don't set platforml. False when runsettings force platform
// in both cases the sourceToArchitectureMap is populated with the real architecture as we inferred it
// from dlls. For sources like .js, we return the default architecture.
var platformWasAutodetected = UpdatePlatform(
document,
navigator,
sources,
defaultArchitecture,
out Architecture chosenPlatform,
out sourceToArchitectureMap);
settingsUpdated |= platformWasAutodetected;
var platformSetByRunsettings = !platformWasAutodetected;
// Before MULTI_TFM feature the sourceToArchitectureMap and sourceToFrameworkMap were only used as informational
// to be able to do this compatibility check and print warning. And in the later steps only chosenPlatform, chosenFramework
// were used, that represented the single architecture and framework to be used.
//
// After MULTI_TFM sourceToArchitectureMap and sourceToFrameworkMap are the source of truth, and are propagated forward,
// so when we want to revert to the older behavior we need to re-enable the check, and unify all the architecture and
// framework entries to the same chosen value.
// Do the check only when we enable MULTI_TFM and platform or framework are forced by settings, because then we maybe have some sources
// that are not compatible with the chosen settings. And do the check always when MULTI_TFM is disabled, because then we want to warn every
// time there are multiple tfms or architectures mixed.
if (disableMultiTfm || (!disableMultiTfm && (platformSetByRunsettings || frameworkSetByRunsettings)))
{
CheckSourcesForCompatibility(
chosenFramework!,
chosenPlatform,
defaultArchitecture,
sourceToArchitectureMap,
sourceToFrameworkMap,
registrar);
}
// The sourceToArchitectureMap contains the real architecture, overwrite it by the value chosen by runsettings, to force one unified platform to be used.
if (disableMultiTfm || platformSetByRunsettings)
{
// Copy the list of key, otherwise we will get collection changed exception.
var keys = sourceToArchitectureMap.Keys.ToList();
foreach (var key in keys)
{
sourceToArchitectureMap[key] = chosenPlatform;
}
}
// The sourceToFrameworkMap contains the real framework, overwrite it by the value chosen by runsettings, to force one unified framework to be used.
if (disableMultiTfm || frameworkSetByRunsettings)
{
// Copy the list of key, otherwise we will get collection changed exception.
var keys = sourceToFrameworkMap.Keys.ToList();
foreach (var key in keys)
{
sourceToFrameworkMap[key] = chosenFramework!;
}
}
settingsUpdated |= UpdateDesignMode(document, runConfiguration);
settingsUpdated |= UpdateCollectSourceInformation(document, runConfiguration);
settingsUpdated |= UpdateTargetDevice(navigator, document);
settingsUpdated |= AddOrUpdateBuiltInLoggers(document, runConfiguration, loggerRunSettings);
settingsUpdated |= AddOrUpdateBatchSize(document, runConfiguration, isDiscovery);
updatedRunSettingsXml = navigator.OuterXml;
return settingsUpdated;
Architecture GetDefaultArchitecture(RunConfiguration runConfiguration)
{
if (!RunSettingsHelper.Instance.IsDefaultTargetArchitecture)
{
return runConfiguration.TargetPlatform;
}
Architecture? defaultArchitectureFromRunsettings = runConfiguration.DefaultPlatform;
if (defaultArchitectureFromRunsettings != null)
{
return defaultArchitectureFromRunsettings.Value;
}
return TranslateToArchitecture(_processHelper.GetCurrentProcessArchitecture());
}
static Architecture TranslateToArchitecture(PlatformArchitecture targetArchitecture)
{
switch (targetArchitecture)
{
case PlatformArchitecture.X86:
return Architecture.X86;
case PlatformArchitecture.X64:
return Architecture.X64;
case PlatformArchitecture.ARM:
return Architecture.ARM;
case PlatformArchitecture.ARM64:
return Architecture.ARM64;
case PlatformArchitecture.S390x:
return Architecture.S390x;
case PlatformArchitecture.Ppc64le:
return Architecture.Ppc64le;
case PlatformArchitecture.RiscV64:
return Architecture.RiscV64;
default:
EqtTrace.Error($"TestRequestManager.TranslateToArchitecture: Unhandled architecture '{targetArchitecture}'.");
break;
}
// We prefer to not throw in case of unhandled architecture but return Default,
// it should be handled in a correct way by the callers.
return Architecture.Default;
}
}
private string AddFakesConfigurationToRunsettings(IList<string>? sources, string runsettings)
{
if (string.Equals(_environmentVariableHelper.GetEnvironmentVariable("VSTEST_SKIP_FAKES_CONFIGURATION"), "1"))
{
return runsettings;
}
TPDebug.Assert(sources is not null, "AddFakesConfigurationToRunsettings: Sources list is null.");
// TODO: Are the sources in _commandLineOptions any different from the ones we get on the request?
// because why would they be? We never pass that forward to the executor, so this probably should
// just look at sources anyway.
//
// The commandline options do not have sources in design time mode,
// and so we fall back to using sources instead.
if (_commandLineOptions.Sources.Any())
{
runsettings = GenerateFakesUtilities.GenerateFakesSettings(
_commandLineOptions,
_commandLineOptions.Sources,
runsettings);
}
else if (sources.Count > 0)
{
runsettings = GenerateFakesUtilities.GenerateFakesSettings(
_commandLineOptions,
sources,
runsettings);
}
return runsettings;
}
private bool AddOrUpdateBuiltInLoggers(
XmlDocument document,
RunConfiguration runConfiguration,
LoggerRunSettings loggerRunSettings)
{
// Update built-in logger settings if requested by the user on command line to populate
// the default assembly path to those loggers so we can find them.
bool consoleLoggerUpdated = UpdateConsoleLoggerIfExists(document, loggerRunSettings);
bool msbuildLoggerUpdated = UpdateMSBuildLoggerIfExists(document, loggerRunSettings);
bool designMode = runConfiguration.DesignModeSet
? runConfiguration.DesignMode
: _commandLineOptions.IsDesignMode;
// In design mode (under IDE) don't add the default logger, we are "logging"
// via messages to vstest console wrapper.
if (!designMode)
{
// When we are not in design mode, add one of the default loggers.
// If msbuild logger was present on the command line, we are being called from
// dotnet sdk via vstest task, and should output to msbuild. If user additionally
// specified console logger it is allowed but we won't add automatically.
if (!msbuildLoggerUpdated) // msbuild logger is not present on command line
{
if (!consoleLoggerUpdated) // console logger is not present on commandline
{
// Add console logger because that is the default
AddConsoleLogger(document, loggerRunSettings);
}
}
}
// Update is required:
// 1) in case of CLI;
// 2) in case of design mode if console logger is present in runsettings.
return !designMode || consoleLoggerUpdated || msbuildLoggerUpdated;
}
private static bool UpdateTargetDevice(
XPathNavigator navigator,
XmlDocument document)
{
if (InferRunSettingsHelper.TryGetDeviceXml(navigator, out string? deviceXml))
{
InferRunSettingsHelper.UpdateTargetDevice(document, deviceXml);
return true;
}
return false;
}
private bool UpdateCollectSourceInformation(
XmlDocument document,
RunConfiguration runConfiguration)
{
bool updateRequired = !runConfiguration.CollectSourceInformationSet;
if (updateRequired)
{
InferRunSettingsHelper.UpdateCollectSourceInformation(
document,
_commandLineOptions.ShouldCollectSourceInformation);
}
return updateRequired;
}
private bool UpdateDesignMode(XmlDocument document, RunConfiguration runConfiguration)
{
// If user is already setting DesignMode via runsettings or CLI args; we skip.
bool updateRequired = !runConfiguration.DesignModeSet;
if (updateRequired)