-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathToolTask_Tests.cs
More file actions
1246 lines (1063 loc) · 47.5 KB
/
ToolTask_Tests.cs
File metadata and controls
1246 lines (1063 loc) · 47.5 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;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Resources;
using System.Text.RegularExpressions;
using Microsoft.Build.Framework;
using Microsoft.Build.Shared;
using Microsoft.Build.UnitTests;
using Microsoft.Build.Utilities;
using Shouldly;
using Xunit;
using Xunit.Abstractions;
#nullable disable
namespace Microsoft.Build.UnitTests
{
public sealed class ToolTask_Tests
{
private readonly ITestOutputHelper _output;
public ToolTask_Tests(ITestOutputHelper testOutput)
{
_output = testOutput;
}
private class MyTool : ToolTask, IDisposable
{
private string _fullToolName;
private string _responseFileCommands = string.Empty;
private string _commandLineCommands = string.Empty;
private string _pathToToolUsed;
public MyTool(ResourceManager resourceManager = null)
: base()
{
base.TaskResources = resourceManager;
_fullToolName = Path.Combine(
NativeMethodsShared.IsUnixLike ? "/bin" : Environment.GetFolderPath(Environment.SpecialFolder.System),
NativeMethodsShared.IsUnixLike ? "sh" : "cmd.exe");
}
public void Dispose()
{
}
public string PathToToolUsed => _pathToToolUsed;
public string MockResponseFileCommands
{
set => _responseFileCommands = value;
}
public string MockCommandLineCommands
{
set => _commandLineCommands = value;
}
public string FullToolName
{
set => _fullToolName = value;
}
/// <summary>
/// Intercepted start info
/// </summary>
internal ProcessStartInfo StartInfo { get; private set; }
/// <summary>
/// Whether execute was called
/// </summary>
internal bool ExecuteCalled { get; private set; }
internal Action<ProcessStartInfo> DoProcessStartInfoMutation { get; set; }
protected override string ToolName => Path.GetFileName(_fullToolName);
protected override string GenerateFullPathToTool() => _fullToolName;
protected override string GenerateResponseFileCommands() => _responseFileCommands;
protected override string GenerateCommandLineCommands() => _commandLineCommands;
protected override ProcessStartInfo GetProcessStartInfo(string pathToTool, string commandLineCommands, string responseFileSwitch)
{
var basePSI = base.GetProcessStartInfo(pathToTool, commandLineCommands, responseFileSwitch);
DoProcessStartInfoMutation?.Invoke(basePSI);
return basePSI;
}
protected override void LogEventsFromTextOutput(string singleLine, MessageImportance messageImportance)
{
if (singleLine.Contains("BADTHINGHAPPENED"))
{
// This is where a customer's tool task implementation could do its own
// parsing of the errors in the stdout/stderr output of the tool being wrapped.
Log.LogError(singleLine);
}
else
{
base.LogEventsFromTextOutput(singleLine, messageImportance);
}
}
protected override int ExecuteTool(string pathToTool, string responseFileCommands, string commandLineCommands)
{
Console.WriteLine("executetool");
_pathToToolUsed = pathToTool;
ExecuteCalled = true;
if (!NativeMethodsShared.IsWindows && string.IsNullOrEmpty(responseFileCommands) && string.IsNullOrEmpty(commandLineCommands))
{
// Unix makes sh interactive and it won't exit if there is nothing on the command line
commandLineCommands = " -c \"echo\"";
}
int result = base.ExecuteTool(pathToTool, responseFileCommands, commandLineCommands);
StartInfo = GetProcessStartInfo(GenerateFullPathToTool(), NativeMethodsShared.IsWindows ? "/x" : string.Empty, null);
return result;
}
}
[Fact]
public void Regress_Mutation_UserSuppliedToolPathIsLogged()
{
using (MyTool t = new MyTool())
{
MockEngine3 engine = new MockEngine3();
t.BuildEngine = engine;
t.ToolPath = NativeMethodsShared.IsWindows ? @"C:\MyAlternatePath" : "/MyAlternatePath";
t.Execute();
// The alternate path should be mentioned in the log.
engine.AssertLogContains("MyAlternatePath");
}
}
[Fact]
public void Regress_Mutation_MissingExecutableIsLogged()
{
using (MyTool t = new MyTool())
{
MockEngine3 engine = new MockEngine3();
t.BuildEngine = engine;
t.ToolPath = NativeMethodsShared.IsWindows ? @"C:\MyAlternatePath" : "/MyAlternatePath";
t.Execute().ShouldBeFalse();
// There should be an error about invalid task location.
engine.AssertLogContains("MSB6004");
}
}
[Fact]
public void Regress_Mutation_WarnIfCommandLineTooLong()
{
using (MyTool t = new MyTool())
{
MockEngine3 engine = new MockEngine3();
t.BuildEngine = engine;
// "cmd.exe" croaks big-time when given a very long command-line. It pops up a message box on
// Windows XP. We can't have that! So use "attrib.exe" for this exercise instead.
string systemPath = NativeMethodsShared.IsUnixLike ? "/bin" : Environment.GetFolderPath(Environment.SpecialFolder.System);
t.FullToolName = Path.Combine(systemPath, NativeMethodsShared.IsWindows ? "attrib.exe" : "ps");
t.MockCommandLineCommands = new string('x', 32001);
// It's only a warning, we still succeed
t.Execute().ShouldBeTrue();
t.ExitCode.ShouldBe(0);
// There should be a warning about the command-line being too long.
engine.AssertLogContains("MSB6002");
}
}
/// <summary>
/// Exercise the code in ToolTask's default implementation of HandleExecutionErrors.
/// </summary>
[Fact]
public void HandleExecutionErrorsWhenToolDoesntLogError()
{
using (MyTool t = new MyTool())
{
MockEngine3 engine = new MockEngine3();
t.BuildEngine = engine;
t.MockCommandLineCommands = NativeMethodsShared.IsWindows ? "/C garbagegarbagegarbagegarbage.exe" : "-c garbagegarbagegarbagegarbage.exe";
t.Execute().ShouldBeFalse();
t.ExitCode.ShouldBe(NativeMethodsShared.IsWindows ? 1 : 127); // cmd.exe error code is 1, sh error code is 127
// We just tried to run "cmd.exe /C garbagegarbagegarbagegarbage.exe". This should fail,
// but since "cmd.exe" doesn't log its errors in canonical format, no errors got
// logged by the tool itself. Therefore, ToolTask's default implementation of
// HandleTaskExecutionErrors should have logged error MSB6006.
engine.AssertLogContains("MSB6006");
}
}
/// <summary>
/// Exercise the code in ToolTask's default implementation of HandleExecutionErrors.
/// </summary>
[Fact]
[Trait("Category", "netcore-osx-failing")]
[Trait("Category", "netcore-linux-failing")]
public void HandleExecutionErrorsWhenToolLogsError()
{
using (MyTool t = new MyTool())
{
MockEngine3 engine = new MockEngine3();
t.BuildEngine = engine;
t.MockCommandLineCommands = NativeMethodsShared.IsWindows
? "/C echo Main.cs(17,20): error CS0168: The variable 'foo' is declared but never used"
: @"-c """"""echo Main.cs\(17,20\): error CS0168: The variable 'foo' is declared but never used""""""";
t.Execute().ShouldBeFalse();
// The above command logged a canonical error message. Therefore ToolTask should
// not log its own error beyond that.
engine.AssertLogDoesntContain("MSB6006");
engine.AssertLogContains("CS0168");
engine.AssertLogContains("The variable 'foo' is declared but never used");
t.ExitCode.ShouldBe(-1);
engine.Errors.ShouldBe(1);
}
}
/// <summary>
/// ToolTask should never run String.Format on strings that are
/// not meant to be formatted.
/// </summary>
[Fact]
public void DoNotFormatTaskCommandOrMessage()
{
using MyTool t = new MyTool();
MockEngine3 engine = new MockEngine3();
t.BuildEngine = engine;
// Unmatched curly would crash if they did
t.MockCommandLineCommands = NativeMethodsShared.IsWindows
? "/C echo hello world {"
: @"-c ""echo hello world {""";
t.Execute();
engine.AssertLogContains("echo hello world {");
engine.Errors.ShouldBe(0);
}
/// <summary>
/// Process notification encoding should be consistent with console code page.
/// not meant to be formatted.
/// </summary>
[InlineData(0, "")]
[InlineData(-1, "1>&2")]
[Theory]
public void ProcessNotificationEncodingConsistentWithConsoleCodePage(int exitCode, string errorPart)
{
using MyTool t = new MyTool();
MockEngine engine = new MockEngine();
t.BuildEngine = engine;
t.UseCommandProcessor = true;
t.LogStandardErrorAsError = true;
t.EchoOff = true;
t.UseUtf8Encoding = EncodingUtilities.UseUtf8Always;
string content = "Building Custom Rule プロジェクト";
string outputMessage = exitCode == 0 ? content : $"'{content}' {errorPart}";
string commandLine = $"echo {outputMessage}";
t.MockCommandLineCommands = commandLine;
t.Execute();
t.ExitCode.ShouldBe(exitCode);
string log = engine.Log;
string singleQuote = NativeMethodsShared.IsWindows ? "'" : string.Empty;
string displayMessage = exitCode == 0 ? content : $"ERROR : {singleQuote}{content}{singleQuote}";
string pattern = $"{commandLine}{Environment.NewLine}\\s*{displayMessage}";
Regex regex = new Regex(pattern);
regex.Matches(log).Count.ShouldBe(1, $"{log} doesn't contain the log matching the pattern: {pattern}");
}
/// <summary>
/// When a message is logged to the standard error stream do not error is LogStandardErrorAsError is not true or set.
/// </summary>
[Fact]
public void DoNotErrorWhenTextSentToStandardError()
{
using (MyTool t = new MyTool())
{
MockEngine3 engine = new MockEngine3();
t.BuildEngine = engine;
t.MockCommandLineCommands = NativeMethodsShared.IsWindows
? "/C Echo 'Who made you king anyways' 1>&2"
: @"-c ""echo Who made you king anyways 1>&2""";
t.Execute().ShouldBeTrue();
engine.AssertLogDoesntContain("MSB");
engine.AssertLogContains("Who made you king anyways");
t.ExitCode.ShouldBe(0);
engine.Errors.ShouldBe(0);
}
}
/// <summary>
/// When a message is logged to the standard output stream do not error is LogStandardErrorAsError is true
/// </summary>
[Fact]
public void DoNotErrorWhenTextSentToStandardOutput()
{
using (MyTool t = new MyTool())
{
MockEngine3 engine = new MockEngine3();
t.BuildEngine = engine;
t.LogStandardErrorAsError = true;
t.MockCommandLineCommands = NativeMethodsShared.IsWindows
? "/C Echo 'Who made you king anyways'"
: @"-c ""echo Who made you king anyways""";
t.Execute().ShouldBeTrue();
engine.AssertLogDoesntContain("MSB");
engine.AssertLogContains("Who made you king anyways");
t.ExitCode.ShouldBe(0);
engine.Errors.ShouldBe(0);
}
}
/// <summary>
/// When LogStandardErrorAsError is true and text is sent to stderr, the tool exits with
/// code 0 but ToolTask overrides the exit code to -1. The low-importance message
/// "The command exited with return value 0, but errors were detected" should be logged,
/// not the generic tool failure error MSB6006.
/// </summary>
[Fact]
public void ErrorWhenTextSentToStandardError()
{
using (MyTool t = new MyTool())
{
MockEngine3 engine = new MockEngine3();
t.BuildEngine = engine;
t.LogStandardErrorAsError = true;
t.MockCommandLineCommands = NativeMethodsShared.IsWindows
? "/C Echo 'Who made you king anyways' 1>&2"
: @"-c ""echo 'Who made you king anyways' 1>&2""";
t.Execute().ShouldBeFalse();
engine.AssertLogContains("Who made you king anyways");
// Should not log other failure error codes
engine.AssertLogDoesntContain("MSB3073");
t.ExitCode.ShouldBe(-1);
// Only the stderr-as-error from tool output
engine.Errors.ShouldBe(1);
}
}
/// <summary>
/// When the tool exits with a non-zero exit code and has already logged its own errors,
/// ToolTask should log the "command exited with code" message (not MSB6006) as a low-importance
/// diagnostic rather than a duplicate error.
/// </summary>
[Fact]
public void HandleExecutionErrorsWhenToolLogsErrorAndExitsNonZero()
{
using (MyTool t = new MyTool())
{
MockEngine3 engine = new MockEngine3();
t.BuildEngine = engine;
t.MockCommandLineCommands = NativeMethodsShared.IsWindows
? "/C echo BADTHINGHAPPENED && exit /b 1"
: @"-c ""echo BADTHINGHAPPENED; exit 1""";
t.Execute().ShouldBeFalse();
engine.AssertLogContains("BADTHINGHAPPENED");
// Should not log the generic tool failure error or the zero-with-errors message
engine.AssertLogDoesntContain("MSB3073");
engine.AssertLogDoesntContain("exited with return value 0");
t.ExitCode.ShouldBe(1);
// Only the custom error logged by MyTool.LogEventsFromTextOutput
engine.Errors.ShouldBe(1);
}
}
/// <summary>
/// When ToolExe is set, it is used instead of ToolName
/// </summary>
[Fact]
public void ToolExeWinsOverToolName()
{
using (MyTool t = new MyTool())
{
MockEngine3 engine = new MockEngine3();
t.BuildEngine = engine;
t.FullToolName = NativeMethodsShared.IsWindows ? "c:\\baz\\foo.exe" : "/baz/foo.exe";
t.ToolExe.ShouldBe("foo.exe");
t.ToolExe = "bar.exe";
t.ToolExe.ShouldBe("bar.exe");
}
}
/// <summary>
/// When ToolExe is set, it is appended to ToolPath instead
/// of the regular tool name
/// </summary>
[Fact]
public void ToolExeIsFoundOnToolPath()
{
string shellName = NativeMethodsShared.IsWindows ? "cmd.exe" : "sh";
string copyName = NativeMethodsShared.IsWindows ? "xcopy.exe" : "cp";
using (MyTool t = new MyTool())
{
MockEngine3 engine = new MockEngine3();
t.BuildEngine = engine;
t.FullToolName = shellName;
string systemPath = NativeMethodsShared.IsUnixLike ? "/bin" : Environment.GetFolderPath(Environment.SpecialFolder.System);
t.ToolPath = systemPath;
t.Execute();
t.PathToToolUsed.ShouldBe(Path.Combine(systemPath, shellName));
engine.AssertLogContains(shellName);
engine.Log = string.Empty;
t.ToolExe = copyName;
t.Execute();
t.PathToToolUsed.ShouldBe(Path.Combine(systemPath, copyName));
engine.AssertLogContains(copyName);
engine.AssertLogDoesntContain(shellName);
}
}
/// <summary>
/// Task is not found on path - regress #499196
/// </summary>
[Fact]
public void TaskNotFoundOnPath()
{
using (MyTool t = new MyTool())
{
MockEngine3 engine = new MockEngine3();
t.BuildEngine = engine;
t.FullToolName = "doesnotexist.exe";
t.Execute().ShouldBeFalse();
t.ExitCode.ShouldBe(-1);
engine.Errors.ShouldBe(1);
// Does not throw an exception
}
}
/// <summary>
/// Task is found on path.
/// </summary>
[Fact]
public void TaskFoundOnPath()
{
using (MyTool t = new MyTool())
{
MockEngine3 engine = new MockEngine3();
t.BuildEngine = engine;
string toolName = NativeMethodsShared.IsWindows ? "cmd.exe" : "sh";
t.FullToolName = toolName;
t.Execute().ShouldBeTrue();
t.ExitCode.ShouldBe(0);
engine.Errors.ShouldBe(0);
string systemPath = NativeMethodsShared.IsUnixLike ? "/bin" : Environment.GetFolderPath(Environment.SpecialFolder.System);
engine.AssertLogContains(
Path.Combine(systemPath, toolName));
}
}
/// <summary>
/// StandardOutputImportance set to Low should not show up in our log
/// </summary>
[Fact]
public void OverrideStdOutImportanceToLow()
{
string tempFile = FileUtilities.GetTemporaryFileName();
File.WriteAllText(tempFile, @"hello world");
using (MyTool t = new MyTool())
{
MockEngine3 engine = new MockEngine3();
engine.MinimumMessageImportance = MessageImportance.High;
t.BuildEngine = engine;
t.FullToolName = NativeMethodsShared.IsWindows ? "findstr.exe" : "grep";
t.MockCommandLineCommands = "\"hello\" \"" + tempFile + "\"";
t.StandardOutputImportance = "Low";
t.Execute().ShouldBeTrue();
t.ExitCode.ShouldBe(0);
engine.Errors.ShouldBe(0);
engine.AssertLogDoesntContain("hello world");
}
File.Delete(tempFile);
}
/// <summary>
/// StandardOutputImportance set to High should show up in our log
/// </summary>
[Fact]
public void OverrideStdOutImportanceToHigh()
{
string tempFile = FileUtilities.GetTemporaryFileName();
File.WriteAllText(tempFile, @"hello world");
using (MyTool t = new MyTool())
{
MockEngine3 engine = new MockEngine3();
engine.MinimumMessageImportance = MessageImportance.High;
t.BuildEngine = engine;
t.FullToolName = NativeMethodsShared.IsWindows ? "findstr.exe" : "grep";
t.MockCommandLineCommands = "\"hello\" \"" + tempFile + "\"";
t.StandardOutputImportance = "High";
t.Execute().ShouldBeTrue();
t.ExitCode.ShouldBe(0);
engine.Errors.ShouldBe(0);
engine.AssertLogContains("hello world");
}
File.Delete(tempFile);
}
[Theory]
[InlineData(true, "InvalidLevel")]
[InlineData(false, "InvalidLevel")]
public void FailToEnumerateStandardLoggingImportance(bool isErr, string invalidLevel)
{
using (MyTool t = new MyTool(AssemblyResources.SharedResources))
{
MockEngine3 engine = new MockEngine3();
t.BuildEngine = engine;
string toolName = NativeMethodsShared.IsWindows ? "cmd.exe" : "sh";
t.FullToolName = toolName;
if (isErr)
{
t.StandardErrorImportance = invalidLevel;
}
else
{
t.StandardOutputImportance = invalidLevel;
}
t.Execute().ShouldBeFalse();
t.ExitCode.ShouldBe(0);
engine.Errors.ShouldBe(1);
engine.AssertLogContains(invalidLevel);
}
}
/// <summary>
/// This is to ensure that somebody could write a task that implements ToolTask,
/// wraps some .EXE tool, and still have the ability to parse the stdout/stderr
/// himself. This is so that in case the tool doesn't log its errors in canonical
/// format, the task can still opt to do something reasonable with it.
/// </summary>
[Fact]
public void ToolTaskCanChangeCanonicalErrorFormat()
{
string tempFile = FileUtilities.GetTemporaryFileName();
File.WriteAllText(tempFile, @"
Main.cs(17,20): warning CS0168: The variable 'foo' is declared but never used.
BADTHINGHAPPENED: This is my custom error format that's not in canonical error format.
");
using (MyTool t = new MyTool())
{
MockEngine3 engine = new MockEngine3();
t.BuildEngine = engine;
// The command we're giving is the command to spew the contents of the temp
// file we created above.
t.MockCommandLineCommands = NativeMethodsShared.IsWindows
? $"/C type \"{tempFile}\""
: $"-c \"cat \'{tempFile}\'\"";
t.Execute();
// The above command logged a canonical warning, as well as a custom error.
engine.AssertLogContains("CS0168");
engine.AssertLogContains("The variable 'foo' is declared but never used");
engine.AssertLogContains("BADTHINGHAPPENED");
engine.AssertLogContains("This is my custom error format");
engine.Warnings.ShouldBe(1); // "Expected one warning in log."
engine.Errors.ShouldBe(1); // "Expected one error in log."
}
File.Delete(tempFile);
}
/// <summary>
/// Passing env vars through the tooltask public property
/// </summary>
[Fact]
public void EnvironmentVariablesToToolTask()
{
using MyTool task = new MyTool();
task.BuildEngine = new MockEngine3();
string userVarName = NativeMethodsShared.IsWindows ? "username" : "user";
task.EnvironmentVariables = new[] { "a=b", "c=d", userVarName + "=x" /* built-in */, "path=" /* blank value */};
bool result = task.Execute();
result.ShouldBe(true);
task.ExecuteCalled.ShouldBe(true);
ProcessStartInfo startInfo = task.StartInfo;
startInfo.Environment["a"].ShouldBe("b");
startInfo.Environment["c"].ShouldBe("d");
startInfo.Environment[userVarName].ShouldBe("x");
startInfo.Environment["path"].ShouldBe(String.Empty);
if (NativeMethodsShared.IsWindows)
{
Assert.Equal(
Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles),
startInfo.Environment["programfiles"],
true);
}
}
/// <summary>
/// Equals sign in value
/// </summary>
[Fact]
public void EnvironmentVariablesToToolTaskEqualsSign()
{
using MyTool task = new MyTool();
task.BuildEngine = new MockEngine3();
task.EnvironmentVariables = new[] { "a=b=c" };
bool result = task.Execute();
result.ShouldBe(true);
task.StartInfo.Environment["a"].ShouldBe("b=c");
}
/// <summary>
/// No value provided
/// </summary>
[Fact]
public void EnvironmentVariablesToToolTaskInvalid1()
{
using MyTool task = new MyTool();
task.BuildEngine = new MockEngine3();
task.EnvironmentVariables = new[] { "x" };
bool result = task.Execute();
result.ShouldBe(false);
task.ExecuteCalled.ShouldBe(false);
}
/// <summary>
/// Empty string provided
/// </summary>
[Fact]
public void EnvironmentVariablesToToolTaskInvalid2()
{
using MyTool task = new MyTool();
task.BuildEngine = new MockEngine3();
task.EnvironmentVariables = new[] { "" };
bool result = task.Execute();
result.ShouldBe(false);
task.ExecuteCalled.ShouldBe(false);
}
/// <summary>
/// Empty name part provided
/// </summary>
[Fact]
public void EnvironmentVariablesToToolTaskInvalid3()
{
using MyTool task = new MyTool();
task.BuildEngine = new MockEngine3();
task.EnvironmentVariables = new[] { "=a;b=c" };
bool result = task.Execute();
result.ShouldBe(false);
task.ExecuteCalled.ShouldBe(false);
}
/// <summary>
/// Not set should not wipe out other env vars
/// </summary>
[Fact]
public void EnvironmentVariablesToToolTaskNotSet()
{
using MyTool task = new MyTool();
task.BuildEngine = new MockEngine3();
task.EnvironmentVariables = null;
bool result = task.Execute();
result.ShouldBe(true);
task.ExecuteCalled.ShouldBe(true);
Assert.True(task.StartInfo.Environment["PATH"].Length > 0);
}
/// <summary>
/// Verifies that if a directory with the same name of the tool exists that the tool task correctly
/// ignores the directory.
/// </summary>
[Fact]
public void ToolPathIsFoundWhenDirectoryExistsWithNameOfTool()
{
string toolName = NativeMethodsShared.IsWindows ? "cmd" : "sh";
string savedCurrentDirectory = Directory.GetCurrentDirectory();
try
{
using (var env = TestEnvironment.Create())
{
string tempDirectory = env.CreateFolder().Path;
env.SetCurrentDirectory(tempDirectory);
env.SetEnvironmentVariable("PATH", $"{tempDirectory}{Path.PathSeparator}{Environment.GetEnvironmentVariable("PATH")}");
Directory.SetCurrentDirectory(tempDirectory);
string directoryNamedSameAsTool = Directory.CreateDirectory(Path.Combine(tempDirectory, toolName)).FullName;
using MyTool task = new MyTool
{
BuildEngine = new MockEngine3(),
FullToolName = toolName,
};
bool result = task.Execute();
Assert.NotEqual(directoryNamedSameAsTool, task.PathToToolUsed);
result.ShouldBeTrue();
}
}
finally
{
Directory.SetCurrentDirectory(savedCurrentDirectory);
}
}
/// <summary>
/// Confirms we can find a file on the PATH.
/// </summary>
[Fact]
public void FindOnPathSucceeds()
{
string[] expectedCmdPath;
string shellName;
string cmdPath;
if (NativeMethodsShared.IsWindows)
{
expectedCmdPath = new[] { Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "cmd.exe").ToUpperInvariant() };
shellName = "cmd.exe";
cmdPath = ToolTask.FindOnPath(shellName).ToUpperInvariant();
}
else
{
expectedCmdPath = new[] { "/bin/sh", "/usr/bin/sh" };
shellName = "sh";
cmdPath = ToolTask.FindOnPath(shellName);
}
cmdPath.ShouldBeOneOf(expectedCmdPath);
}
/// <summary>
/// Equals sign in value
/// </summary>
[Fact]
public void GetProcessStartInfoCanOverrideEnvironmentVariables()
{
using MyTool task = new MyTool();
task.DoProcessStartInfoMutation = (p) => p.Environment.Remove("a");
task.BuildEngine = new MockEngine3();
task.EnvironmentVariables = new[] { "a=b" };
bool result = task.Execute();
result.ShouldBe(true);
task.StartInfo.Environment.ContainsKey("a").ShouldBe(false);
}
[Fact]
public void VisualBasicLikeEscapedQuotesInCommandAreNotMadeForwardSlashes()
{
using MyTool t = new MyTool();
MockEngine3 engine = new MockEngine3();
t.BuildEngine = engine;
t.MockCommandLineCommands = NativeMethodsShared.IsWindows
? "/C echo \"hello \\\"world\\\"\""
: "-c echo \"hello \\\"world\\\"\"";
t.Execute();
engine.AssertLogContains("echo \"hello \\\"world\\\"\"");
engine.Errors.ShouldBe(0);
}
private sealed class MyToolWithCustomProcess : MyTool
{
protected override Process StartToolProcess(Process proc)
{
#pragma warning disable CA2000 // Dispose objects before losing scope - caller needs the process
Process customProcess = new Process();
#pragma warning restore CA2000
customProcess.StartInfo = proc.StartInfo;
customProcess.EnableRaisingEvents = true;
customProcess.Exited += ReceiveExitNotification;
customProcess.ErrorDataReceived += ReceiveStandardErrorData;
customProcess.OutputDataReceived += ReceiveStandardOutputData;
return base.StartToolProcess(customProcess);
}
}
[Fact]
public void UsesCustomProcess()
{
using (MyToolWithCustomProcess t = new MyToolWithCustomProcess())
{
MockEngine3 engine = new MockEngine3();
t.BuildEngine = engine;
t.MockCommandLineCommands = NativeMethodsShared.IsWindows
? "/C echo hello_stdout & echo hello_stderr >&2"
: "-c \"echo hello_stdout ; echo hello_stderr >&2\"";
t.Execute();
engine.AssertLogContains("\nhello_stdout");
engine.AssertLogContains("\nhello_stderr");
}
}
/// <summary>
/// Verifies that a ToolTask running under the command processor on Windows has autorun
/// disabled or enabled depending on an escape hatch.
/// </summary>
[Theory]
[InlineData("MSBUILDUSERAUTORUNINCMD", null, true)]
[InlineData("MSBUILDUSERAUTORUNINCMD", "0", true)]
[InlineData("MSBUILDUSERAUTORUNINCMD", "1", false)]
[Trait("Category", "nonosxtests")]
[Trait("Category", "nonlinuxtests")]
public void ExecTaskDisablesAutoRun(string environmentVariableName, string environmentVariableValue, bool autoRunShouldBeDisabled)
{
using (TestEnvironment testEnvironment = TestEnvironment.Create())
{
testEnvironment.SetEnvironmentVariable(environmentVariableName, environmentVariableValue);
ToolTaskThatGetsCommandLine task = new ToolTaskThatGetsCommandLine
{
UseCommandProcessor = true
};
task.Execute();
if (autoRunShouldBeDisabled)
{
task.CommandLineCommands.ShouldContain("/D ");
}
else
{
task.CommandLineCommands.ShouldNotContain("/D ");
}
}
}
/// <summary>
/// A simple implementation of <see cref="ToolTask"/> that allows tests to verify the command-line that was generated.
/// </summary>
private sealed class ToolTaskThatGetsCommandLine : ToolTask
{
protected override string ToolName => "cmd.exe";
protected override string GenerateFullPathToTool() => null;
protected override int ExecuteTool(string pathToTool, string responseFileCommands, string commandLineCommands)
{
PathToTool = pathToTool;
ResponseFileCommands = responseFileCommands;
CommandLineCommands = commandLineCommands;
return 0;
}
protected override void LogToolCommand(string message)
{
}
public string CommandLineCommands { get; private set; }
public string PathToTool { get; private set; }
public string ResponseFileCommands { get; private set; }
}
[Theory]
[InlineData("MSBUILDAVOIDUNICODE", null, false)]
[InlineData("MSBUILDAVOIDUNICODE", "0", false)]
[InlineData("MSBUILDAVOIDUNICODE", "1", true)]
public void ToolTaskCanUseUnicode(string environmentVariableName, string environmentVariableValue, bool expectNormalizationToANSI)
{
using TestEnvironment testEnvironment = TestEnvironment.Create(_output);
testEnvironment.SetEnvironmentVariable(environmentVariableName, environmentVariableValue);
var output = testEnvironment.ExpectFile();
MockEngine3 engine = new MockEngine3();
var task = new ToolTaskThatNeedsUnicode
{
BuildEngine = engine,
UseCommandProcessor = true,
OutputPath = output.Path,
};
task.Execute();
File.Exists(output.Path).ShouldBeTrue();
if (NativeMethodsShared.IsUnixLike // treat all UNIXy OSes as capable of UTF-8 everywhere
|| !expectNormalizationToANSI)
{
File.ReadAllText(output.Path).ShouldContain("łoł");
}
else
{
File.ReadAllText(output.Path).ShouldContain("lol");
}
}
private sealed class ToolTaskThatNeedsUnicode : ToolTask
{
protected override string ToolName => "cmd.exe";
[Required]
public string OutputPath { get; set; }
public ToolTaskThatNeedsUnicode()
{
UseCommandProcessor = true;
}
protected override string GenerateFullPathToTool()
{
return "cmd.exe";
}
protected override string GenerateCommandLineCommands()
{
return $"echo łoł > {OutputPath}";
}
}
/// <summary>
/// Verifies the validation of the <see cref="ToolTask.TaskProcessTerminationTimeout" />.
/// </summary>
/// <param name="timeout">New value for <see cref="ToolTask.TaskProcessTerminationTimeout" />.</param>
/// <param name="isInvalidValid">Is a task expected to be valid or not.</param>
[Theory]
[InlineData(int.MaxValue, false)]
[InlineData(97, false)]
[InlineData(0, false)]
[InlineData(-1, false)]
[InlineData(-2, true)]
[InlineData(-101, true)]
[InlineData(int.MinValue, true)]
public void SetsTerminationTimeoutCorrectly(int timeout, bool isInvalidValid)
{
using var env = TestEnvironment.Create(_output);
// Task under test:
var task = new ToolTaskSetsTerminationTimeout
{
BuildEngine = new MockEngine3()
};
task.TerminationTimeout = timeout;
task.ValidateParameters().ShouldBe(!isInvalidValid);
task.TerminationTimeout.ShouldBe(timeout);
}
/// <summary>
/// Verifies that a ToolTask instance can return correct results when executed multiple times with timeout.
/// </summary>
/// <param name="repeats">Specifies the number of repeats for external command execution.</param>
/// <param name="timeoutOnFirstExecution">Whether the first execution should be forced to time out before later retries succeed.</param>
/// <remarks>
/// These tests execute the same task instance multiple times, which will in turn run a command to sleep for a
/// predefined amount of time. The first execution may time out, but all following ones won't. It is expected