-
Notifications
You must be signed in to change notification settings - Fork 349
Expand file tree
/
Copy pathTestRequestHandler.cs
More file actions
642 lines (576 loc) · 29.6 KB
/
TestRequestHandler.cs
File metadata and controls
642 lines (576 loc) · 29.6 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
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
// 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.Globalization;
using System.Threading;
using Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.EventHandlers;
using Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.Interfaces;
using Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.ObjectModel;
using Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.EventHandlers;
using Microsoft.VisualStudio.TestPlatform.ObjectModel;
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client;
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client.Interfaces;
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Engine;
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Engine.TesthostProtocol;
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging;
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Utilities;
using Microsoft.VisualStudio.TestPlatform.Utilities;
using Microsoft.VisualStudio.TestPlatform.Utilities.Helpers;
using Microsoft.VisualStudio.TestPlatform.Utilities.Helpers.Interfaces;
using CrossPlatResources = Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.Resources.Resources;
using ObjectModelConstants = Microsoft.VisualStudio.TestPlatform.ObjectModel.Constants;
namespace Microsoft.VisualStudio.TestPlatform.CommunicationUtilities;
/// <summary>
/// Listens inside of testhost for requests, that are sent from vstest.console. Requests are handled in <see cref="OnMessageReceived"/>
/// and responses are sent back via various methods, for example <see cref="SendExecutionComplete"/>.
/// </summary>
public class TestRequestHandler : ITestRequestHandler, IDeploymentAwareTestRequestHandler
{
private readonly int _highestSupportedVersion = ProtocolVersioning.HighestSupportedVersion;
private readonly IDataSerializer _dataSerializer;
private readonly ICommunicationEndpointFactory _communicationEndpointFactory;
private readonly JobQueue<Action> _jobQueue;
private readonly IFileHelper _fileHelper;
private readonly ManualResetEventSlim _requestSenderConnected;
private readonly ManualResetEventSlim _testHostManagerFactoryReady;
private readonly ManualResetEventSlim _sessionCompleted;
private int _protocolVersion = 1;
private ITestHostManagerFactory? _testHostManagerFactory;
private ICommunicationEndPoint? _communicationEndPoint;
private ICommunicationChannel? _channel;
private Action<Message>? _onLaunchAdapterProcessWithDebuggerAttachedAckReceived;
private Action<Message>? _onAttachDebuggerAckRecieved;
private IPathConverter _pathConverter;
private Exception? _messageProcessingUnrecoverableError;
private bool _isDisposed;
public TestHostConnectionInfo ConnectionInfo { get; set; }
string? IDeploymentAwareTestRequestHandler.LocalPath { get; set; }
string? IDeploymentAwareTestRequestHandler.RemotePath { get; set; }
public TestRequestHandler() : this(JsonDataSerializer.Instance, new CommunicationEndpointFactory())
{
}
protected TestRequestHandler(
TestHostConnectionInfo connectionInfo,
ICommunicationEndpointFactory communicationEndpointFactory,
IDataSerializer dataSerializer,
JobQueue<Action> jobQueue,
Action<Message> onLaunchAdapterProcessWithDebuggerAttachedAckReceived,
Action<Message> onAttachDebuggerAckRecieved)
{
_communicationEndpointFactory = communicationEndpointFactory;
ConnectionInfo = connectionInfo;
_dataSerializer = dataSerializer;
_requestSenderConnected = new ManualResetEventSlim(false);
_testHostManagerFactoryReady = new ManualResetEventSlim(false);
_sessionCompleted = new ManualResetEventSlim(false);
_onLaunchAdapterProcessWithDebuggerAttachedAckReceived = onLaunchAdapterProcessWithDebuggerAttachedAckReceived;
_onAttachDebuggerAckRecieved = onAttachDebuggerAckRecieved;
_jobQueue = jobQueue;
_fileHelper = new FileHelper();
_pathConverter = NullPathConverter.Instance;
}
protected TestRequestHandler(IDataSerializer dataSerializer, ICommunicationEndpointFactory communicationEndpointFactory)
{
_dataSerializer = dataSerializer;
_communicationEndpointFactory = communicationEndpointFactory;
_requestSenderConnected = new ManualResetEventSlim(false);
_sessionCompleted = new ManualResetEventSlim(false);
_testHostManagerFactoryReady = new ManualResetEventSlim(false);
_onLaunchAdapterProcessWithDebuggerAttachedAckReceived = (message) => throw new NotImplementedException();
_onAttachDebuggerAckRecieved = (message) => throw new NotImplementedException();
_jobQueue = new JobQueue<Action>(
action => action?.Invoke(),
"TestHostOperationQueue",
500,
25000000,
true,
message => EqtTrace.Error(message));
_fileHelper = new FileHelper();
_pathConverter = NullPathConverter.Instance;
}
/// <inheritdoc />
public virtual void InitializeCommunication()
{
if (this is IDeploymentAwareTestRequestHandler self)
{
var currentProcessPath = Process.GetCurrentProcess().MainModule?.FileName;
var currentProcessDirectory = !currentProcessPath.IsNullOrWhiteSpace()
? System.IO.Path.GetDirectoryName(currentProcessPath)
: null;
var remotePath = Environment.GetEnvironmentVariable("VSTEST_UWP_DEPLOY_REMOTE_PATH") ?? self.RemotePath ?? currentProcessDirectory;
var localPath = Environment.GetEnvironmentVariable("VSTEST_UWP_DEPLOY_LOCAL_PATH") ?? self.LocalPath;
if (!localPath.IsNullOrWhiteSpace()
&& !remotePath.IsNullOrWhiteSpace())
{
_pathConverter = new PathConverter(localPath, remotePath, _fileHelper);
}
}
_communicationEndPoint = _communicationEndpointFactory.Create(ConnectionInfo.Role);
_communicationEndPoint.Connected += (sender, connectedArgs) =>
{
if (!connectedArgs.Connected)
{
_requestSenderConnected.Set();
throw connectedArgs.Fault;
}
_channel = connectedArgs.Channel;
_channel.MessageReceived.Subscribe(OnMessageReceived);
_requestSenderConnected.Set();
};
_communicationEndPoint.Start(ConnectionInfo.Endpoint);
}
/// <inheritdoc />
public bool WaitForRequestSenderConnection(int connectionTimeout)
{
return _requestSenderConnected.Wait(connectionTimeout);
}
/// <inheritdoc />
public void ProcessRequests(ITestHostManagerFactory testHostManagerFactory)
{
_testHostManagerFactory = testHostManagerFactory;
_testHostManagerFactoryReady.Set();
_sessionCompleted.Wait();
}
/// <inheritdoc />
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (_isDisposed)
return;
if (disposing)
{
_communicationEndPoint?.Stop();
_channel?.Dispose();
}
_isDisposed = true;
}
/// <inheritdoc />
public void Close()
{
Dispose();
EqtTrace.Info("Closing the connection !");
}
/// <inheritdoc />
public void SendTestCases(IEnumerable<TestCase>? discoveredTestCases)
{
var updatedTestCases = _pathConverter.UpdateTestCases(discoveredTestCases, PathConversionDirection.Send);
var data = _dataSerializer.SerializePayload(MessageType.TestCasesFound, updatedTestCases, _protocolVersion);
SendData(data);
}
/// <inheritdoc />
public void SendTestRunStatistics(TestRunChangedEventArgs? testRunChangedArgs)
{
var updatedTestRunChangedEventArgs = _pathConverter.UpdateTestRunChangedEventArgs(testRunChangedArgs, PathConversionDirection.Send);
var data = _dataSerializer.SerializePayload(MessageType.TestRunStatsChange, updatedTestRunChangedEventArgs, _protocolVersion);
SendData(data);
}
/// <inheritdoc />
public void SendLog(TestMessageLevel messageLevel, string? message)
{
var data = _dataSerializer.SerializePayload(
MessageType.TestMessage,
new TestMessagePayload { MessageLevel = messageLevel, Message = message },
_protocolVersion);
SendData(data);
}
/// <inheritdoc />
public void SendExecutionComplete(
TestRunCompleteEventArgs testRunCompleteArgs,
TestRunChangedEventArgs? lastChunkArgs,
ICollection<AttachmentSet>? runContextAttachments,
ICollection<string>? executorUris)
{
// When we abort the run we might have saved the error before we gave the handler the chance to abort
// if the handler does not return with any new error we report the original one.
if (testRunCompleteArgs.IsAborted
&& testRunCompleteArgs.Error == null
&& _messageProcessingUnrecoverableError != null)
{
var curentArgs = testRunCompleteArgs;
testRunCompleteArgs = new TestRunCompleteEventArgs(
curentArgs.TestRunStatistics,
curentArgs.IsCanceled,
curentArgs.IsAborted,
_messageProcessingUnrecoverableError,
_pathConverter.UpdateAttachmentSets(curentArgs.AttachmentSets, PathConversionDirection.Send), curentArgs.InvokedDataCollectors, curentArgs.ElapsedTimeInRunningTests
);
}
var data = _dataSerializer.SerializePayload(
MessageType.ExecutionComplete,
new TestRunCompletePayload
{
TestRunCompleteArgs = _pathConverter.UpdateTestRunCompleteEventArgs(testRunCompleteArgs, PathConversionDirection.Send),
LastRunTests = _pathConverter.UpdateTestRunChangedEventArgs(lastChunkArgs, PathConversionDirection.Send),
RunAttachments = _pathConverter.UpdateAttachmentSets(runContextAttachments, PathConversionDirection.Send),
ExecutorUris = executorUris
},
_protocolVersion);
SendData(data);
}
/// <inheritdoc />
public void DiscoveryComplete(DiscoveryCompleteEventArgs discoveryCompleteEventArgs, IEnumerable<TestCase>? lastChunk)
{
var data = _dataSerializer.SerializePayload(
MessageType.DiscoveryComplete,
new DiscoveryCompletePayload
{
TotalTests = discoveryCompleteEventArgs.TotalCount,
// TODO: avoid failing when lastChunk is null
LastDiscoveredTests = discoveryCompleteEventArgs.IsAborted ? null : _pathConverter.UpdateTestCases(lastChunk!, PathConversionDirection.Send),
IsAborted = discoveryCompleteEventArgs.IsAborted,
Metrics = discoveryCompleteEventArgs.Metrics,
FullyDiscoveredSources = discoveryCompleteEventArgs.FullyDiscoveredSources,
PartiallyDiscoveredSources = discoveryCompleteEventArgs.PartiallyDiscoveredSources,
NotDiscoveredSources = discoveryCompleteEventArgs.NotDiscoveredSources,
SkippedDiscoverySources = discoveryCompleteEventArgs.SkippedDiscoveredSources,
DiscoveredExtensions = discoveryCompleteEventArgs.DiscoveredExtensions,
},
_protocolVersion);
SendData(data);
}
/// <inheritdoc />
public int LaunchProcessWithDebuggerAttached(TestProcessStartInfo? testProcessStartInfo)
{
var waitHandle = new ManualResetEventSlim(false);
Message? ackMessage = null;
_onLaunchAdapterProcessWithDebuggerAttachedAckReceived = (ackRawMessage) =>
{
ackMessage = ackRawMessage;
waitHandle.Set();
};
var data = _dataSerializer.SerializePayload(MessageType.LaunchAdapterProcessWithDebuggerAttached,
testProcessStartInfo, _protocolVersion);
SendData(data);
EqtTrace.Verbose("Waiting for LaunchAdapterProcessWithDebuggerAttached ack");
waitHandle.Wait();
_onLaunchAdapterProcessWithDebuggerAttachedAckReceived = null;
return _dataSerializer.DeserializePayload<int>(ackMessage);
}
/// <inheritdoc />
public bool AttachDebuggerToProcess(AttachDebuggerInfo attachDebuggerInfo)
{
// If an attach request is issued but there is no support for attaching on the other
// side of the communication channel, we simply return and let the caller know the
// request failed.
if (_protocolVersion < ObjectModelConstants.MinimumProtocolVersionWithDebugSupport)
{
return false;
}
Message? ackMessage = null;
var waitHandle = new ManualResetEventSlim(false);
_onAttachDebuggerAckRecieved = (ackRawMessage) =>
{
ackMessage = ackRawMessage;
waitHandle.Set();
};
var data = _dataSerializer.SerializePayload(
MessageType.AttachDebugger,
new TestProcessAttachDebuggerPayload(attachDebuggerInfo.ProcessId)
{
TargetFramework = attachDebuggerInfo.TargetFramework?.ToString(),
},
_protocolVersion);
SendData(data);
EqtTrace.Verbose("Waiting for AttachDebuggerToProcess ack ...");
waitHandle.Wait();
_onAttachDebuggerAckRecieved = null;
return _dataSerializer.DeserializePayload<bool>(ackMessage);
}
public void OnMessageReceived(object? sender, MessageReceivedEventArgs messageReceivedArgs)
{
try
{
OnMessageReceivedCore(messageReceivedArgs);
}
catch (Exception ex)
{
EqtTrace.Error("TestRequestHandler.OnMessageReceived: Failed to process message, sending ProtocolError and closing session: {0}", ex);
// Notify the caller about the error so it does not hang
// waiting for a response that will never come.
try
{
SendData(_dataSerializer.SerializePayload(MessageType.ProtocolError, ex.Message));
}
catch (Exception sendEx)
{
EqtTrace.Error("TestRequestHandler.OnMessageReceived: Failed to send ProtocolError: {0}", sendEx);
}
_sessionCompleted.Set();
Close();
}
}
private void OnMessageReceivedCore(MessageReceivedEventArgs messageReceivedArgs)
{
var message = _dataSerializer.DeserializeMessage(messageReceivedArgs.Data!);
EqtTrace.Info("TestRequestHandler.OnMessageReceived: received message: {0}", message);
switch (message?.MessageType)
{
case MessageType.VersionCheck:
try
{
var version = _dataSerializer.DeserializePayload<int>(message);
// choose the highest version that we both support
var negotiatedVersion = Math.Min(version, _highestSupportedVersion);
// BUT don't choose 3, because protocol version 3 has performance problems in 16.7.1-16.8. Those problems are caused
// by choosing payloadSerializer instead of payloadSerializer2 for protocol version 3.
//
// We cannot just update the code to choose the new serializer, because then that change would apply only to testhost.
// Testhost is is delivered by Microsoft.NET.Test.SDK nuget package, and can be used with an older vstest.console.
// An older vstest.console, that supports protocol version 3, would serialize its messages using payloadSerializer,
// but the fixed testhost would serialize it using payloadSerializer2, resulting in incompatible messages.
//
// Instead we must downgrade to protocol version 2 when 3 would be negotiated. Or higher when higher version
// would be negotiated.
if (negotiatedVersion != 3)
{
_protocolVersion = negotiatedVersion;
}
else
{
var flag = Environment.GetEnvironmentVariable("VSTEST_DISABLE_PROTOCOL_3_VERSION_DOWNGRADE");
var flagIsEnabled = flag is not null and not "0";
var dowgradeIsDisabled = flagIsEnabled;
_protocolVersion = dowgradeIsDisabled ? negotiatedVersion : 2;
}
// Send the negotiated protocol to request sender
TPDebug.Assert(_channel is not null, "_channel is null");
_channel.Send(_dataSerializer.SerializePayload(MessageType.VersionCheck, _protocolVersion));
// Can only do this after InitializeCommunication because TestHost cannot "Send Log" unless communications are initialized
if (!StringUtils.IsNullOrEmpty(EqtTrace.LogFile))
{
SendLog(TestMessageLevel.Informational, string.Format(CultureInfo.CurrentCulture, CrossPlatResources.TesthostDiagLogOutputFile, EqtTrace.LogFile));
}
else if (!StringUtils.IsNullOrEmpty(EqtTrace.ErrorOnInitialization))
{
SendLog(TestMessageLevel.Warning, EqtTrace.ErrorOnInitialization);
}
}
catch (Exception ex)
{
_messageProcessingUnrecoverableError = ex;
EqtTrace.Error("Failed processing message {0}, aborting test run.", message.MessageType);
EqtTrace.Error(ex);
goto case MessageType.AbortTestRun;
}
break;
case MessageType.DiscoveryInitialize:
{
try
{
_testHostManagerFactoryReady.Wait();
var discoveryEventsHandler = new TestDiscoveryEventHandler(this);
var path = _dataSerializer.DeserializePayload<IEnumerable<string>>(message);
TPDebug.Assert(path is not null, "path is null");
var pathToAdditionalExtensions = _pathConverter.UpdatePaths(path, PathConversionDirection.Receive);
Action job = () =>
{
EqtTrace.Info("TestRequestHandler.OnMessageReceived: Running job '{0}'.", message.MessageType);
TPDebug.Assert(_testHostManagerFactory is not null, "_testHostManagerFactory is null");
_testHostManagerFactory.GetDiscoveryManager().Initialize(pathToAdditionalExtensions, discoveryEventsHandler);
};
_jobQueue.QueueJob(job, 0);
}
catch (Exception ex)
{
_messageProcessingUnrecoverableError = ex;
EqtTrace.Error("Failed processing message {0}, aborting test run.", message.MessageType);
EqtTrace.Error(ex);
goto case MessageType.AbortTestRun;
}
break;
}
case MessageType.StartDiscovery:
{
try
{
_testHostManagerFactoryReady.Wait();
var discoveryEventsHandler = new TestDiscoveryEventHandler(this);
var discoveryCriteria = _dataSerializer.DeserializePayload<DiscoveryCriteria>(message);
TPDebug.Assert(discoveryCriteria is not null, "discoveryCriteria is null");
discoveryCriteria = _pathConverter.UpdateDiscoveryCriteria(discoveryCriteria, PathConversionDirection.Receive);
Action job = () =>
{
EqtTrace.Info("TestRequestHandler.OnMessageReceived: Running job '{0}'.", message.MessageType);
TPDebug.Assert(_testHostManagerFactory is not null, "_testHostManagerFactory is null");
_testHostManagerFactory.GetDiscoveryManager()
.DiscoverTests(discoveryCriteria, discoveryEventsHandler);
};
_jobQueue.QueueJob(job, 0);
}
catch (Exception ex)
{
_messageProcessingUnrecoverableError = ex;
EqtTrace.Error("Failed processing message {0}, aborting test run.", message.MessageType);
EqtTrace.Error(ex);
goto case MessageType.AbortTestRun;
}
break;
}
case MessageType.ExecutionInitialize:
{
try
{
_testHostManagerFactoryReady.Wait();
var testInitializeEventsHandler = new TestInitializeEventsHandler(this);
var pathToAdditionalExtensions = _dataSerializer.DeserializePayload<IEnumerable<string>>(message);
TPDebug.Assert(pathToAdditionalExtensions is not null, "pathToAdditionalExtensions is null");
pathToAdditionalExtensions = _pathConverter.UpdatePaths(pathToAdditionalExtensions, PathConversionDirection.Receive);
Action job = () =>
{
EqtTrace.Info("TestRequestHandler.OnMessageReceived: Running job '{0}'.", message.MessageType);
TPDebug.Assert(_testHostManagerFactory is not null, "_testHostManagerFactory is null");
_testHostManagerFactory.GetExecutionManager().Initialize(pathToAdditionalExtensions, testInitializeEventsHandler);
};
_jobQueue.QueueJob(job, 0);
}
catch (Exception ex)
{
_messageProcessingUnrecoverableError = ex;
EqtTrace.Error("Failed processing message {0}, aborting test run.", message.MessageType);
EqtTrace.Error(ex);
goto case MessageType.AbortTestRun;
}
break;
}
case MessageType.StartTestExecutionWithSources:
{
try
{
var testRunEventsHandler = new TestRunEventsHandler(this);
_testHostManagerFactoryReady.Wait();
var testRunCriteriaWithSources = _dataSerializer.DeserializePayload<TestRunCriteriaWithSources>(message);
TPDebug.Assert(testRunCriteriaWithSources is not null, "testRunCriteriaWithSources is null");
testRunCriteriaWithSources = _pathConverter.UpdateTestRunCriteriaWithSources(testRunCriteriaWithSources, PathConversionDirection.Receive);
Action job = () =>
{
EqtTrace.Info("TestRequestHandler.OnMessageReceived: Running job '{0}'.", message.MessageType);
TPDebug.Assert(_testHostManagerFactory is not null, "_testHostManagerFactory is null");
_testHostManagerFactory.GetExecutionManager()
.StartTestRun(
testRunCriteriaWithSources.AdapterSourceMap,
testRunCriteriaWithSources.Package,
testRunCriteriaWithSources.RunSettings,
testRunCriteriaWithSources.TestExecutionContext,
GetTestCaseEventsHandler(testRunCriteriaWithSources.RunSettings),
testRunEventsHandler);
};
_jobQueue.QueueJob(job, 0);
}
catch (Exception ex)
{
_messageProcessingUnrecoverableError = ex;
EqtTrace.Error("Failed processing message {0}, aborting test run.", message.MessageType);
EqtTrace.Error(ex);
goto case MessageType.AbortTestRun;
}
break;
}
case MessageType.StartTestExecutionWithTests:
{
try
{
var testRunEventsHandler = new TestRunEventsHandler(this);
_testHostManagerFactoryReady.Wait();
var testRunCriteriaWithTests = _dataSerializer.DeserializePayload<TestRunCriteriaWithTests>(message);
TPDebug.Assert(testRunCriteriaWithTests is not null, "testRunCriteriaWithTests is null");
testRunCriteriaWithTests = _pathConverter.UpdateTestRunCriteriaWithTests(testRunCriteriaWithTests, PathConversionDirection.Receive);
Action job = () =>
{
EqtTrace.Info("TestRequestHandler.OnMessageReceived: Running job '{0}'.", message.MessageType);
TPDebug.Assert(_testHostManagerFactory is not null, "_testHostManagerFactory is null");
_testHostManagerFactory.GetExecutionManager()
.StartTestRun(
testRunCriteriaWithTests.Tests,
testRunCriteriaWithTests.Package,
testRunCriteriaWithTests.RunSettings,
testRunCriteriaWithTests.TestExecutionContext,
GetTestCaseEventsHandler(testRunCriteriaWithTests.RunSettings),
testRunEventsHandler);
};
_jobQueue.QueueJob(job, 0);
}
catch (Exception ex)
{
_messageProcessingUnrecoverableError = ex;
EqtTrace.Error("Failed processing message {0}, aborting test run.", message.MessageType);
EqtTrace.Error(ex);
goto case MessageType.AbortTestRun;
}
break;
}
case MessageType.CancelTestRun:
_jobQueue.Pause();
_testHostManagerFactoryReady.Wait();
TPDebug.Assert(_testHostManagerFactory is not null, "_testHostManagerFactory is null");
_testHostManagerFactory.GetExecutionManager().Cancel(new TestRunEventsHandler(this));
break;
case MessageType.LaunchAdapterProcessWithDebuggerAttachedCallback:
_onLaunchAdapterProcessWithDebuggerAttachedAckReceived?.Invoke(message);
break;
case MessageType.AttachDebuggerCallback:
_onAttachDebuggerAckRecieved?.Invoke(message);
break;
case MessageType.CancelDiscovery:
_jobQueue.Pause();
_testHostManagerFactoryReady.Wait();
TPDebug.Assert(_testHostManagerFactory is not null, "_testHostManagerFactory is null");
_testHostManagerFactory.GetDiscoveryManager().Abort(new TestDiscoveryEventHandler(this));
break;
case MessageType.AbortTestRun:
try
{
_jobQueue.Pause();
_testHostManagerFactoryReady.Wait();
TPDebug.Assert(_testHostManagerFactory is not null, "_testHostManagerFactory is null");
_testHostManagerFactory.GetExecutionManager().Abort(new TestRunEventsHandler(this));
}
catch (Exception ex)
{
EqtTrace.Error("Failed processing message {0}. Stopping communication.", message.MessageType);
EqtTrace.Error(ex);
_sessionCompleted.Set();
Close();
}
break;
case MessageType.SessionEnd:
{
EqtTrace.Info("Session End message received from server. Closing the connection.");
_sessionCompleted.Set();
Close();
break;
}
case MessageType.SessionAbort:
{
// Don't do anything for now.
break;
}
default:
{
EqtTrace.Info("Invalid Message types");
break;
}
}
}
private static ITestCaseEventsHandler? GetTestCaseEventsHandler(string? runSettings)
{
ITestCaseEventsHandler? testCaseEventsHandler = null;
// Listen to test case events only if data collection is enabled
if ((XmlRunSettingsUtilities.IsDataCollectionEnabled(runSettings) && DataCollectionTestCaseEventSender.Instance != null)
|| XmlRunSettingsUtilities.IsInProcDataCollectionEnabled(runSettings))
{
testCaseEventsHandler = new TestCaseEventsHandler();
}
return testCaseEventsHandler;
}
private void SendData(string data)
{
EqtTrace.Verbose("TestRequestHandler.SendData: sending data from testhost: {0}", data);
_channel?.Send(data);
}
}