/
BuildManager_Tests.cs
4321 lines (3678 loc) · 176 KB
/
BuildManager_Tests.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
using System.Xml;
using Microsoft.Build.BackEnd;
using Microsoft.Build.Collections;
using Microsoft.Build.Construction;
using Microsoft.Build.Evaluation;
using Microsoft.Build.Exceptions;
using Microsoft.Build.Execution;
using Microsoft.Build.Framework;
using Microsoft.Build.Graph;
using Microsoft.Build.Logging;
using Microsoft.Build.Shared;
using Microsoft.Build.Utilities;
using Shouldly;
using Xunit;
using Xunit.Abstractions;
using static Microsoft.Build.UnitTests.ObjectModelHelpers;
namespace Microsoft.Build.UnitTests.BackEnd
{
/// <summary>
/// The test fixture for the BuildManager
/// </summary>
public class BuildManager_Tests : IDisposable
{
/// <summary>
/// The mock logger for testing.
/// </summary>
private readonly MockLogger _logger;
/// <summary>
/// The standard build manager for each test.
/// </summary>
private readonly BuildManager _buildManager;
/// <summary>
/// The build parameters.
/// </summary>
private readonly BuildParameters _parameters;
/// <summary>
/// The project collection used.
/// </summary>
private readonly ProjectCollection _projectCollection;
private readonly TestEnvironment _env;
private readonly ITestOutputHelper _output;
/// <summary>
/// The transient state corresponding to setting MSBUILDINPROCENVCHECK to 1.
/// </summary>
private readonly TransientTestState _inProcEnvCheckTransientEnvironmentVariable;
/// <summary>
/// SetUp
/// </summary>
public BuildManager_Tests(ITestOutputHelper output)
{
_output = output;
// Ensure that any previous tests which may have been using the default BuildManager do not conflict with us.
BuildManager.DefaultBuildManager.Dispose();
_logger = new MockLogger(output);
_parameters = new BuildParameters
{
ShutdownInProcNodeOnBuildFinish = true,
Loggers = new ILogger[] { _logger },
EnableNodeReuse = false
};
_buildManager = new BuildManager();
_projectCollection = new ProjectCollection();
_env = TestEnvironment.Create(output);
_inProcEnvCheckTransientEnvironmentVariable = _env.SetEnvironmentVariable("MSBUILDINPROCENVCHECK", "1");
}
/// <summary>
/// TearDown
/// </summary>
public void Dispose()
{
_buildManager.Dispose();
_projectCollection.Dispose();
_env.Dispose();
}
/// <summary>
/// Check that we behave reasonably when passed a null ProjectCollection
/// </summary>
[Fact]
public void BuildParametersWithNullCollection()
{
Assert.Throws<ArgumentNullException>(() => { new BuildParameters(null); });
}
/// <summary>
/// A simple successful build.
/// </summary>
[Fact]
public void SimpleBuild()
{
string contents = CleanupFileContents(@"
<Project xmlns='msbuildnamespace' ToolsVersion='msbuilddefaulttoolsversion'>
<PropertyGroup>
<InitialProperty1>InitialProperty1</InitialProperty1>
<InitialProperty2>InitialProperty2</InitialProperty2>
<InitialProperty3>InitialProperty3</InitialProperty3>
</PropertyGroup>
<Target Name='test'>
<Message Text='[success]'/>
</Target>
</Project>
");
BuildRequestData data = GetBuildRequestData(contents);
BuildResult result = _buildManager.Build(_parameters, data);
Assert.Equal(BuildResultCode.Success, result.OverallResult);
_logger.AssertLogContains("[success]");
Assert.Single(_logger.ProjectStartedEvents);
ProjectStartedEventArgs projectStartedEvent = _logger.ProjectStartedEvents[0];
Dictionary<string, string> properties = ExtractProjectStartedPropertyList(projectStartedEvent.Properties);
Assert.True(properties.TryGetValue("InitialProperty1", out string propertyValue));
Assert.Equal("InitialProperty1", propertyValue);
Assert.True(properties.TryGetValue("InitialProperty2", out propertyValue));
Assert.Equal("InitialProperty2", propertyValue);
Assert.True(properties.TryGetValue("InitialProperty3", out propertyValue));
Assert.Equal("InitialProperty3", propertyValue);
}
[Fact]
public void SimpleP2PBuildInProc()
{
var newParameters = _parameters.Clone();
newParameters.DisableInProcNode = false;
newParameters.MaxNodeCount = 1;
SimpleP2PBuild(newParameters);
}
[Fact]
public void SimpleP2PBuildOutOfProc()
{
var newParameters = _parameters.Clone();
newParameters.DisableInProcNode = true;
newParameters.MaxNodeCount = 3;
SimpleP2PBuild(newParameters);
}
private void SimpleP2PBuild(BuildParameters buildParameters)
{
var graph = Helpers.CreateProjectGraph(
_env,
new Dictionary<int, int[]>
{
{1, new[] {2, 3}}
},
createProjectFile:
(env, projectNumber, references, targets, defaultTargets, content) =>
{
return Helpers.CreateProjectFile(
env,
projectNumber,
references,
targets,
"ActualBuild",
@"<Target Name='ActualBuild'>
<MSBuild Projects='@(ProjectReference)'/>
</Target>");
});
var result = _buildManager.Build(
buildParameters,
new BuildRequestData(
graph.GraphRoots.FirstOrDefault()
.ProjectInstance.FullPath,
new Dictionary<string, string>(),
MSBuildConstants.CurrentToolsVersion,
new string[0],
null));
result.OverallResult.ShouldBe(BuildResultCode.Success);
_logger.AllBuildEvents.OfType<ProjectStartedEventArgs>()
.Count()
.ShouldBe(3);
_logger.AllBuildEvents.OfType<ProjectEvaluationFinishedEventArgs>()
.Count()
.ShouldBe(3);
_logger.AllBuildEvents.OfType<ProjectEvaluationStartedEventArgs>()
.Count()
.ShouldBe(3);
_logger.AllBuildEvents.OfType<ProjectEvaluationFinishedEventArgs>()
.Count()
.ShouldBe(3);
}
[Fact]
public void GraphBuildOptionsDefaults()
{
var options = new GraphBuildOptions();
options.Build.ShouldBeTrue();
}
/// <summary>
/// A simple successful graph build.
/// </summary>
[Fact]
[ActiveIssue("https://github.com/Microsoft/msbuild/issues/4368")]
public void SimpleGraphBuild()
{
string contents = CleanupFileContents(@"
<Project xmlns='msbuildnamespace' ToolsVersion='msbuilddefaulttoolsversion'>
<PropertyGroup>
<InitialProperty1>InitialProperty1</InitialProperty1>
<InitialProperty2>InitialProperty2</InitialProperty2>
<InitialProperty3>InitialProperty3</InitialProperty3>
</PropertyGroup>
<Target Name='test'>
<Message Text='[success]'/>
</Target>
</Project>
");
GraphBuildRequestData data = GetGraphBuildRequestData(contents);
GraphBuildResult result = _buildManager.Build(_parameters, data);
result.OverallResult.ShouldBe(BuildResultCode.Success);
_logger.AssertLogContains("[success]");
_logger.ProjectStartedEvents.Count.ShouldBe(1);
ProjectStartedEventArgs projectStartedEvent = _logger.ProjectStartedEvents[0];
Dictionary<string, string> properties = ExtractProjectStartedPropertyList(projectStartedEvent.Properties);
properties.TryGetValue("InitialProperty1", out string propertyValue).ShouldBeTrue();
propertyValue.ShouldBe("InitialProperty1", StringCompareShould.IgnoreCase);
properties.TryGetValue("InitialProperty2", out propertyValue).ShouldBeTrue();
propertyValue.ShouldBe("InitialProperty2", StringCompareShould.IgnoreCase);
properties.TryGetValue("InitialProperty3", out propertyValue).ShouldBeTrue();
propertyValue.ShouldBe("InitialProperty3", StringCompareShould.IgnoreCase);
}
#if FEATURE_CODETASKFACTORY
/// <summary>
/// Verify that the environment between two msbuild calls to the same project are stored
/// so that on the next call we get access to them
/// </summary>
[Fact]
public void VerifyEnvironmentSavedBetweenCalls()
{
string contents1 = CleanupFileContents(@"
<Project xmlns='msbuildnamespace' ToolsVersion='msbuilddefaulttoolsversion'>
<UsingTask TaskName='SetEnvv' TaskFactory='CodeTaskFactory' AssemblyFile='$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll' >
<Task>
<Code Language='cs'>
System.Environment.SetEnvironmentVariable(""MOO"", ""When the dawn comes, tonight will be a memory too"");
</Code>
</Task>
</UsingTask>
<Target Name='SetEnv'>
<SetEnvv/>
</Target>
<Target Name='Message1'>
<Exec Command='echo What does a cat say : " + (NativeMethodsShared.IsWindows ? "%MOO%" : "$MOO") + @"' />
</Target>
</Project>
");
var project = new Project(XmlReader.Create(new StringReader(contents1)), null, null, _projectCollection)
{
FullPath = _env.CreateFile(".proj").Path
};
project.Save();
string contents2 = CleanupFileContents(@"
<Project xmlns='msbuildnamespace' ToolsVersion='msbuilddefaulttoolsversion'>
<Target Name='Build' >
<MSBuild Targets='SetEnv' Projects='" + project.FullPath + "'/>" +
"<MSBuild Targets='Message1' Projects='" + project.FullPath + "'/>" +
@"</Target>
</Project>
");
ProjectInstance instance = CreateProjectInstance(contents2, null, _projectCollection, true);
BuildRequestData data = new BuildRequestData(instance, new[] { "Build" }, _projectCollection.HostServices);
BuildResult result = _buildManager.Build(_parameters, data);
Assert.Equal(BuildResultCode.Success, result.OverallResult);
_logger.AssertLogContains("What does a cat say : When the dawn comes, tonight will be a memory too");
}
#endif
/// <summary>
/// Verify if idle nodes are shutdown when BuildManager.ShutdownAllNodes is evoked.
/// The final number of nodes has to be less or equal the number of nodes already in
/// the system before this method was called.
/// </summary>
#if RUNTIME_TYPE_NETCORE
[Theory(Skip = "https://github.com/Microsoft/msbuild/issues/1975")]
#elif MONO
[Theory(Skip = "https://github.com/Microsoft/msbuild/issues/1240")]
#else
[Theory(Skip = "https://github.com/Microsoft/msbuild/issues/2057")]
#endif
[InlineData(8, false)]
public void ShutdownNodesAfterParallelBuild(int numberOfParallelProjectsToBuild, bool enbaleDebugComm)
{
// This test has previously been failing silently. With the addition of TestEnvironment the
// failure is now noticed (worker node is crashing with "Pipe is broken" exception. See #2057:
// https://github.com/Microsoft/msbuild/issues/2057
_env.ClearTestInvariants();
// Communications debug log enabled, picked up by TestEnvironment
if (enbaleDebugComm)
{
_env.SetEnvironmentVariable("MSBUILDDEBUGCOMM", "1");
}
var projectCollection = new ProjectCollection();
// Get number of MSBuild processes currently instantiated
int numberProcsOriginally = (new List<Process>(Process.GetProcessesByName("MSBuild"))).Count;
_output.WriteLine($"numberProcsOriginally = {numberProcsOriginally}");
// Generate a theoretically unique directory to put our dummy projects in.
string shutdownProjectDirectory = Path.Combine(Path.GetTempPath(), String.Format(CultureInfo.InvariantCulture, "VSNodeShutdown_{0}_UnitTest", Process.GetCurrentProcess().Id));
// Create the dummy projects we'll be "building" as our excuse to connect to and shut down
// all the nodes.
ProjectInstance rootProject = GenerateDummyProjects(shutdownProjectDirectory, numberOfParallelProjectsToBuild, projectCollection);
// Build the projects.
var buildParameters = new BuildParameters(projectCollection)
{
OnlyLogCriticalEvents = true,
MaxNodeCount = numberOfParallelProjectsToBuild,
EnableNodeReuse = true,
DisableInProcNode = true,
SaveOperatingEnvironment = false,
Loggers = new List<ILogger> {new MockLogger(_output)}
};
// Tell the build manager to not disturb process wide state
var requestData = new BuildRequestData(rootProject, new[] { "Build" }, null);
// Use a separate BuildManager for the node shutdown build, so that we don't have
// to worry about taking dependencies on whether or not the existing ones have already
// disappeared.
var shutdownManager = new BuildManager("IdleNodeShutdown");
shutdownManager.Build(buildParameters, requestData);
// Number of nodes after the build has to be greater than the original number
int numberProcsAfterBuild = (new List<Process>(Process.GetProcessesByName("MSBuild"))).Count;
_output.WriteLine($"numberProcsAfterBuild = {numberProcsAfterBuild}");
Assert.True(numberProcsOriginally < numberProcsAfterBuild, $"Expected '{numberProcsOriginally}' < '{numberProcsAfterBuild}'");
// Shutdown all nodes
shutdownManager.ShutdownAllNodes();
// Wait until all processes shut down
Thread.Sleep(3000);
// Number of nodes after the shutdown has to be smaller or equal the original number
int numberProcsAfterShutdown = (new List<Process>(Process.GetProcessesByName("MSBuild"))).Count;
_output.WriteLine($"numberProcsAfterShutdown = {numberProcsAfterShutdown}");
Assert.True(numberProcsAfterShutdown <= numberProcsOriginally);
// Delete directory with the dummy project
if (Directory.Exists(shutdownProjectDirectory))
{
FileUtilities.DeleteWithoutTrailingBackslash(shutdownProjectDirectory, true /* recursive delete */);
}
}
/// <summary>
/// A simple successful build, out of process only.
/// </summary>
#if MONO
[Fact(Skip = "https://github.com/Microsoft/msbuild/issues/1240")]
#else
[Fact]
#endif
public void SimpleBuildOutOfProcess()
{
RunOutOfProcBuild(_ => _env.SetEnvironmentVariable("MSBUILDNOINPROCNODE", "1"));
}
/// <summary>
/// A simple successful build, out of process only. Triggered by setting build parameters' DisableInProcNode to true.
/// </summary>
#if MONO
[Fact(Skip = "https://github.com/Microsoft/msbuild/issues/1240")]
#else
[Fact]
#endif
public void DisableInProcNode()
{
RunOutOfProcBuild(buildParameters => buildParameters.DisableInProcNode = true);
}
/// <summary>
/// Runs a build and verifies it happens out of proc by checking the process ID.
/// </summary>
/// <param name="buildParametersModifier">Runs a test out of proc.</param>
private void RunOutOfProcBuild(Action<BuildParameters> buildParametersModifier)
{
const string contents = @"
<Project xmlns='msbuildnamespace' ToolsVersion='msbuilddefaulttoolsversion'>
<ItemGroup>
<InitialProperty Include='InitialProperty2'/>
<InitialProperty Include='InitialProperty3'/>
</ItemGroup>
<Target Name='test' Returns='@(InitialProperty)'>
<ItemGroup>
<InitialProperty Include='$([System.Diagnostics.Process]::GetCurrentProcess().Id)'/>
</ItemGroup>
<Message Text='[success]'/>
</Target>
</Project>
";
// Need to set this env variable to enable Process.GetCurrentProcess().Id in the project file.
_env.SetEnvironmentVariable("MSBUILDENABLEALLPROPERTYFUNCTIONS", "1");
Project project = CreateProject(CleanupFileContents(contents), MSBuildDefaultToolsVersion, _projectCollection, false);
var data = new BuildRequestData(project.CreateProjectInstance(), new string[0], _projectCollection.HostServices);
var customparameters = new BuildParameters { EnableNodeReuse = false, Loggers = new ILogger[] { _logger } };
buildParametersModifier(customparameters);
BuildResult result = _buildManager.Build(customparameters, data);
TargetResult targetresult = result.ResultsByTarget["test"];
ITaskItem[] item = targetresult.Items;
Assert.Equal(BuildResultCode.Success, result.OverallResult);
Assert.Equal(3, item.Length);
Assert.True(int.TryParse(item[2].ItemSpec, out int processId), $"Process ID passed from the 'test' target is not a valid integer (actual is '{item[2].ItemSpec}')");
Assert.NotEqual(Process.GetCurrentProcess().Id, processId); // "Build is expected to be out-of-proc. In fact it was in-proc."
}
#if MONO
[Fact(Skip = "https://github.com/Microsoft/msbuild/issues/1240")]
#else
[Fact]
#endif
public void RequestedResultsAreSatisfied()
{
const string contents = @"
<Project xmlns='msbuildnamespace' ToolsVersion='msbuilddefaulttoolsversion'>
<PropertyGroup>
<UnrequestedProperty>IsUnrequested</UnrequestedProperty>
<RequestedProperty>IsRequested</RequestedProperty>
<UpdatedProperty>Stale</UpdatedProperty>
</PropertyGroup>
<ItemGroup>
<AnItem Include='Item1' UnexpectedMetadatum='Unexpected' />
<AnItem Include='Item2'/>
</ItemGroup>
<Target Name='test' Returns='@(ItemWithMetadata)'>
<ItemGroup>
<AnItem Include='$([System.Diagnostics.Process]::GetCurrentProcess().Id)' />
<ItemWithMetadata Metadatum1='m1' Metadatum2='m2' Include='ItemFromTarget' />
</ItemGroup>
<PropertyGroup>
<NewProperty>FunValue</NewProperty>
<UpdatedProperty>Updated</UpdatedProperty>
</PropertyGroup>
<Message Text='[success]'/>
</Target>
<Target Name='other' Returns='@(ItemWithMetadata)' DependsOnTargets='test' />
</Project>
";
// Need to set this env variable to enable Process.GetCurrentProcess().Id in the project file.
_env.SetEnvironmentVariable("MSBUILDENABLEALLPROPERTYFUNCTIONS", "1");
Project project = CreateProject(CleanupFileContents(contents), MSBuildDefaultToolsVersion,
_projectCollection, false);
var requestedProjectState = new RequestedProjectState
{
ItemFilters = new Dictionary<string, List<string>>
{
{"AnItem", null},
{"ItemWithMetadata", new List<string> {"Metadatum1"}},
},
PropertyFilters = new List<string> {"NewProperty", "RequestedProperty"},
};
var data = new BuildRequestData(project.CreateProjectInstance(), new [] {"test", "other"},
_projectCollection.HostServices, BuildRequestDataFlags.ProvideSubsetOfStateAfterBuild, null,
requestedProjectState);
var customparameters = new BuildParameters
{
EnableNodeReuse = false,
Loggers = new ILogger[] {_logger},
DisableInProcNode = true,
};
BuildResult result = _buildManager.Build(customparameters, data);
result.OverallResult.ShouldBe(BuildResultCode.Success);
result.ProjectStateAfterBuild.ShouldNotBeNull();
result.ProjectStateAfterBuild.Properties.ShouldNotContain(p => p.Name == "UnrequestedProperty");
result.ProjectStateAfterBuild.Properties.ShouldContain(p => p.Name == "NewProperty");
result.ProjectStateAfterBuild.GetPropertyValue("NewProperty").ShouldBe("FunValue");
result.ProjectStateAfterBuild.Properties.ShouldContain(p => p.Name == "RequestedProperty");
result.ProjectStateAfterBuild.GetPropertyValue("RequestedProperty").ShouldBe("IsRequested");
result.ProjectStateAfterBuild.Items.Count.ShouldBe(4);
result.ProjectStateAfterBuild.GetItems("ItemWithMetadata").ShouldHaveSingleItem();
result.ProjectStateAfterBuild.GetItems("ItemWithMetadata").First().DirectMetadataCount.ShouldBe(1);
result.ProjectStateAfterBuild.GetItems("ItemWithMetadata").First().GetMetadataValue("Metadatum1")
.ShouldBe("m1");
result.ProjectStateAfterBuild.GetItems("ItemWithMetadata").First().GetMetadataValue("Metadatum2")
.ShouldBeNullOrEmpty();
result.ProjectStateAfterBuild.GetItems("AnItem").Count.ShouldBe(3);
result.ProjectStateAfterBuild.GetItems("AnItem").ShouldContain(p => p.EvaluatedInclude == "Item2");
result.ProjectStateAfterBuild.GetItemsByItemTypeAndEvaluatedInclude("AnItem", "Item1")
.ShouldHaveSingleItem();
result.ProjectStateAfterBuild.GetItemsByItemTypeAndEvaluatedInclude("AnItem", "Item1").First()
.GetMetadataValue("UnexpectedMetadatum").ShouldBe("Unexpected");
}
/// <summary>
/// Make sure when we are doing an in-process build that even if the environment variable MSBUILDFORWARDPROPERTIESFROMCHILD is set that we still
/// get all of the initial properties.
/// </summary>
[Fact]
public void InProcForwardPropertiesFromChild()
{
string contents = CleanupFileContents(@"
<Project xmlns='msbuildnamespace' ToolsVersion='msbuilddefaulttoolsversion'>
<PropertyGroup>
<InitialProperty1>InitialProperty1</InitialProperty1>
<InitialProperty2>InitialProperty2</InitialProperty2>
<InitialProperty3>InitialProperty3</InitialProperty3>
</PropertyGroup>
<Target Name='test'>
<Message Text='[success]'/>
</Target>
</Project>
");
_env.SetEnvironmentVariable("MSBuildForwardPropertiesFromChild", "InitialProperty2;IAMNOTREAL");
BuildRequestData data = GetBuildRequestData(contents);
BuildResult result = _buildManager.Build(_parameters, data);
Assert.Equal(BuildResultCode.Success, result.OverallResult);
_logger.AssertLogContains("[success]");
Assert.Single(_logger.ProjectStartedEvents);
ProjectStartedEventArgs projectStartedEvent = _logger.ProjectStartedEvents[0];
Dictionary<string, string> properties = ExtractProjectStartedPropertyList(projectStartedEvent.Properties);
Assert.True(properties.TryGetValue("InitialProperty1", out string propertyValue));
Assert.Equal("InitialProperty1", propertyValue);
Assert.True(properties.TryGetValue("InitialProperty2", out propertyValue));
Assert.Equal("InitialProperty2", propertyValue);
Assert.True(properties.TryGetValue("InitialProperty3", out propertyValue));
Assert.Equal("InitialProperty3", propertyValue);
}
/// <summary>
/// Make sure when we are doing an in-process build that even if the environment variable MsBuildForwardAllPropertiesFromChild is set that we still
/// get all of the initial properties.
/// </summary>
[Fact]
public void InProcMsBuildForwardAllPropertiesFromChild()
{
string contents = CleanupFileContents(@"
<Project xmlns='msbuildnamespace' ToolsVersion='msbuilddefaulttoolsversion'>
<PropertyGroup>
<InitialProperty1>InitialProperty1</InitialProperty1>
<InitialProperty2>InitialProperty2</InitialProperty2>
<InitialProperty3>InitialProperty3</InitialProperty3>
</PropertyGroup>
<Target Name='test'>
<Message Text='[success]'/>
</Target>
</Project>
");
_env.SetEnvironmentVariable("MsBuildForwardAllPropertiesFromChild", "InitialProperty2;IAMNOTREAL");
BuildRequestData data = GetBuildRequestData(contents);
BuildResult result = _buildManager.Build(_parameters, data);
Assert.Equal(BuildResultCode.Success, result.OverallResult);
_logger.AssertLogContains("[success]");
Assert.Single(_logger.ProjectStartedEvents);
ProjectStartedEventArgs projectStartedEvent = _logger.ProjectStartedEvents[0];
Dictionary<string, string> properties = ExtractProjectStartedPropertyList(projectStartedEvent.Properties);
Assert.True(properties.TryGetValue("InitialProperty1", out string propertyValue));
Assert.Equal("InitialProperty1", propertyValue);
Assert.True(properties.TryGetValue("InitialProperty2", out propertyValue));
Assert.Equal("InitialProperty2", propertyValue);
Assert.True(properties.TryGetValue("InitialProperty3", out propertyValue));
Assert.Equal("InitialProperty3", propertyValue);
}
/// <summary>
/// Make sure when we launch a child node and set MsBuildForwardAllPropertiesFromChild that we get all of our properties. This needs to happen
/// even if the msbuildforwardpropertiesfromchild is set to something.
/// </summary>
[Fact]
public void MsBuildForwardAllPropertiesFromChildLaunchChildNode()
{
string contents = CleanupFileContents(@"
<Project xmlns='msbuildnamespace' ToolsVersion='msbuilddefaulttoolsversion'>
<PropertyGroup>
<InitialProperty1>InitialProperty1</InitialProperty1>
<InitialProperty2>InitialProperty2</InitialProperty2>
<InitialProperty3>InitialProperty3</InitialProperty3>
</PropertyGroup>
<Target Name='test'>
<Message Text='[success]'/>
</Target>
</Project>
");
_env.SetEnvironmentVariable("MsBuildForwardAllPropertiesFromChild", "InitialProperty2;IAMNOTREAL");
_env.SetEnvironmentVariable("MsBuildForwardPropertiesFromChild", "Something");
var project = CreateProject(contents, null, _projectCollection, false);
var data = new BuildRequestData(project.FullPath, new Dictionary<string, string>(), MSBuildDefaultToolsVersion, new string[] { }, null);
BuildResult result = _buildManager.Build(_parameters, data);
Assert.Equal(BuildResultCode.Success, result.OverallResult);
_logger.AssertLogContains("[success]");
Assert.Single(_logger.ProjectStartedEvents);
ProjectStartedEventArgs projectStartedEvent = _logger.ProjectStartedEvents[0];
Dictionary<string, string> properties = ExtractProjectStartedPropertyList(projectStartedEvent.Properties);
Assert.True(properties.TryGetValue("InitialProperty1", out string propertyValue));
Assert.Equal("InitialProperty1", propertyValue);
Assert.True(properties.TryGetValue("InitialProperty2", out propertyValue));
Assert.Equal("InitialProperty2", propertyValue);
Assert.True(properties.TryGetValue("InitialProperty3", out propertyValue));
Assert.Equal("InitialProperty3", propertyValue);
}
/// <summary>
/// Make sure when if the environment variable MsBuildForwardPropertiesFromChild is set to a value and
/// we launch a child node that we get only that value.
/// </summary>
#if RUNTIME_TYPE_NETCORE
[Fact(Skip = "https://github.com/Microsoft/msbuild/issues/1976")]
#elif MONO
[Fact(Skip = "https://github.com/Microsoft/msbuild/issues/1240")]
#else
[Fact]
#endif
public void OutOfProcNodeForwardCertainproperties()
{
string contents = CleanupFileContents(@"
<Project xmlns='msbuildnamespace' ToolsVersion='msbuilddefaulttoolsversion'>
<PropertyGroup>
<InitialProperty1>InitialProperty1</InitialProperty1>
<InitialProperty2>InitialProperty2</InitialProperty2>
<InitialProperty3>InitialProperty3</InitialProperty3>
</PropertyGroup>
<Target Name='test'>
<Message Text='[success]'/>
</Target>
</Project>
");
_env.SetEnvironmentVariable("MsBuildForwardPropertiesFromChild", "InitialProperty3;IAMNOTREAL");
_env.SetEnvironmentVariable("MSBUILDNOINPROCNODE", "1");
var project = CreateProject(contents, null, _projectCollection, false);
var data = new BuildRequestData(project.FullPath, new Dictionary<string, string>(),
MSBuildDefaultToolsVersion, new string[] { }, null);
BuildResult result = _buildManager.Build(_parameters, data);
Assert.Equal(BuildResultCode.Success, result.OverallResult);
_logger.AssertLogContains("[success]");
Assert.Single(_logger.ProjectStartedEvents);
ProjectStartedEventArgs projectStartedEvent = _logger.ProjectStartedEvents[0];
Dictionary<string, string> properties = ExtractProjectStartedPropertyList(projectStartedEvent.Properties);
Assert.Single(properties);
Assert.True(properties.TryGetValue("InitialProperty3", out string propertyValue));
Assert.Equal("InitialProperty3", propertyValue);
}
/// <summary>
/// Make sure when if the environment variable MsBuildForwardPropertiesFromChild is set to a value and
/// we launch a child node that we get only that value. Also, make sure that when a project is pulled from the results cache
/// and we have a list of properties to serialize that we do not crash. This is to prevent a regression of 826594
/// </summary>
#if RUNTIME_TYPE_NETCORE
[Fact(Skip = "https://github.com/Microsoft/msbuild/issues/1976")]
#elif MONO
[Fact(Skip = "https://github.com/Microsoft/msbuild/issues/1240")]
#else
[Fact]
#endif
public void OutOfProcNodeForwardCertainpropertiesAlsoGetResultsFromCache()
{
string tempProject = _env.CreateFile(".proj").Path;
string contents = CleanupFileContents($@"
<Project ToolsVersion='msbuilddefaulttoolsversion' DefaultTargets='Build' xmlns='msbuildnamespace'>
<Target Name='Build'>
<MsBuild Projects='{tempProject}' Targets='BuildA'/>
<MsBuild Projects='{tempProject}' Targets='BuildA'/>
</Target>
</Project>
");
string projectContents = CleanupFileContents(@"
<Project ToolsVersion='msbuilddefaulttoolsversion' DefaultTargets='Build' xmlns='msbuildnamespace'>
<PropertyGroup>
<InitialProperty1>InitialProperty1</InitialProperty1>
<InitialProperty2>InitialProperty2</InitialProperty2>
<InitialProperty3>InitialProperty3</InitialProperty3>
</PropertyGroup>
<Target Name='BuildA'>
<Message Text='BuildA' Importance='High'/>
<Message Text='[success]'/>
</Target>
</Project>
");
File.WriteAllText(tempProject, projectContents);
_env.SetEnvironmentVariable("MsBuildForwardPropertiesFromChild", "InitialProperty3;IAMNOTREAL");
_env.SetEnvironmentVariable("MSBUILDNOINPROCNODE", "1");
var project = CreateProject(contents, null, _projectCollection, false);
var data = new BuildRequestData(project.FullPath, new Dictionary<string, string>(),
MSBuildDefaultToolsVersion, new string[] { }, null);
BuildResult result = _buildManager.Build(_parameters, data);
Assert.Equal(BuildResultCode.Success, result.OverallResult);
_logger.AssertLogContains("[success]");
Assert.Equal(3, _logger.ProjectStartedEvents.Count);
ProjectStartedEventArgs projectStartedEvent = _logger.ProjectStartedEvents[1];
// After conversion to xunit, this test sometimes fails at this assertion.
// Related to shared state that the test touches that's getting handled
// differently in xunit?
Assert.NotNull(projectStartedEvent.Properties);
Dictionary<string, string> properties = ExtractProjectStartedPropertyList(projectStartedEvent.Properties);
Assert.NotNull(properties);
Assert.Single(properties);
Assert.True(properties.TryGetValue("InitialProperty3", out string propertyValue));
Assert.Equal("InitialProperty3", propertyValue);
projectStartedEvent = _logger.ProjectStartedEvents[2];
Assert.Null(projectStartedEvent.Properties);
}
/// <summary>
/// Make sure when if the environment variable MsBuildForwardPropertiesFromChild is set to empty and
/// we launch a child node that we get no properties
/// </summary>
#if MONO
[Fact(Skip = "https://github.com/Microsoft/msbuild/issues/1240")]
#else
[Fact]
#endif
public void ForwardNoPropertiesLaunchChildNode()
{
string contents = CleanupFileContents(@"
<Project xmlns='msbuildnamespace' ToolsVersion='msbuilddefaulttoolsversion'>
<PropertyGroup>
<InitialProperty1>InitialProperty1</InitialProperty1>
<InitialProperty2>InitialProperty2</InitialProperty2>
<InitialProperty3>InitialProperty3</InitialProperty3>
</PropertyGroup>
<Target Name='test'>
<Message Text='[success]'/>
</Target>
</Project>
");
_env.SetEnvironmentVariable("MsBuildForwardPropertiesFromChild", "");
_env.SetEnvironmentVariable("MSBUILDNOINPROCNODE", "1");
var project = CreateProject(contents, null, _projectCollection, false);
var data = new BuildRequestData(project.FullPath, new Dictionary<string, string>(),
MSBuildDefaultToolsVersion, new string[] { }, null);
BuildResult result = _buildManager.Build(_parameters, data);
Assert.Equal(BuildResultCode.Success, result.OverallResult);
_logger.AssertLogContains("[success]");
Assert.Single(_logger.ProjectStartedEvents);
ProjectStartedEventArgs projectStartedEvent = _logger.ProjectStartedEvents[0];
Dictionary<string, string> properties = ExtractProjectStartedPropertyList(projectStartedEvent.Properties);
Assert.Null(properties);
}
/// <summary>
/// We want to pass the toolsets from the parent to the child nodes so that any custom toolsets
/// defined on the parent are also available on the child nodes for tasks which use the global project
/// collection
/// </summary>
#if RUNTIME_TYPE_NETCORE
[Fact(Skip = "https://github.com/Microsoft/msbuild/issues/933")]
#elif MONO
[Fact(Skip = "https://github.com/Microsoft/msbuild/issues/1240")]
#else
[Fact]
#endif
public void VerifyCustomToolSetsPropagated()
{
string netFrameworkDirectory = ToolLocationHelper.GetPathToDotNetFrameworkReferenceAssemblies(TargetDotNetFrameworkVersion.Version45);
string contents = CleanupFileContents(@"
<Project xmlns='msbuildnamespace' ToolsVersion='msbuilddefaulttoolsversion'>
<UsingTask TaskName='VerifyGlobalProjectCollection' TaskFactory='CodeTaskFactory' AssemblyFile='$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll'>
<Task>
<Using Namespace='Microsoft.Build.Evaluation'/>
<Reference Include='$(MSBuildToolsPath)\Microsoft.Build.dll'/>
<Code Type='Method'>
<![CDATA[
public override bool Execute()
{
bool foundToolSet = false;
foreach(Toolset t in ProjectCollection.GlobalProjectCollection.Toolsets)
{
if(t.ToolsVersion.Equals(""CustomToolSet"", StringComparison.OrdinalIgnoreCase))
{
foundToolSet = true;
break;
}
}
Log.LogMessage(MessageImportance.High, ""foundToolset:"" + foundToolSet.ToString());
return foundToolSet;
}
]]>
</Code>
</Task>
</UsingTask>
<Target Name='Build'>
<VerifyGlobalProjectCollection/>
</Target>
</Project>");
_env.SetEnvironmentVariable("MSBUILDNOINPROCNODE", "1");
var projectCollection = new ProjectCollection();
var newToolSet = new Toolset("CustomToolSet", "c:\\SomePath", projectCollection, null);
projectCollection.AddToolset(newToolSet);
var project = CreateProject(contents, null, projectCollection, false);
var data = new BuildRequestData(project.FullPath, new Dictionary<string, string>(),
MSBuildDefaultToolsVersion, new string[] { }, null);
var customParameters = new BuildParameters(projectCollection) { Loggers = new ILogger[] { _logger } };
BuildResult result = _buildManager.Build(customParameters, data);
Assert.Equal(BuildResultCode.Success, result.OverallResult);
}
/// <summary>
/// When a child node is launched by default we should not send any properties.
/// we launch a child node that we get no properties
/// </summary>
#if MONO
[Fact(Skip = "https://github.com/Microsoft/msbuild/issues/1240")]
#else
[Fact]
#endif
public void ForwardNoPropertiesLaunchChildNodeDefault()
{
string contents = CleanupFileContents(@"
<Project xmlns='msbuildnamespace' ToolsVersion='msbuilddefaulttoolsversion'>
<PropertyGroup>
<InitialProperty1>InitialProperty1</InitialProperty1>
<InitialProperty2>InitialProperty2</InitialProperty2>
<InitialProperty3>InitialProperty3</InitialProperty3>
</PropertyGroup>
<Target Name='test'>
<Message Text='[success]'/>
</Target>
</Project>
");
_env.SetEnvironmentVariable("MsBuildForwardPropertiesFromChild", null);
_env.SetEnvironmentVariable("MSBUILDNOINPROCNODE", "1");
var project = CreateProject(contents, null, _projectCollection, false);
var data = new BuildRequestData(project.FullPath, new Dictionary<string, string>(),
MSBuildDefaultToolsVersion, new string[] { }, null);
BuildResult result = _buildManager.Build(_parameters, data);
Assert.Equal(BuildResultCode.Success, result.OverallResult);
_logger.AssertLogContains("[success]");
Assert.Single(_logger.ProjectStartedEvents);
ProjectStartedEventArgs projectStartedEvent = _logger.ProjectStartedEvents[0];
Dictionary<string, string> properties = ExtractProjectStartedPropertyList(projectStartedEvent.Properties);
Assert.Null(properties);
}
/// <summary>
/// A simple failing build.
/// </summary>
[Fact]
public void SimpleBuildWithFailure()
{
string contents = CleanupFileContents(@"
<Project xmlns='msbuildnamespace' ToolsVersion='msbuilddefaulttoolsversion'>
<Target Name='test'>
<Error Text='[errormessage]'/>
</Target>
</Project>
");
BuildRequestData data = GetBuildRequestData(contents);
BuildResult result = _buildManager.Build(_parameters, data);
Assert.Equal(BuildResultCode.Failure, result.OverallResult);
_logger.AssertLogContains("[errormessage]");
}
[Fact]
public void DeferredMessageShouldBeLogged()
{
string contents = CleanupFileContents(@"
<Project>
<Target Name='Build'>
<Message Text='[Message]' Importance='high'/>
<Warning Text='[Warn]'/>
</Target>
</Project>
");
MockLogger logger;
const string highMessage = "deferred[High]";
const string normalMessage = "deferred[Normal]";
const string lowMessage = "deferred[Low]";
using (var buildManagerSession = new Helpers.BuildManagerSession(
_env,
deferredMessages: new[]
{
new BuildManager.DeferredBuildMessage(highMessage, MessageImportance.High),
new BuildManager.DeferredBuildMessage(normalMessage, MessageImportance.Normal),
new BuildManager.DeferredBuildMessage(lowMessage, MessageImportance.Low)
}))
{
var result = buildManagerSession.BuildProjectFile(_env.CreateFile("build.proj", contents).Path);
result.OverallResult.ShouldBe(BuildResultCode.Success);
logger = buildManagerSession.Logger;
}
logger.AssertLogContains("[Warn]");
logger.AssertLogContains("[Message]");
logger.AssertLogContains(highMessage);
logger.AssertLogContains(normalMessage);
logger.AssertLogContains(lowMessage);
var deferredMessages = logger.BuildMessageEvents.Where(e => e.Message.StartsWith("deferred")).ToArray();