Repository navigation
Expand file tree
/
Copy pathTestApplicationHandlerTests.cs
More file actions
1904 lines (1626 loc) · 96.6 KB
/
Copy pathTestApplicationHandlerTests.cs
File metadata and controls
1904 lines (1626 loc) · 96.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
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Globalization;
using Microsoft.DotNet.Cli.Commands;
using Microsoft.DotNet.Cli.Commands.Run;
using Microsoft.DotNet.Cli.Commands.Test;
using Microsoft.DotNet.Cli.Commands.Test.IPC.Models;
using Microsoft.DotNet.Cli.Commands.Test.Terminal;
using TestExitCode = Microsoft.DotNet.Cli.Commands.Test.ExitCode;
namespace dotnet.Tests.CommandTests.Test;
[TestClass]
public class TestApplicationHandlerTests : IDisposable
{
// TerminalTestReporter is IDisposable and starts progress tracking via TestExecutionStarted
// inside CreateHandler. MSTest instantiates the test class per test, so disposing this list in
// Dispose() releases every reporter built for the current test.
private readonly List<IDisposable> _disposables = new();
public void Dispose()
{
foreach (var disposable in _disposables)
{
disposable.Dispose();
}
}
[TestMethod]
public void ContextualOutput_AttributesHostTextButPreservesWorkflowCommands()
{
(TestApplicationHandler handler, _, CapturingConsole console) = CreateHandler(
isHelp: false, isDiscovery: false, contextualModuleOutput: true);
handler.WriteMessage("raw output\n");
handler.WriteMessage("global::Example.Type\n");
handler.OnAzureDevOpsLogReceived(new AzureDevOpsLogMessage(null, null, "slow test\n##[warning]unchanged"));
handler.OnAzureDevOpsLogReceived(new AzureDevOpsLogMessage(null, null, "##[group]user group\n##[endgroup]"));
handler.OnDisplayMessageReceived(new DisplayMessage(null, null, DisplayMessageLevels.Warning, "host warning"));
handler.OnDisplayMessageReceived(new DisplayMessage(null, null, DisplayMessageLevels.Information, "prefix ##vso[task.logissue type=warning;]unchanged"));
handler.OnDisplayMessageReceived(new DisplayMessage(null, null, DisplayMessageLevels.Information, " ::warning::unchanged"));
handler.OnDisplayMessageReceived(new DisplayMessage(null, null, DisplayMessageLevels.Information, "prefix ##[warning]legacy"));
string[] lines = console.GetOutput().Split('\n').Select(line => line.TrimEnd('\r')).ToArray();
foreach (string text in new[] { "raw output", "global::Example.Type", "slow test", "host warning" })
{
lines.Should().Contain(line => line.Contains(TargetPath) && line.Contains(TargetFramework) && line.Contains(text));
}
lines.Should().Contain("##[warning]unchanged");
lines.Should().Contain("##[group]user group");
lines.Should().Contain("##[endgroup]");
lines.Should().Contain("prefix ##vso[task.logissue type=warning;]unchanged");
lines.Should().Contain(" ::warning::unchanged");
lines.Should().Contain("prefix ##[warning]legacy");
}
[TestMethod]
[DataRow(true)]
[DataRow(false)]
public void LiveOutputAfterDrainTimeout_IsOnlySuppressedInContextualMode(bool contextual)
{
(TestApplicationHandler handler, _, CapturingConsole console) = CreateHandler(
isHelp: false, isDiscovery: false, contextualModuleOutput: contextual);
handler.WriteLiveMessage("before timeout\n");
handler.CloseLiveOutput(timedOut: true);
handler.CloseLiveOutput(timedOut: true);
handler.WriteLiveMessage("late output\n");
handler.WriteMessage("buffered exit output\n");
string output = console.GetOutput();
output.Should().Contain("before timeout").And.Contain("buffered exit output");
if (contextual)
{
output.Should().NotContain("late output");
output.Split(CliCommandStrings.TestApplicationOutputStreamTimeout, StringSplitOptions.None)
.Should().HaveCount(2, "one contextual warning must precede the summary");
output.Should().Contain(TargetPath).And.Contain(TargetFramework);
}
else
{
output.Should().Contain("late output").And.NotContain(CliCommandStrings.TestApplicationOutputStreamTimeout);
}
}
[TestMethod]
[DataRow("net472", null, ".NET Framework 4.8", "net472|x64, runtime: net48")]
[DataRow("net48", null, ".NET Framework 4.8", "net48|x64")]
[DataRow(null, "net48", ".NET Framework 4.8", "net48|x64")]
[DataRow(null, null, ".NET Framework 4.8", "x64, runtime: net48")]
[DataRow("net472", null, ".NET Framework 4.8.1", "net472|x64, runtime: net481")]
[DataRow("net472", "net481", ".NET Framework 4.8.1", "net472|x64, runtime: net481")]
[DataRow("net481", null, ".NET Framework 4.8.1", "net481|x64")]
[DataRow("net8.0", null, ".NET 8.0.25", "net8.0|x64")]
[DataRow("net8.0-windows10.0.19041.0", null, ".NET 8.0.25", "net8.0-windows10.0.19041.0|x64")]
[DataRow("net8.0", null, ".NET 9.0.3", "net8.0|x64, runtime: net9.0")]
[DataRow(null, "net472", ".NET Framework 4.8.1", "net472|x64, runtime: net481")]
[DataRow(null, null, ".NET 8.0.25", "x64, runtime: net8.0")]
[DataRow(null, "", ".NET 8.0.25", "x64, runtime: net8.0")]
[DataRow(null, " ", ".NET 8.0.25", "x64, runtime: net8.0")]
[DataRow("net9.0", null, "Unknown runtime", "net9.0|x64, runtime: Unknown runtime")]
public void OnHandshakeReceived_KeepsTargetAndRuntimeSeparateAcrossStartResultsAndCompletion(
string? projectFramework, string? handshakeFramework, string runtimeDescription, string expectedIdentity)
{
(TestApplicationHandler handler, TerminalTestReporter reporter, CapturingConsole console) = CreateHandler(
isHelp: false, isDiscovery: false, showAssembly: true, targetFramework: projectFramework,
testApplicationSettings: TestApplicationSettings.Default with { TestResultVisibility = TestResultVisibility.All });
HandshakeMessage handshake = BuildHandshake(HandshakeMessageExecutionModes.Run);
handshake.Properties[HandshakeMessagePropertyNames.Framework] = runtimeDescription;
handshake.Properties[HandshakeMessagePropertyNames.Architecture] = "X64";
if (handshakeFramework is not null)
{
handshake.Properties[HandshakeMessagePropertyNames.TargetFramework] = handshakeFramework;
}
handler.OnHandshakeReceived(handshake, gotSupportedVersion: true).Should().BeTrue();
handler.OnTestResultsReceived(new TestResultMessages(
"exec-1", "inst-1",
[new SuccessfulTestResultMessage("passed", "Passed test", TestStates.Passed, null, null, null, null, "session")],
[new FailedTestResultMessage("failed", "Failed test", TestStates.Failed,
Duration: null, Reason: null, Exceptions: null, StandardOutput: null, ErrorOutput: null,
SessionUid: "session", Expected: null, Actual: null)]));
handler.OnTestProcessExited(TestExitCode.AtLeastOneTestFailed, string.Empty, string.Empty);
string output = console.GetOutput();
output.Split($"({expectedIdentity})", StringSplitOptions.None).Should().HaveCount(5,
"the start, both test results, and completion must use the same target/process identity");
reporter.TotalTests.Should().Be(2);
reporter.HasHandshakeFailure.Should().BeFalse();
}
[TestMethod]
public void OnHandshakeReceived_OptionalTargetMayFollowAControllerWithoutMetadata()
{
(TestApplicationHandler handler, TerminalTestReporter reporter, CapturingConsole console) = CreateHandler(
isHelp: false, isDiscovery: false, showAssembly: true, targetFramework: null);
HandshakeMessage controller = BuildHandshake(
HandshakeMessageExecutionModes.Run, hostType: HandshakeMessageHostTypes.TestHostOrchestrator);
controller.Properties[HandshakeMessagePropertyNames.Framework] = ".NET Framework 4.8.1";
handler.OnHandshakeReceived(controller, gotSupportedVersion: true).Should().BeTrue();
HandshakeMessage host = BuildHandshake(HandshakeMessageExecutionModes.Run);
host.Properties[HandshakeMessagePropertyNames.Framework] = ".NET Framework 4.8.1";
host.Properties[HandshakeMessagePropertyNames.TargetFramework] = "net472";
handler.OnHandshakeReceived(host, gotSupportedVersion: true).Should().BeTrue();
handler.OnTestProcessExited(TestExitCode.Success, string.Empty, string.Empty);
console.GetOutput().Should().Contain("(net472|x64, runtime: net481)");
reporter.HasHandshakeFailure.Should().BeFalse();
}
[TestMethod]
public void OnHandshakeReceived_TestHostTargetOverridesOrchestratorTarget()
{
(TestApplicationHandler handler, TerminalTestReporter reporter, CapturingConsole console) = CreateHandler(
isHelp: false, isDiscovery: false, showAssembly: true, targetFramework: null);
HandshakeMessage orchestrator = BuildHandshake(
HandshakeMessageExecutionModes.Run, hostType: HandshakeMessageHostTypes.TestHostOrchestrator);
orchestrator.Properties[HandshakeMessagePropertyNames.Framework] = ".NET Framework 4.8.1";
orchestrator.Properties[HandshakeMessagePropertyNames.TargetFramework] = "net481";
handler.OnHandshakeReceived(orchestrator, gotSupportedVersion: true).Should().BeTrue();
HandshakeMessage host = BuildHandshake(HandshakeMessageExecutionModes.Run);
host.Properties[HandshakeMessagePropertyNames.Framework] = ".NET Framework 4.8.1";
host.Properties[HandshakeMessagePropertyNames.TargetFramework] = "net472";
handler.OnHandshakeReceived(host, gotSupportedVersion: true).Should().BeTrue();
handler.OnTestProcessExited(TestExitCode.Success, string.Empty, string.Empty);
console.GetOutput().Should().Contain("(net472|x64, runtime: net481)");
reporter.HasHandshakeFailure.Should().BeFalse();
}
[TestMethod]
public void OnHandshakeReceived_LateOptionalTargetKeepsRetryIdentityConsistent()
{
(TestApplicationHandler handler, TerminalTestReporter reporter, CapturingConsole console) = CreateHandler(
isHelp: false, isDiscovery: false, showAssembly: true, targetFramework: null);
HandshakeMessage handshake = BuildHandshake(HandshakeMessageExecutionModes.Run);
handshake.Properties[HandshakeMessagePropertyNames.Framework] = ".NET 8.0.25";
handler.OnHandshakeReceived(handshake, gotSupportedVersion: true).Should().BeTrue();
handshake.Properties[HandshakeMessagePropertyNames.InstanceId] = "second";
handshake.Properties[HandshakeMessagePropertyNames.TargetFramework] = "net8.0";
handler.OnHandshakeReceived(handshake, gotSupportedVersion: true).Should().BeTrue();
handler.OnTestProcessExited(TestExitCode.Success, string.Empty, string.Empty);
string output = console.GetOutput();
output.Split("(x64, runtime: net8.0)", StringSplitOptions.None).Should().HaveCount(4);
output.Should().NotContain("(net8.0|x64)");
reporter.HasHandshakeFailure.Should().BeFalse();
}
/// <summary>
/// Regression test for the handler-level routing fix in https://github.com/dotnet/sdk/pull/52308
/// (linked to https://github.com/dotnet/sdk/issues/51608). When the test host process exits
/// after only a controller (non-"TestHost") handshake — i.e. <c>_receivedTestHostHandshake</c>
/// is false — <see cref="TestApplicationHandler.OnTestProcessExited"/> must route to
/// <c>HandshakeFailure</c> with the module's TargetPath and TargetFramework preserved, rather
/// than to <c>AssemblyRunCompleted</c> (which would hit the defensive empty-path fallback in
/// <c>TerminalTestReporter</c> and drop the assembly identifier from the output).
/// </summary>
[TestMethod]
public void OnTestProcessExited_WhenOnlyControllerHandshakeReceived_RoutesToHandshakeFailureWithModuleContext()
{
var capturingConsole = new CapturingConsole();
var options = new TerminalTestReporterOptions
{
AnsiMode = AnsiMode.SimpleAnsi,
ShowProgress = false,
};
using var reporter = new TerminalTestReporter(capturingConsole, options);
const string targetPath = "/repo/bin/Debug/net9.0/MyTest.dll";
const string projectPath = "/repo/MyTest.csproj";
const string targetFramework = "net9.0";
var module = new TestModule(
RunProperties: new RunProperties("dotnet", targetPath, "/repo"),
ProjectFullPath: projectPath,
TargetFramework: targetFramework,
IsTestingPlatformApplication: true,
LaunchSettings: null,
TargetPath: targetPath,
DotnetRootArchVariableName: null,
EnvironmentVariables: new Dictionary<string, string>());
var testOptions = new TestOptions(IsHelp: false, IsDiscovery: false, ListTestsFormat: TestListFormat.Text);
var handler = new TestApplicationHandler(reporter, module, testOptions);
// Controller-only handshake — hostType is not "TestHost", so _receivedTestHostHandshake stays false
// and AssemblyRunStarted is never called (so the executionId is never registered in _assemblies).
var handshake = new HandshakeMessage(new Dictionary<byte, string>
{
[HandshakeMessagePropertyNames.PID] = "1234",
[HandshakeMessagePropertyNames.Architecture] = "x64",
[HandshakeMessagePropertyNames.Framework] = ".NET 9.0.0",
[HandshakeMessagePropertyNames.OS] = "Windows",
[HandshakeMessagePropertyNames.SupportedProtocolVersions] = ProtocolConstants.SupportedVersions,
[HandshakeMessagePropertyNames.HostType] = "TestHostController",
[HandshakeMessagePropertyNames.ModulePath] = targetPath,
[HandshakeMessagePropertyNames.ExecutionId] = "exec-1",
[HandshakeMessagePropertyNames.InstanceId] = "inst-1",
});
Action handshakeAct = () => handler.OnHandshakeReceived(handshake, gotSupportedVersion: true);
handshakeAct.Should().NotThrow();
Action exitAct = () => handler.OnTestProcessExited(exitCode: 1, outputData: "stdout-line", errorData: "stderr-line");
exitAct.Should().NotThrow();
reporter.HasHandshakeFailure.Should().BeTrue();
// The handler must preserve module context (TargetPath + TargetFramework) when routing to
// HandshakeFailure. If a future regression of #52308 routes through AssemblyRunCompleted's
// defensive fallback instead, the assembly identifier would be empty and this assertion would fail.
string rendered = capturingConsole.GetOutput();
rendered.Should().Contain(targetPath);
rendered.Should().Contain(targetFramework);
rendered.Should().Contain("stdout-line");
rendered.Should().Contain("stderr-line");
}
[TestMethod]
[DataRow(false)]
[DataRow(true)]
public void OnTestProcessExited_ReportsIncompleteLiveResultsWithoutAddingRecoveredCounts(bool completeSession)
{
(TestApplicationHandler handler, TerminalTestReporter reporter, CapturingConsole console) = CreateHandler(
isHelp: false, isDiscovery: false, showAssembly: true);
handler.OnHandshakeReceived(BuildHandshake(HandshakeMessageExecutionModes.Run), gotSupportedVersion: true)
.Should().BeTrue();
handler.OnSessionEventReceived(new TestSessionEvent(SessionEventTypes.TestSessionStart, "session", "exec-1"));
handler.OnTestResultsReceived(new TestResultMessages(
"exec-1", "inst-1",
[new SuccessfulTestResultMessage("test", "Test", TestStates.Passed, null, null, null, null, "session")],
[]));
if (completeSession)
{
handler.OnSessionEventReceived(new TestSessionEvent(SessionEventTypes.TestSessionEnd, "session", "exec-1"));
}
handler.OnTestProcessExited(exitCode: 7, outputData: "Recovered 388 test results from TRX.", errorData: string.Empty);
reporter.TotalTests.Should().Be(1, "recovered artifact counts must not be added to live IPC results");
reporter.TestExecutionCompleted(DateTimeOffset.UtcNow, exitCode: 7);
string rendered = console.GetOutput();
rendered.Should().Contain("Test run summary: Failed!").And.Contain("total: 1");
rendered.Should().Contain("Recovered 388 test results from TRX.");
if (completeSession)
{
rendered.Should().NotContain("Live test results are incomplete");
}
else
{
rendered.Should().Contain("Live test results are incomplete").And.Contain("recovered");
}
}
/// <summary>
/// Backward-compat regression test. Older Microsoft.Testing.Platform versions don't include the
/// optional <see cref="HandshakeMessagePropertyNames.ExecutionMode"/> property at all (added in
/// https://github.com/microsoft/testfx/pull/8794). When the property is absent the SDK must keep
/// today's behavior and not perform any execution-mode validation.
/// </summary>
[TestMethod]
[DataRow(false, false)]
[DataRow(true, false)]
[DataRow(false, true)]
public void OnHandshakeReceived_WhenExecutionModePropertyIsAbsent_AcceptsHandshakeAndDoesNotReportFailure(bool isHelp, bool isDiscovery)
{
(TestApplicationHandler handler, TerminalTestReporter reporter, CapturingConsole console) = CreateHandler(isHelp: isHelp, isDiscovery: isDiscovery);
var handshake = BuildHandshake(executionMode: null);
bool accepted = handler.OnHandshakeReceived(handshake, gotSupportedVersion: true);
accepted.Should().BeTrue();
reporter.HasHandshakeFailure.Should().BeFalse();
console.GetOutput().Should().NotContain("MismatchingHandshakeExecutionMode");
}
[TestMethod]
[DataRow(false, false, HandshakeMessageExecutionModes.Run)]
[DataRow(true, false, HandshakeMessageExecutionModes.Help)]
[DataRow(false, true, HandshakeMessageExecutionModes.Discover)]
public void OnHandshakeReceived_WhenExecutionModeMatchesSdkExpectation_AcceptsHandshake(bool isHelp, bool isDiscovery, string executionMode)
{
(TestApplicationHandler handler, TerminalTestReporter reporter, _) = CreateHandler(isHelp: isHelp, isDiscovery: isDiscovery);
var handshake = BuildHandshake(executionMode);
bool accepted = handler.OnHandshakeReceived(handshake, gotSupportedVersion: true);
accepted.Should().BeTrue();
reporter.HasHandshakeFailure.Should().BeFalse();
}
[TestMethod]
public void OnHandshakeReceived_WithExplicitAttemptNumber_UsesReportedAttempt()
{
(TestApplicationHandler handler, TerminalTestReporter reporter, CapturingConsole console) = CreateHandler(
isHelp: false,
isDiscovery: false,
showAssembly: true);
var handshake = BuildHandshake(
executionMode: HandshakeMessageExecutionModes.Run,
attemptNumber: 3);
bool accepted = handler.OnHandshakeReceived(handshake, gotSupportedVersion: true);
accepted.Should().BeTrue();
reporter.HasHandshakeFailure.Should().BeFalse();
console.GetOutput().Should().Contain("(try 3)");
}
[TestMethod]
public void OnHandshakeReceived_WithRetryOrchestrator_EnablesRetryBeforeFirstTestHost()
{
(TestApplicationHandler handler, TerminalTestReporter reporter, CapturingConsole console) = CreateHandler(
isHelp: false,
isDiscovery: false,
showAssembly: true);
bool orchestratorAccepted = handler.OnHandshakeReceived(
BuildHandshake(
executionMode: HandshakeMessageExecutionModes.Run,
hostType: HandshakeMessageHostTypes.TestHostOrchestrator,
orchestratorFeature: "RetryOrchestrator"),
gotSupportedVersion: true);
bool testHostAccepted = handler.OnHandshakeReceived(
BuildHandshake(
executionMode: HandshakeMessageExecutionModes.Run,
attemptNumber: 1),
gotSupportedVersion: true);
orchestratorAccepted.Should().BeTrue();
testHostAccepted.Should().BeTrue();
reporter.HasHandshakeFailure.Should().BeFalse();
console.GetOutput().Should().Contain("(try 1)");
}
[TestMethod]
public void OnHandshakeReceived_WithUnknownOrchestrator_AcceptsWithoutEnablingRetry()
{
(TestApplicationHandler handler, TerminalTestReporter reporter, CapturingConsole console) = CreateHandler(
isHelp: false,
isDiscovery: false,
showAssembly: true);
bool orchestratorAccepted = handler.OnHandshakeReceived(
BuildHandshake(
executionMode: HandshakeMessageExecutionModes.Run,
hostType: HandshakeMessageHostTypes.TestHostOrchestrator,
orchestratorFeature: "FutureOrchestrator"),
gotSupportedVersion: true);
bool testHostAccepted = handler.OnHandshakeReceived(
BuildHandshake(
executionMode: HandshakeMessageExecutionModes.Run,
attemptNumber: 1),
gotSupportedVersion: true);
orchestratorAccepted.Should().BeTrue();
testHostAccepted.Should().BeTrue();
reporter.HasHandshakeFailure.Should().BeFalse();
console.GetOutput().Should().NotContain("(try 1)");
}
[TestMethod]
public void OnHandshakeReceived_WithLegacyRetrySetting_EnablesRetryBeforeFirstTestHost()
{
(TestApplicationHandler handler, TerminalTestReporter reporter, CapturingConsole console) = CreateHandler(
isHelp: false,
isDiscovery: false,
showAssembly: true,
testApplicationSettings: new TestApplicationSettings(
default,
TestResultVisibility.Failed,
SlowestTestsCount: 0,
ShowFlakyTests: true,
LegacyRetryEnabled: true));
bool accepted = handler.OnHandshakeReceived(
BuildHandshake(executionMode: HandshakeMessageExecutionModes.Run),
gotSupportedVersion: true);
accepted.Should().BeTrue();
reporter.HasHandshakeFailure.Should().BeFalse();
console.GetOutput().Should().Contain("(try 1)");
}
[TestMethod]
public void OnTestResultsReceived_WithPerApplicationVisibility_UsesModuleSetting()
{
(TestApplicationHandler handler, _, CapturingConsole console) = CreateHandler(
isHelp: false,
isDiscovery: false,
testApplicationSettings: new TestApplicationSettings(
default,
TestResultVisibility.None,
SlowestTestsCount: 0,
ShowFlakyTests: true,
LegacyRetryEnabled: false));
handler.OnHandshakeReceived(
BuildHandshake(executionMode: HandshakeMessageExecutionModes.Run),
gotSupportedVersion: true).Should().BeTrue();
handler.OnTestResultsReceived(new TestResultMessages(
ExecutionId: "exec-1",
InstanceId: "inst-1",
SuccessfulTestMessages:
[
new SuccessfulTestResultMessage(
Uid: "test-1",
DisplayName: "Hidden passing test",
State: TestStates.Passed,
Duration: 1,
Reason: null,
StandardOutput: null,
ErrorOutput: null,
SessionUid: null),
],
FailedTestMessages: []));
console.GetOutput().Should().NotContain("Hidden passing test");
}
[TestMethod]
public void OnHandshakeReceived_WithArtifactPostProcessingCapabilities_RecordsApplication()
{
var manager = new ArtifactPostProcessingManager();
(TestApplicationHandler handler, _, _) = CreateHandler(
isHelp: false,
isDiscovery: false,
artifactPostProcessingManager: manager);
var handshake = BuildHandshake(
executionMode: HandshakeMessageExecutionModes.Run,
supportedPostProcessorKinds: "microsoft.testing.trx;example.junit",
supportedPostProcessorExtensions: ".trx;.xml",
supportedTruncatedRunPostProcessorKinds: "example.junit",
supportedTruncatedRunPostProcessorExtensions: ".xml");
bool accepted = handler.OnHandshakeReceived(handshake, gotSupportedVersion: true);
accepted.Should().BeTrue();
ArtifactPostProcessingApplication application = manager.SnapshotApplications().Should().ContainSingle().Subject;
application.SupportedKinds.Should().BeEquivalentTo("microsoft.testing.trx", "example.junit");
application.SupportedExtensions.Should().BeEquivalentTo(".trx", ".xml");
application.SupportedTruncatedRunKinds.Should().BeEquivalentTo("example.junit");
application.SupportedTruncatedRunExtensions.Should().BeEquivalentTo(".xml");
}
[TestMethod]
[DataRow(false)]
[DataRow(true)]
public void OnHandshakeReceived_LaterHostTargetEnrichesControllerCapabilities(bool hostAdvertisesCapabilities)
{
var manager = new ArtifactPostProcessingManager();
(TestApplicationHandler handler, _, _) = CreateHandler(
isHelp: false, isDiscovery: false, artifactPostProcessingManager: manager, targetFramework: null);
HandshakeMessage controller = BuildHandshake(
HandshakeMessageExecutionModes.Run,
hostType: "TestHostController",
includeInstanceId: false,
supportedPostProcessorKinds: "microsoft.testing.trx");
controller.Properties[HandshakeMessagePropertyNames.Framework] = ".NET Framework 4.8.1";
handler.OnHandshakeReceived(controller, gotSupportedVersion: true).Should().BeTrue();
manager.SnapshotApplications().Should().ContainSingle().Which.TargetFramework.Should().BeNull();
HandshakeMessage host = BuildHandshake(
HandshakeMessageExecutionModes.Run,
supportedPostProcessorKinds: hostAdvertisesCapabilities ? "example.junit" : null);
host.Properties[HandshakeMessagePropertyNames.Framework] = ".NET Framework 4.8.1";
host.Properties[HandshakeMessagePropertyNames.TargetFramework] = "net472";
handler.OnHandshakeReceived(host, gotSupportedVersion: true).Should().BeTrue();
ArtifactPostProcessingApplication application = manager.SnapshotApplications().Should().ContainSingle().Subject;
application.TargetFramework.Should().Be("net472");
string[] expectedKinds = hostAdvertisesCapabilities ? ["microsoft.testing.trx", "example.junit"] : ["microsoft.testing.trx"];
application.SupportedKinds.Should().BeEquivalentTo(expectedKinds);
}
[TestMethod]
public void OnFileArtifactsReceived_RecordsArtifactMetadata()
{
var manager = new ArtifactPostProcessingManager();
(TestApplicationHandler handler, _, _) = CreateHandler(
isHelp: false,
isDiscovery: false,
artifactPostProcessingManager: manager);
handler.OnHandshakeReceived(
BuildHandshake(HandshakeMessageExecutionModes.Run),
gotSupportedVersion: true).Should().BeTrue();
string artifactPath = Path.GetFullPath("result.trx");
handler.OnFileArtifactsReceived(new FileArtifactMessages(
"exec-1",
"inst-1",
[new FileArtifactMessage(artifactPath, "TRX", null, null, null, null, "microsoft.testing.trx")]));
ArtifactPostProcessingArtifact artifact = manager.SnapshotArtifacts().Should().ContainSingle().Subject;
artifact.Path.Should().Be(artifactPath);
artifact.Kind.Should().Be("microsoft.testing.trx");
artifact.ProducingTestModule.Should().Be(TargetPath);
artifact.TargetFramework.Should().Be(TargetFramework);
artifact.Architecture.Should().Be("x64");
artifact.ExecutionId.Should().Be("exec-1");
}
[TestMethod]
[DataRow("net472", null, "net472")]
[DataRow(null, "net472", "net472")]
[DataRow(null, null, null)]
public void OnFileArtifactsReceived_UsesOnlyKnownTargetMetadata(
string? projectFramework, string? handshakeFramework, string? expectedFramework)
{
var manager = new ArtifactPostProcessingManager();
(TestApplicationHandler handler, _, _) = CreateHandler(
isHelp: false, isDiscovery: false, artifactPostProcessingManager: manager, targetFramework: projectFramework);
HandshakeMessage handshake = BuildHandshake(
HandshakeMessageExecutionModes.Run, supportedPostProcessorKinds: "microsoft.testing.trx");
handshake.Properties[HandshakeMessagePropertyNames.Framework] = ".NET Framework 4.8.1";
if (handshakeFramework is not null)
{
handshake.Properties[HandshakeMessagePropertyNames.TargetFramework] = handshakeFramework;
}
handler.OnHandshakeReceived(handshake, gotSupportedVersion: true).Should().BeTrue();
handler.OnFileArtifactsReceived(new FileArtifactMessages(
"exec-1", "inst-1",
[new FileArtifactMessage(Path.GetFullPath("result.trx"), "TRX", null, null, null, null, "microsoft.testing.trx")]));
manager.SnapshotApplications().Should().ContainSingle().Which.TargetFramework.Should().Be(expectedFramework);
manager.SnapshotArtifacts().Should().ContainSingle().Which.TargetFramework.Should().Be(expectedFramework);
}
[TestMethod]
public void OnFileArtifactsReceived_UsesHandshakeModuleIdentityRatherThanLaunchPath()
{
var manager = new ArtifactPostProcessingManager();
(TestApplicationHandler handler, _, _) = CreateHandler(
isHelp: false, isDiscovery: false, artifactPostProcessingManager: manager);
HandshakeMessage handshake = BuildHandshake(
HandshakeMessageExecutionModes.Run, supportedPostProcessorKinds: "example.summary");
string modulePath = Path.GetFullPath("AssemblyBehindAppHost.dll");
handshake.Properties[HandshakeMessagePropertyNames.ModulePath] = modulePath;
handler.OnHandshakeReceived(handshake, gotSupportedVersion: true).Should().BeTrue();
handler.OnFileArtifactsReceived(new FileArtifactMessages(
"exec-1", "inst-1",
[new FileArtifactMessage(Path.GetFullPath("summary.json"), "Summary", null, null, null, null, "example.summary")]));
manager.SnapshotArtifacts().Should().ContainSingle().Which.ProducingTestModule.Should().Be(modulePath);
manager.SnapshotApplications().Should().ContainSingle().Which.ProducingTestModule.Should().Be(modulePath);
}
[TestMethod]
public void OnFileArtifactsReceived_DuringArtifactPostProcessing_RecordsInputProvenance()
{
var invocation = new ArtifactPostProcessingInvocation("manifest.json");
(TestApplicationHandler handler, _, _) = CreateHandler(
isHelp: false,
isDiscovery: false,
artifactPostProcessingInvocation: invocation);
handler.OnHandshakeReceived(
BuildHandshake(
HandshakeMessageExecutionModes.Tool,
hostType: HandshakeMessageHostTypes.ArtifactPostProcessor,
includeInstanceId: false),
gotSupportedVersion: true).Should().BeTrue();
string outputPath = Path.GetFullPath("merged.trx");
string[] inputPaths = [Path.GetFullPath("first.trx"), Path.GetFullPath("second.trx")];
handler.OnFileArtifactsReceived(new FileArtifactMessages(
"exec-1",
"inst-1",
[new FileArtifactMessage(outputPath, "Merged TRX", null, null, null, null, "microsoft.testing.trx", inputPaths)]));
ArtifactPostProcessingArtifact output = invocation.SnapshotOutputs().Should().ContainSingle().Subject;
output.Path.Should().Be(outputPath);
output.InputArtifactPaths.Should().Equal(inputPaths);
}
[TestMethod]
public void OnHandshakeReceived_WhenArtifactPostProcessorHandshakeFails_DoesNotFailTestRun()
{
var invocation = new ArtifactPostProcessingInvocation("manifest.json");
(TestApplicationHandler handler, TerminalTestReporter reporter, _) = CreateHandler(
isHelp: false,
isDiscovery: false,
artifactPostProcessingInvocation: invocation);
bool accepted = handler.OnHandshakeReceived(
BuildHandshake(
HandshakeMessageExecutionModes.Tool,
hostType: HandshakeMessageHostTypes.TestHost),
gotSupportedVersion: true);
accepted.Should().BeFalse();
invocation.FailureMessage.Should().NotBeNullOrEmpty();
reporter.HasHandshakeFailure.Should().BeFalse(
"post-processing failures must not change the test run exit code");
}
[TestMethod]
public void OnTestProcessExited_WorkerWithoutHandshake_RecordsReportingFailureOnly()
{
var invocation = new ArtifactPostProcessingInvocation("manifest.json");
(TestApplicationHandler handler, TerminalTestReporter reporter, _) = CreateHandler(
isHelp: false, isDiscovery: false, artifactPostProcessingInvocation: invocation);
handler.OnTestProcessExited(0, string.Empty, string.Empty);
invocation.FailureMessage.Should().Be(CliCommandStrings.ArtifactPostProcessingMissingHandshake);
reporter.HasHandshakeFailure.Should().BeFalse();
reporter.TotalTests.Should().Be(0);
}
[TestMethod]
public void OnTestProcessExited_WorkerWithSuccessfulHandshakeAndNullOutput_IsNotAFailure()
{
var invocation = new ArtifactPostProcessingInvocation("manifest.json");
(TestApplicationHandler handler, TerminalTestReporter reporter, _) = CreateHandler(
isHelp: false, isDiscovery: false, artifactPostProcessingInvocation: invocation);
handler.OnHandshakeReceived(
BuildHandshake(HandshakeMessageExecutionModes.Tool, hostType: HandshakeMessageHostTypes.ArtifactPostProcessor),
gotSupportedVersion: true).Should().BeTrue();
handler.OnTestProcessExited(0, string.Empty, string.Empty);
invocation.FailureMessage.Should().BeNull();
invocation.SnapshotOutputs().Should().BeEmpty();
reporter.HasHandshakeFailure.Should().BeFalse();
reporter.TotalTests.Should().Be(0);
}
/// <summary>
/// Drives the new validation added in this change: if the host reports an execution mode that
/// doesn't match what <c>dotnet test</c> intended (e.g. <c>RunArguments</c> or
/// <c>launchSettings.json</c> injected a <c>--help</c> or <c>--list-tests</c> option), the SDK
/// must reject the handshake at the protocol level and report the mismatch.
/// </summary>
[TestMethod]
[DataRow(false, false, HandshakeMessageExecutionModes.Help, HandshakeMessageExecutionModes.Run)]
[DataRow(false, false, HandshakeMessageExecutionModes.Discover, HandshakeMessageExecutionModes.Run)]
[DataRow(true, false, HandshakeMessageExecutionModes.Run, HandshakeMessageExecutionModes.Help)]
[DataRow(false, true, HandshakeMessageExecutionModes.Run, HandshakeMessageExecutionModes.Discover)]
public void OnHandshakeReceived_WhenExecutionModeMismatch_RejectsHandshakeAndReportsFailure(
bool isHelp, bool isDiscovery, string reportedMode, string expectedMode)
{
(TestApplicationHandler handler, TerminalTestReporter reporter, CapturingConsole console) = CreateHandler(isHelp: isHelp, isDiscovery: isDiscovery);
var handshake = BuildHandshake(reportedMode);
bool accepted = handler.OnHandshakeReceived(handshake, gotSupportedVersion: true);
accepted.Should().BeFalse();
reporter.HasHandshakeFailure.Should().BeTrue();
string rendered = console.GetOutput();
rendered.Should().Contain(reportedMode);
rendered.Should().Contain(expectedMode);
}
[TestMethod]
public void ContextualSummary_DoesNotCountRejectedHostAsMultipleModules()
{
(TestApplicationHandler handler, TerminalTestReporter reporter, CapturingConsole console) = CreateHandler(
isHelp: false, isDiscovery: false, contextualModuleOutput: true);
handler.OnHandshakeReceived(BuildHandshake(HandshakeMessageExecutionModes.Help), gotSupportedVersion: true)
.Should().BeFalse();
handler.OnTestProcessExited(TestExitCode.GenericFailure, string.Empty, string.Empty);
reporter.TestExecutionCompleted(DateTimeOffset.UtcNow, TestExitCode.GenericFailure);
console.GetOutput().Should().Contain("##[group]Test run summary:" + Environment.NewLine);
}
[TestMethod]
public void ContextualSummary_DoesNotCountRejectedRetryAsAnotherModule()
{
(TestApplicationHandler handler, TerminalTestReporter reporter, CapturingConsole console) = CreateHandler(
isHelp: false, isDiscovery: false, contextualModuleOutput: true);
handler.OnHandshakeReceived(BuildHandshake(HandshakeMessageExecutionModes.Run), gotSupportedVersion: true)
.Should().BeTrue();
handler.OnHandshakeReceived(BuildHandshake(HandshakeMessageExecutionModes.Help), gotSupportedVersion: true)
.Should().BeFalse();
handler.OnTestProcessExited(TestExitCode.GenericFailure, string.Empty, string.Empty);
reporter.TestExecutionCompleted(DateTimeOffset.UtcNow, TestExitCode.GenericFailure);
console.GetOutput().Should().Contain("##[group]Test run summary:" + Environment.NewLine);
}
[TestMethod]
public void ContextualSummary_ShowsUnselectedCountWithoutAmbiguousFailureCounts()
{
(TestApplicationHandler handler, TerminalTestReporter reporter, CapturingConsole console) = CreateHandler(
isHelp: false, isDiscovery: false, contextualModuleOutput: true);
handler.OnHandshakeReceived(BuildHandshake(HandshakeMessageExecutionModes.Help), gotSupportedVersion: true)
.Should().BeFalse();
reporter.AssemblyRunNotSelected("other.dll", "net9.0", "x64");
reporter.TestExecutionCompleted(DateTimeOffset.UtcNow, TestExitCode.GenericFailure);
console.GetOutput().Should().Contain("##[group]Test run summary: 1 skipped (No affected tests selected)");
}
/// <summary>
/// Even when the SDK itself was invoked in help mode, an explicit ExecutionMode mismatch reported
/// by the test host is a protocol-level rejection and must still be surfaced. This pins down the
/// <c>reportEvenWhenHelp: true</c> opt-out around the legacy "swallow handshake failures in help
/// mode" workaround in <see cref="TerminalTestReporter.HandshakeFailure"/>.
/// </summary>
[TestMethod]
public void OnHandshakeReceived_WhenSdkInHelpModeAndExecutionModeMismatch_StillReportsFailure()
{
(TestApplicationHandler handler, TerminalTestReporter reporter, _) = CreateHandler(isHelp: true, isDiscovery: false);
var handshake = BuildHandshake(HandshakeMessageExecutionModes.Run);
bool accepted = handler.OnHandshakeReceived(handshake, gotSupportedVersion: true);
accepted.Should().BeFalse();
reporter.HasHandshakeFailure.Should().BeTrue();
}
/// <summary>
/// Every protocol-level rejection inside <c>OnHandshakeReceived</c> (not just ExecutionMode
/// mismatch) opts out of the legacy "swallow handshake failures when SDK is in help mode"
/// workaround. Missing-required-property is one such rejection — covered here. The workaround
/// is intentionally scoped to <c>OnTestProcessExited</c> calling <c>HandshakeFailure</c>
/// without ever having received a real handshake (older MTP behavior on <c>--help</c>).
/// </summary>
[TestMethod]
public void OnHandshakeReceived_WhenSdkInHelpModeAndRequiredPropertyMissing_StillReportsFailure()
{
(TestApplicationHandler handler, TerminalTestReporter reporter, _) = CreateHandler(isHelp: true, isDiscovery: false);
// Build a handshake that's missing the required ExecutionId property.
var handshake = BuildHandshake(executionMode: null);
var properties = handshake.Properties.Where(kvp => kvp.Key != HandshakeMessagePropertyNames.ExecutionId).ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
var incompleteHandshake = new HandshakeMessage(properties);
bool accepted = handler.OnHandshakeReceived(incompleteHandshake, gotSupportedVersion: true);
accepted.Should().BeFalse();
reporter.HasHandshakeFailure.Should().BeTrue();
}
/// <summary>
/// When the protocol version itself is unsupported, that failure is reported and we exit early
/// — we don't also report an ExecutionMode mismatch on the same handshake, since the version
/// rejection makes any subsequent property validation moot (and it would be confusing to
/// surface two distinct failures for one handshake).
/// </summary>
[TestMethod]
public void OnHandshakeReceived_WhenUnsupportedProtocolVersion_DoesNotAlsoReportExecutionModeMismatch()
{
(TestApplicationHandler handler, TerminalTestReporter reporter, CapturingConsole console) = CreateHandler(isHelp: false, isDiscovery: false);
// ExecutionMode is "help" which would mismatch (SDK expects "run") if we got that far.
var handshake = BuildHandshake(HandshakeMessageExecutionModes.Help);
bool accepted = handler.OnHandshakeReceived(handshake, gotSupportedVersion: false);
accepted.Should().BeFalse();
reporter.HasHandshakeFailure.Should().BeTrue();
// The version-related failure IS reported and the ExecutionMode-related one is NOT —
// both sides of the assertion matter: it should catch a regression that produces no
// failure at all (no version error) as well as one that produces both.
string rendered = console.GetOutput();
rendered.Should().Contain("protocol version", "the unsupported-protocol-version failure is expected to be reported");
rendered.Should().NotContain("execution mode", "the ExecutionMode validation should be skipped when the protocol version itself was rejected");
}
/// <summary>
/// Forward-compat/protocol guard: a future testing-platform release that ships a new ExecutionMode
/// value without bumping the protocol version, or a host that sends an empty value, is not silently
/// accepted; we reject so we don't try to interpret a message stream we don't understand.
/// </summary>
[TestMethod]
[DataRow("future-mode")]
[DataRow("")]
[DataRow(" ")]
public void OnHandshakeReceived_WhenExecutionModeIsUnknownOrEmpty_RejectsHandshake(string executionMode)
{
(TestApplicationHandler handler, TerminalTestReporter reporter, _) = CreateHandler(isHelp: false, isDiscovery: false);
var handshake = BuildHandshake(executionMode: executionMode);
bool accepted = handler.OnHandshakeReceived(handshake, gotSupportedVersion: true);
accepted.Should().BeFalse();
reporter.HasHandshakeFailure.Should().BeTrue();
}
/// <summary>
/// A controller-host handshake (no <c>AssemblyRunStarted</c> bookkeeping) with a mismatched
/// ExecutionMode must still be rejected — the validation lives in <c>OnHandshakeReceived</c>,
/// not in a code path gated on <c>HostType == "TestHost"</c>.
/// </summary>
[TestMethod]
public void OnHandshakeReceived_WhenControllerHostReportsMismatchedExecutionMode_RejectsHandshake()
{
(TestApplicationHandler handler, TerminalTestReporter reporter, _) = CreateHandler(isHelp: false, isDiscovery: false);
var handshake = BuildHandshake(
executionMode: HandshakeMessageExecutionModes.Help,
hostType: "TestHostController",
includeInstanceId: false);
bool accepted = handler.OnHandshakeReceived(handshake, gotSupportedVersion: true);
accepted.Should().BeFalse();
reporter.HasHandshakeFailure.Should().BeTrue();
}
[TestMethod]
public void OnTestInProgressReceived_WhenOnlyControllerHandshakeReceived_ReportsProtocolError()
{
(TestApplicationHandler handler, _, _) = CreateHandler(isHelp: false, isDiscovery: false);
handler.OnHandshakeReceived(
BuildHandshake(
executionMode: HandshakeMessageExecutionModes.Run,
hostType: "TestHostController",
includeInstanceId: false),
gotSupportedVersion: true).Should().BeTrue();
Action act = () => handler.OnTestInProgressReceived(
new TestInProgressMessages(
ExecutionId: "exec-1",
InstanceId: "inst-1",
InProgressMessages: [new TestInProgressMessage("test-1", "Test 1")]));
act.Should().Throw<InvalidOperationException>()
.WithMessage(string.Format(
CliCommandStrings.UnexpectedMessageWithoutTestHostHandshake,
nameof(TestInProgressMessages)));
}
[TestMethod]
public void OnTestInProgressReceived_WhenExecutionIdMismatchesHandshake_ReportsProtocolError()
{
(TestApplicationHandler handler, _, _) = CreateHandler(isHelp: false, isDiscovery: false);
handler.OnHandshakeReceived(
BuildHandshake(executionMode: HandshakeMessageExecutionModes.Run),
gotSupportedVersion: true).Should().BeTrue();
Action act = () => handler.OnTestInProgressReceived(
new TestInProgressMessages(
ExecutionId: "different-execution",
InstanceId: "inst-1",
InProgressMessages: [new TestInProgressMessage("test-1", "Test 1")]));
act.Should().Throw<InvalidOperationException>()
.WithMessage(string.Format(
CliCommandStrings.DotnetTestMismatchingExecutionId,
"different-execution",
nameof(TestInProgressMessages),
"exec-1"));
}
[TestMethod]
[DataRow(nameof(TestInProgressMessages.ExecutionId))]
[DataRow(nameof(TestInProgressMessages.InstanceId))]
[DataRow(nameof(TestInProgressMessage.Uid))]
[DataRow(nameof(TestInProgressMessage.DisplayName))]
public void OnTestInProgressReceived_WhenRequiredPropertyIsMissing_ReportsProtocolError(string missingProperty)
{
(TestApplicationHandler handler, _, _) = CreateHandler(isHelp: false, isDiscovery: false);
handler.OnHandshakeReceived(
BuildHandshake(executionMode: HandshakeMessageExecutionModes.Run),
gotSupportedVersion: true).Should().BeTrue();
var message = new TestInProgressMessages(
ExecutionId: missingProperty == nameof(TestInProgressMessages.ExecutionId) ? null : "exec-1",
InstanceId: missingProperty == nameof(TestInProgressMessages.InstanceId) ? null : "inst-1",
InProgressMessages:
[
new TestInProgressMessage(
missingProperty == nameof(TestInProgressMessage.Uid) ? null : "test-1",
missingProperty == nameof(TestInProgressMessage.DisplayName) ? null : "Test 1"),
]);
string messageType = missingProperty is nameof(TestInProgressMessage.Uid) or nameof(TestInProgressMessage.DisplayName)
? nameof(TestInProgressMessage)
: nameof(TestInProgressMessages);
Action act = () => handler.OnTestInProgressReceived(message);
act.Should().Throw<InvalidOperationException>()
.WithMessage(string.Format(
CliCommandStrings.DotnetTestMissingRequiredMessageProperty,
missingProperty,
messageType));
}
/// <summary>
/// Old-MTP help path: the test host exits without performing a handshake at all because older
/// Microsoft.Testing.Platform versions don't handshake on <c>--help</c>. The SDK's existing
/// workaround in <see cref="TerminalTestReporter.HandshakeFailure"/> must keep swallowing that
/// case so we don't print a spurious failure for the legacy host. The new
/// <c>reportEvenWhenHelp</c> opt-out must not break this — only the explicit protocol-level
/// mismatch path opts in.
/// </summary>
[TestMethod]
public void OnTestProcessExited_WhenSdkInHelpModeAndNoHandshakeReceived_DoesNotReportFailure()
{
(TestApplicationHandler handler, TerminalTestReporter reporter, _) = CreateHandler(isHelp: true, isDiscovery: false);
Action act = () => handler.OnTestProcessExited(exitCode: 0, outputData: "help text", errorData: string.Empty);
act.Should().NotThrow();
reporter.HasHandshakeFailure.Should().BeFalse();
}
[TestMethod]
public void OnTestProcessExited_WhenSuccessfulTestMapCollectionSuppressesReporting_DoesNotReportFailure()
{
(TestApplicationHandler handler, TerminalTestReporter reporter, _) = CreateHandler(
isHelp: false,
isDiscovery: false,
collectTestMap: true);
handler.OnTestProcessExited(exitCode: 0, outputData: string.Empty, errorData: string.Empty);
reporter.HasHandshakeFailure.Should().BeFalse();
}
[TestMethod]
public void OnTestProcessExited_WhenTestMapCollectionFailsWithoutHandshake_ReportsFailure()
{
(TestApplicationHandler handler, TerminalTestReporter reporter, _) = CreateHandler(
isHelp: false,
isDiscovery: false,
collectTestMap: true);
handler.OnTestProcessExited(exitCode: 1, outputData: string.Empty, errorData: string.Empty);
reporter.HasHandshakeFailure.Should().BeTrue();
}
[TestMethod]
public void OnTestProcessExited_WhenTestMapCollectionReceivesOnlyControllerHandshake_ReportsFailure()
{
(TestApplicationHandler handler, TerminalTestReporter reporter, _) = CreateHandler(
isHelp: false,
isDiscovery: false,