/
ObjectModelHelpers.cs
2079 lines (1761 loc) · 80.8 KB
/
ObjectModelHelpers.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.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Xml;
using Microsoft.Build.Construction;
using Microsoft.Build.Evaluation;
using Microsoft.Build.Execution;
using Microsoft.Build.FileSystem;
using Microsoft.Build.Framework;
using Microsoft.Build.Graph;
using Microsoft.Build.Logging;
using Microsoft.Build.Shared;
using Microsoft.Build.Shared.FileSystem;
using Shouldly;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.Build.UnitTests
{
/*
* Class: ObjectModelHelpers
*
* Utility methods for unit tests that work through the object model.
*
*/
internal static class ObjectModelHelpers
{
private const string msbuildNamespace = "http://schemas.microsoft.com/developer/msbuild/2003";
private static string s_msbuildDefaultToolsVersion = MSBuildConstants.CurrentToolsVersion;
private static string s_msbuildAssemblyVersion = MSBuildConstants.CurrentAssemblyVersion;
private static string s_currentVisualStudioVersion = MSBuildConstants.CurrentVisualStudioVersion;
/// <summary>
/// Return the current Visual Studio version
/// </summary>
internal static string CurrentVisualStudioVersion
{
get
{
return s_currentVisualStudioVersion;
}
}
/// <summary>
/// Return the default tools version
/// </summary>
internal static string MSBuildDefaultToolsVersion
{
get
{
return s_msbuildDefaultToolsVersion;
}
}
/// <summary>
/// Return the current assembly version
/// </summary>
internal static string MSBuildAssemblyVersion
{
get
{
return s_msbuildAssemblyVersion;
}
}
/// <summary>
/// Helper method to tell us whether a particular metadata name is an MSBuild well-known metadata
/// (e.g., "RelativeDir", "FullPath", etc.)
/// </summary>
private static Hashtable s_builtInMetadataNames;
private static bool IsBuiltInItemMetadataName(string metadataName)
{
if (s_builtInMetadataNames == null)
{
s_builtInMetadataNames = new Hashtable();
Utilities.TaskItem dummyTaskItem = new Utilities.TaskItem();
foreach (string builtInMetadataName in dummyTaskItem.MetadataNames)
{
s_builtInMetadataNames[builtInMetadataName] = string.Empty;
}
}
return s_builtInMetadataNames.Contains(metadataName);
}
/// <summary>
/// Gets an item list from the project and assert that it contains
/// exactly one item with the supplied name.
/// </summary>
internal static ProjectItem AssertSingleItem(Project p, string type, string itemInclude)
{
ProjectItem[] items = p.GetItems(type).ToArray();
int count = 0;
foreach (ProjectItem item in items)
{
Assert.Equal(itemInclude.ToUpperInvariant(), item.EvaluatedInclude.ToUpperInvariant());
++count;
}
Assert.Equal(1, count);
return items[0];
}
internal static void AssertItemEvaluationFromProject(string projectContents, string[] inputFiles, string[] expectedInclude, Dictionary<string, string>[] expectedMetadataPerItem = null, bool normalizeSlashes = false, bool makeExpectedIncludeAbsolute = false)
{
AssertItemEvaluationFromGenericItemEvaluator((p, c) =>
{
return new Project(p, new Dictionary<string, string>(), MSBuildConstants.CurrentToolsVersion, c)
.Items
.Select(i => (TestItem) new ProjectItemTestItemAdapter(i))
.ToList();
},
projectContents,
inputFiles,
expectedInclude,
makeExpectedIncludeAbsolute,
expectedMetadataPerItem,
normalizeSlashes);
}
internal static void AssertItemEvaluationFromGenericItemEvaluator(Func<string, ProjectCollection, IList<TestItem>> itemEvaluator, string projectContents, string[] inputFiles, string[] expectedInclude, bool makeExpectedIncludeAbsolute = false, Dictionary<string, string>[] expectedMetadataPerItem = null, bool normalizeSlashes = false)
{
using (var env = TestEnvironment.Create())
using (var collection = new ProjectCollection())
{
var testProject = env.CreateTestProjectWithFiles(projectContents, inputFiles);
var evaluatedItems = itemEvaluator(testProject.ProjectFile, collection);
if (makeExpectedIncludeAbsolute)
{
expectedInclude = expectedInclude.Select(i => Path.Combine(testProject.TestRoot, i)).ToArray();
}
if (expectedMetadataPerItem == null)
{
AssertItems(expectedInclude, evaluatedItems, expectedDirectMetadata: null, normalizeSlashes: normalizeSlashes);
}
else
{
AssertItems(expectedInclude, evaluatedItems, expectedMetadataPerItem, normalizeSlashes);
}
}
}
internal static string NormalizeSlashes(string path)
{
return path.Replace('/', Path.DirectorySeparatorChar).Replace('\\', Path.DirectorySeparatorChar);
}
// todo Make IItem<M> public and add these new members to it.
internal interface TestItem
{
string EvaluatedInclude { get; }
int DirectMetadataCount { get; }
string GetMetadataValue(string key);
}
internal class ProjectItemTestItemAdapter : TestItem
{
private readonly ProjectItem _projectInstance;
public ProjectItemTestItemAdapter(ProjectItem projectInstance)
{
_projectInstance = projectInstance;
}
public string EvaluatedInclude => _projectInstance.EvaluatedInclude;
public int DirectMetadataCount => _projectInstance.DirectMetadataCount;
public string GetMetadataValue(string key) => _projectInstance.GetMetadataValue(key);
public static implicit operator ProjectItemTestItemAdapter(ProjectItem pi)
{
return new ProjectItemTestItemAdapter(pi);
}
}
internal class ProjectItemInstanceTestItemAdapter : TestItem
{
private readonly ProjectItemInstance _projectInstance;
public ProjectItemInstanceTestItemAdapter(ProjectItemInstance projectInstance)
{
_projectInstance = projectInstance;
}
public string EvaluatedInclude => _projectInstance.EvaluatedInclude;
public int DirectMetadataCount => _projectInstance.DirectMetadataCount;
public string GetMetadataValue(string key) => _projectInstance.GetMetadataValue(key);
public static implicit operator ProjectItemInstanceTestItemAdapter(ProjectItemInstance pi)
{
return new ProjectItemInstanceTestItemAdapter(pi);
}
}
internal static void AssertItems(string[] expectedItems, ICollection<ProjectItem> items, Dictionary<string, string> expectedDirectMetadata = null, bool normalizeSlashes = false)
{
var converteditems = items.Select(i => (TestItem) new ProjectItemTestItemAdapter(i)).ToList();
AssertItems(expectedItems, converteditems, expectedDirectMetadata, normalizeSlashes);
}
/// <summary>
/// Asserts that the list of items has the specified evaluated includes.
/// </summary>
internal static void AssertItems(string[] expectedItems, IList<TestItem> items, Dictionary<string, string> expectedDirectMetadata = null, bool normalizeSlashes = false)
{
if (expectedDirectMetadata == null)
{
expectedDirectMetadata = new Dictionary<string, string>();
}
// all items have the same metadata
var metadata = new Dictionary<string, string>[expectedItems.Length];
for (var i = 0; i < metadata.Length; i++)
{
metadata[i] = expectedDirectMetadata;
}
AssertItems(expectedItems, items, metadata, normalizeSlashes);
}
public static void AssertItems(string[] expectedItems, IList<ProjectItem> items, Dictionary<string, string>[] expectedDirectMetadataPerItem, bool normalizeSlashes = false)
{
var convertedItems = items.Select(i => (TestItem) new ProjectItemTestItemAdapter(i)).ToList();
AssertItems(expectedItems, convertedItems, expectedDirectMetadataPerItem, normalizeSlashes);
}
public static void AssertItems(string[] expectedItems, IList<TestItem> items, Dictionary<string, string>[] expectedDirectMetadataPerItem, bool normalizeSlashes = false)
{
if (items.Count != 0 || expectedDirectMetadataPerItem.Length != 0)
{
expectedItems.ShouldNotBeEmpty();
}
// iterate to the minimum length; if the lengths don't match but there's a prefix match the count assertion below will trigger
int minimumLength = Math.Min(expectedItems.Length, items.Count);
for (var i = 0; i < minimumLength; i++)
{
if (!normalizeSlashes)
{
items[i].EvaluatedInclude.ShouldBe(expectedItems[i]);
}
else
{
var normalizedItem = NormalizeSlashes(expectedItems[i]);
items[i].EvaluatedInclude.ShouldBe(normalizedItem);
}
AssertItemHasMetadata(expectedDirectMetadataPerItem[i], items[i]);
}
items.Count.ShouldBe(expectedItems.Length,
() => $"got items \"{string.Join(", ", items)}\", expected \"{string.Join(", ", expectedItems)}\"");
expectedItems.Length.ShouldBe(expectedDirectMetadataPerItem.Length);
}
/// <summary>
/// Amazingly sophisticated :) helper function to determine if the set of ITaskItems returned from
/// a task match the expected set of ITaskItems. It can also check that the ITaskItems have the expected
/// metadata, and that the ITaskItems are returned in the correct order.
///
/// The "expectedItemsString" is a formatted way of easily specifying which items you expect to see.
/// The format is:
///
/// itemspec1 : metadataname1=metadatavalue1 ; metadataname2=metadatavalue2 ; ...
/// itemspec2 : metadataname3=metadatavalue3 ; metadataname4=metadatavalue4 ; ...
/// itemspec3 : metadataname5=metadatavalue5 ; metadataname6=metadatavalue6 ; ...
///
/// (Each item needs to be on its own line.)
///
/// </summary>
/// <param name="expectedItemsString"></param>
/// <param name="actualItems"></param>
internal static void AssertItemsMatch(string expectedItemsString, ITaskItem[] actualItems)
{
AssertItemsMatch(expectedItemsString, actualItems, true);
}
/// <summary>
/// Amazingly sophisticated :) helper function to determine if the set of ITaskItems returned from
/// a task match the expected set of ITaskItems. It can also check that the ITaskItems have the expected
/// metadata, and that the ITaskItems are returned in the correct order.
///
/// The "expectedItemsString" is a formatted way of easily specifying which items you expect to see.
/// The format is:
///
/// itemspec1 : metadataname1=metadatavalue1 ; metadataname2=metadatavalue2 ; ...
/// itemspec2 : metadataname3=metadatavalue3 ; metadataname4=metadatavalue4 ; ...
/// itemspec3 : metadataname5=metadatavalue5 ; metadataname6=metadatavalue6 ; ...
///
/// (Each item needs to be on its own line.)
///
/// </summary>
/// <param name="expectedItemsString"></param>
/// <param name="actualItems"></param>
/// <param name="orderOfItemsShouldMatch"></param>
internal static void AssertItemsMatch(string expectedItemsString, ITaskItem[] actualItems, bool orderOfItemsShouldMatch)
{
List<ITaskItem> expectedItems = ParseExpectedItemsString(expectedItemsString);
// Form a string of expected item specs. For logging purposes only.
StringBuilder expectedItemSpecs = new StringBuilder();
foreach (ITaskItem expectedItem in expectedItems)
{
if (expectedItemSpecs.Length > 0)
{
expectedItemSpecs.Append("; ");
}
expectedItemSpecs.Append(expectedItem.ItemSpec);
}
// Form a string of expected item specs. For logging purposes only.
StringBuilder actualItemSpecs = new StringBuilder();
foreach (ITaskItem actualItem in actualItems)
{
if (actualItemSpecs.Length > 0)
{
actualItemSpecs.Append("; ");
}
actualItemSpecs.Append(actualItem.ItemSpec);
}
bool outOfOrder = false;
// Loop through all the actual items.
for (int actualItemIndex = 0; actualItemIndex < actualItems.Length; actualItemIndex++)
{
ITaskItem actualItem = actualItems[actualItemIndex];
// Loop through all the expected items to find one with the same item spec.
ITaskItem expectedItem = null;
int expectedItemIndex;
for (expectedItemIndex = 0; expectedItemIndex < expectedItems.Count; expectedItemIndex++)
{
if (expectedItems[expectedItemIndex].ItemSpec == actualItem.ItemSpec)
{
expectedItem = expectedItems[expectedItemIndex];
// If the items are expected to be in the same order, then the expected item
// should always be found at index zero, because we remove items from the expected
// list as we find them.
if ((expectedItemIndex != 0) && orderOfItemsShouldMatch)
{
outOfOrder = true;
}
break;
}
}
Assert.NotNull(expectedItem); // String.Format("Item '{0}' was returned but not expected.", actualItem.ItemSpec));
// Make sure all the metadata on the expected item matches the metadata on the actual item.
// Don't check built-in metadata ... only check custom metadata.
foreach (string metadataName in expectedItem.MetadataNames)
{
// This check filters out any built-in item metadata, like "RelativeDir", etc.
if (!IsBuiltInItemMetadataName(metadataName))
{
string expectedMetadataValue = expectedItem.GetMetadata(metadataName);
string actualMetadataValue = actualItem.GetMetadata(metadataName);
Assert.True(
actualMetadataValue.Length > 0 || expectedMetadataValue.Length == 0,
string.Format("Item '{0}' does not have expected metadata '{1}'.", actualItem.ItemSpec, metadataName)
);
Assert.True(
actualMetadataValue.Length == 0 || expectedMetadataValue.Length > 0,
string.Format("Item '{0}' has unexpected metadata {1}={2}.", actualItem.ItemSpec, metadataName, actualMetadataValue)
);
Assert.Equal(
expectedMetadataValue,
actualMetadataValue
//string.Format
// (
// "Item '{0}' has metadata {1}={2} instead of expected {1}={3}.",
// actualItem.ItemSpec,
// metadataName,
// actualMetadataValue,
// expectedMetadataValue
// )
);
}
}
expectedItems.RemoveAt(expectedItemIndex);
}
// Log an error for any leftover items in the expectedItems collection.
foreach (ITaskItem expectedItem in expectedItems)
{
Assert.True(false, string.Format("Item '{0}' was expected but not returned.", expectedItem.ItemSpec));
}
if (outOfOrder)
{
Console.WriteLine("ERROR: Items were returned in the incorrect order...");
Console.WriteLine("Expected: " + expectedItemSpecs);
Console.WriteLine("Actual: " + actualItemSpecs);
Assert.True(false, "Items were returned in the incorrect order. See 'Standard Out' tab for more details.");
}
}
internal static void AssertItemHasMetadata(Dictionary<string, string> expected, ProjectItem item)
{
AssertItemHasMetadata(expected, new ProjectItemTestItemAdapter(item));
}
internal static void AssertItemHasMetadata(Dictionary<string, string> expected, TestItem item)
{
expected ??= new Dictionary<string, string>();
item.DirectMetadataCount.ShouldBe(expected.Keys.Count, () => $"Expected {expected.Keys.Count} metadata, ({string.Join(", ", expected.Keys)}), got {item.DirectMetadataCount}");
foreach (var key in expected.Keys)
{
item.GetMetadataValue(key).ShouldBe(expected[key]);
}
}
/// <summary>
/// Used to compare the contents of two arrays.
/// </summary>
internal static void AssertArrayContentsMatch(object[] expected, object[] actual)
{
if (expected == null)
{
Assert.Null(actual); // "Expected a null array"
return;
}
Assert.NotNull(actual); // "Result should be non-null."
Assert.Equal(expected.Length, actual.Length); // "Expected array length of <" + expected.Length + "> but was <" + actual.Length + ">.");
// Now that we've verified they're both non-null and of the same length, compare each item in the array.
for (int i = 0; i < expected.Length; i++)
{
Assert.Equal(expected[i], actual[i]); // "At index " + i + " expected " + expected[i].ToString() + " but was " + actual.ToString());
}
}
/// <summary>
/// Parses the crazy string passed into AssertItemsMatch and returns a list of ITaskItems.
/// </summary>
/// <param name="expectedItemsString"></param>
/// <returns></returns>
private static List<ITaskItem> ParseExpectedItemsString(string expectedItemsString)
{
List<ITaskItem> expectedItems = new List<ITaskItem>();
// First, parse this massive string that we've been given, and create an ITaskItem[] out of it,
// so we can more easily compare it against the actual items.
string[] expectedItemsStringSplit = expectedItemsString.Split(MSBuildConstants.CrLf, StringSplitOptions.RemoveEmptyEntries);
foreach (string singleExpectedItemString in expectedItemsStringSplit)
{
string singleExpectedItemStringTrimmed = singleExpectedItemString.Trim();
if (singleExpectedItemStringTrimmed.Length > 0)
{
int indexOfColon = singleExpectedItemStringTrimmed.IndexOf(": ");
if (indexOfColon == -1)
{
expectedItems.Add(new Utilities.TaskItem(singleExpectedItemStringTrimmed));
}
else
{
// We found a colon, which means there's metadata in there.
// The item spec is the part before the colon.
string itemSpec = singleExpectedItemStringTrimmed.Substring(0, indexOfColon).Trim();
// The metadata is the part after the colon.
string itemMetadataString = singleExpectedItemStringTrimmed.Substring(indexOfColon + 1);
ITaskItem expectedItem = new Utilities.TaskItem(itemSpec);
string[] itemMetadataPieces = itemMetadataString.Split(MSBuildConstants.SemicolonChar, StringSplitOptions.RemoveEmptyEntries);
foreach (string itemMetadataPiece in itemMetadataPieces)
{
string itemMetadataPieceTrimmed = itemMetadataPiece.Trim();
if (itemMetadataPieceTrimmed.Length > 0)
{
int indexOfEquals = itemMetadataPieceTrimmed.IndexOf('=');
Assert.NotEqual(-1, indexOfEquals);
string itemMetadataName = itemMetadataPieceTrimmed.Substring(0, indexOfEquals).Trim();
string itemMetadataValue = itemMetadataPieceTrimmed.Substring(indexOfEquals + 1).Trim();
expectedItem.SetMetadata(itemMetadataName, itemMetadataValue);
}
}
expectedItems.Add(expectedItem);
}
}
}
return expectedItems;
}
/// <summary>
/// Assert that a given file exists within the temp project directory.
/// </summary>
/// <param name="fileRelativePath"></param>
internal static void AssertFileExistsInTempProjectDirectory(string fileRelativePath)
{
AssertFileExistsInTempProjectDirectory(fileRelativePath, null);
}
/// <summary>
/// Assert that a given file exists within the temp project directory.
/// </summary>
/// <param name="fileRelativePath"></param>
/// <param name="message">Can be null.</param>
internal static void AssertFileExistsInTempProjectDirectory(string fileRelativePath, string message)
{
if (message == null)
{
message = fileRelativePath + " doesn't exist, but it should.";
}
Assert.True(FileSystems.Default.FileExists(Path.Combine(TempProjectDir, fileRelativePath)), message);
}
/// <summary>
/// Does certain replacements in a string representing the project file contents.
/// This makes it easier to write unit tests because the author doesn't have
/// to worry about escaping double-quotes, etc.
/// </summary>
/// <param name="projectFileContents"></param>
/// <returns></returns>
internal static string CleanupFileContents(string projectFileContents)
{
// Replace reverse-single-quotes with double-quotes.
projectFileContents = projectFileContents.Replace("`", "\"");
// Place the correct MSBuild namespace into the <Project> tag.
projectFileContents = projectFileContents.Replace("msbuildnamespace", msbuildNamespace);
projectFileContents = projectFileContents.Replace("msbuilddefaulttoolsversion", s_msbuildDefaultToolsVersion);
projectFileContents = projectFileContents.Replace("msbuildassemblyversion", s_msbuildAssemblyVersion);
return projectFileContents;
}
public static string Cleanup(this string aString)
{
return CleanupFileContents(aString);
}
/// <summary>
/// Normalizes all the whitespace in an xml string so that two documents that
/// differ only in whitespace can be easily compared to each other for sameness.
/// </summary>
internal static string NormalizeXmlWhitespace(string xml)
{
XmlDocument xmldoc = new XmlDocument();
xmldoc.LoadXml(xml);
// Normalize all the whitespace by writing the Xml document out to a
// string, with PreserveWhitespace=false.
xmldoc.PreserveWhitespace = false;
StringBuilder sb = new StringBuilder(xml.Length);
var writerSettings = new XmlWriterSettings
{
OmitXmlDeclaration = true,
Encoding = Encoding.UTF8,
Indent = true
};
using (var writer = XmlWriter.Create(sb, writerSettings))
{
xmldoc.WriteTo(writer);
}
return sb.ToString();
}
/// <summary>
/// Create an MSBuild project file on disk and return the full path to it.
/// </summary>
/// <param name="xml"></param>
/// <returns></returns>
internal static string CreateTempFileOnDisk(string fileContents, params object[] args)
{
return CreateTempFileOnDiskNoFormat(string.Format(fileContents, args));
}
/// <summary>
/// Create an MSBuild project file on disk and return the full path to it.
/// </summary>
/// <param name="xml"></param>
/// <returns></returns>
internal static string CreateTempFileOnDiskNoFormat(string fileContents)
{
string projectFilePath = FileUtilities.GetTemporaryFile();
File.WriteAllText(projectFilePath, CleanupFileContents(fileContents));
return projectFilePath;
}
internal static ProjectRootElement CreateInMemoryProjectRootElement(string projectContents, ProjectCollection collection = null, bool preserveFormatting = true)
{
var cleanedProject = CleanupFileContents(projectContents);
return ProjectRootElement.Create(
XmlReader.Create(new StringReader(cleanedProject)),
collection ?? new ProjectCollection(),
preserveFormatting);
}
/// <summary>
/// Create a project in memory. Load up the given XML.
/// </summary>
/// <param name="xml"></param>
/// <returns></returns>
internal static Project CreateInMemoryProject(string xml)
{
return CreateInMemoryProject(xml, new ConsoleLogger());
}
/// <summary>
/// Create a project in memory. Load up the given XML.
/// </summary>
/// <param name="xml"></param>
/// <param name="logger"></param>
/// <returns></returns>
internal static Project CreateInMemoryProject(string xml, ILogger logger /* May be null */)
{
return CreateInMemoryProject(new ProjectCollection(), xml, logger);
}
/// <summary>
/// Create an in-memory project and attach it to the passed-in engine.
/// </summary>
/// <param name="engine"></param>
/// <param name="xml"></param>
/// <param name="logger">May be null</param>
/// <returns></returns>
internal static Project CreateInMemoryProject(ProjectCollection e, string xml, ILogger logger /* May be null */)
{
return CreateInMemoryProject(e, xml, logger, null);
}
/// <summary>
/// Create an in-memory project and attach it to the passed-in engine.
/// </summary>
/// <param name="logger">May be null</param>
/// <param name="toolsVersion">May be null</param>
internal static Project CreateInMemoryProject
(
ProjectCollection projectCollection,
string xml,
ILogger logger /* May be null */,
string toolsVersion /* may be null */
)
{
XmlReaderSettings readerSettings = new XmlReaderSettings {DtdProcessing = DtdProcessing.Ignore};
Project project = new Project
(
XmlReader.Create(new StringReader(CleanupFileContents(xml)), readerSettings),
null,
toolsVersion,
projectCollection
);
Guid guid = Guid.NewGuid();
project.FullPath = Path.Combine(TempProjectDir, "Temporary" + guid.ToString("N") + ".csproj");
project.ReevaluateIfNecessary();
if (logger != null)
{
project.ProjectCollection.RegisterLogger(logger);
}
return project;
}
/// <summary>
/// Creates a project in memory and builds the default targets. The build is
/// expected to succeed.
/// </summary>
/// <param name="projectContents"></param>
/// <returns></returns>
internal static MockLogger BuildProjectExpectSuccess
(
string projectContents,
ITestOutputHelper testOutputHelper = null
)
{
MockLogger logger = new MockLogger(testOutputHelper);
BuildProjectExpectSuccess(projectContents, logger);
return logger;
}
internal static void BuildProjectExpectSuccess
(
string projectContents,
params ILogger[] loggers
)
{
Project project = CreateInMemoryProject(projectContents, logger: null); // logger is null so we take care of loggers ourselves
project.Build(loggers).ShouldBeTrue();
}
/// <summary>
/// Creates a project in memory and builds the default targets. The build is
/// expected to fail.
/// </summary>
/// <param name="projectContents"></param>
/// <returns></returns>
internal static MockLogger BuildProjectExpectFailure
(
string projectContents
)
{
MockLogger logger = new MockLogger();
BuildProjectExpectFailure(projectContents, logger);
return logger;
}
internal static void BuildProjectExpectFailure
(
string projectContents,
ILogger logger
)
{
Project project = CreateInMemoryProject(projectContents, logger);
bool success = project.Build(logger);
Assert.False(success); // "Build succeeded, but shouldn't have. See test output (Attachments in Azure Pipelines) for details"
}
/// <summary>
/// This helper method compares the final project contents with the expected
/// value.
/// </summary>
/// <param name="project"></param>
/// <param name="newExpectedProjectContents"></param>
internal static void CompareProjectContents
(
Project project,
string newExpectedProjectContents
)
{
// Get the new XML for the project, normalizing the whitespace.
string newActualProjectContents = project.Xml.RawXml;
// Replace single-quotes with double-quotes, and normalize whitespace.
newExpectedProjectContents = NormalizeXmlWhitespace(CleanupFileContents(newExpectedProjectContents));
// Compare the actual XML with the expected XML.
Console.WriteLine("================================= EXPECTED ===========================================");
Console.WriteLine(newExpectedProjectContents);
Console.WriteLine();
Console.WriteLine("================================== ACTUAL ============================================");
Console.WriteLine(newActualProjectContents);
Console.WriteLine();
Assert.Equal(newExpectedProjectContents, newActualProjectContents); // "Project XML does not match expected XML. See 'Standard Out' tab for details."
}
private static string s_tempProjectDir;
/// <summary>
/// Creates and returns a unique path under temp
/// </summary>
internal static string TempProjectDir
{
get
{
if (s_tempProjectDir == null)
{
s_tempProjectDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(s_tempProjectDir);
}
return s_tempProjectDir;
}
}
/// <summary>
/// Deletes the directory %TEMP%\TempDirForMSBuildUnitTests, and all its contents.
/// </summary>
internal static void DeleteTempProjectDirectory()
{
DeleteDirectory(TempProjectDir);
}
/// <summary>
/// Deletes the directory and all its contents.
/// </summary>
internal static void DeleteDirectory(string dir)
{
// Manually deleting all children, but intentionally leaving the
// Temp project directory behind due to locking issues which were causing
// failures in main on Amd64-WOW runs.
// retries to deal with occasional locking issues where the file / directory can't be deleted to initially
for (int retries = 0; retries < 5; retries++)
{
try
{
if (FileSystems.Default.DirectoryExists(dir))
{
foreach (string directory in Directory.GetDirectories(dir))
{
Directory.Delete(directory, true);
}
foreach (string file in Directory.GetFiles(dir))
{
File.Delete(file);
}
}
break;
}
catch (Exception ex)
{
if (retries < 4)
{
Console.WriteLine(ex.ToString());
}
else
{
// All the retries have failed. We will now fail with the
// actual problem now instead of with some more difficult-to-understand
// issue later.
throw;
}
}
}
}
/// <summary>
/// Creates a file in the %TEMP%\TempDirForMSBuildUnitTests directory, after cleaning
/// up the file contents (replacing single-back-quote with double-quote, etc.).
/// Silently OVERWRITES existing file.
/// </summary>
internal static string CreateFileInTempProjectDirectory(string fileRelativePath, string fileContents, Encoding encoding = null)
{
Assert.False(string.IsNullOrEmpty(fileRelativePath));
string fullFilePath = Path.Combine(TempProjectDir, fileRelativePath);
Directory.CreateDirectory(Path.GetDirectoryName(fullFilePath));
// retries to deal with occasional locking issues where the file can't be written to initially
for (int retries = 0; retries < 5; retries++)
{
try
{
if (encoding == null)
{
// This method uses UTF-8 encoding without a Byte-Order Mark (BOM)
// https://msdn.microsoft.com/en-us/library/ms143375(v=vs.110).aspx#Remarks
File.WriteAllText(fullFilePath, CleanupFileContents(fileContents));
}
else
{
// If it is necessary to include a UTF-8 identifier, such as a byte order mark, at the beginning of a file,
// use the WriteAllText(String,?String,?Encoding) method overload with UTF8 encoding.
File.WriteAllText(fullFilePath, CleanupFileContents(fileContents), encoding);
}
break;
}
catch (Exception ex)
{
if (retries < 4)
{
Console.WriteLine(ex.ToString());
}
else
{
// All the retries have failed. We will now fail with the
// actual problem now instead of with some more difficult-to-understand
// issue later.
throw;
}
}
}
return fullFilePath;
}
/// <summary>
/// Builds a project file from disk, and asserts if the build does not succeed.
/// </summary>
/// <param name="projectFileRelativePath"></param>
/// <returns></returns>
internal static void BuildTempProjectFileExpectSuccess(string projectFileRelativePath, MockLogger logger)
{
BuildTempProjectFileWithTargetsExpectSuccess(projectFileRelativePath, null, null, logger);
}
/// <summary>
/// Builds a project file from disk, and asserts if the build does not succeed.
/// </summary>
internal static void BuildTempProjectFileWithTargetsExpectSuccess(string projectFileRelativePath, string[] targets, IDictionary<string, string> additionalProperties, MockLogger logger)
{
BuildTempProjectFileWithTargets(projectFileRelativePath, targets, additionalProperties, logger)
.ShouldBeTrue("Build failed. See test output (Attachments in Azure Pipelines) for details");
}
/// <summary>
/// Builds a project file from disk, and asserts if the build succeeds.
/// </summary>
internal static void BuildTempProjectFileExpectFailure(string projectFileRelativePath, MockLogger logger)
{
BuildTempProjectFileWithTargets(projectFileRelativePath, null, null, logger)
.ShouldBeFalse("Build unexpectedly succeeded. See test output (Attachments in Azure Pipelines) for details");
}
/// <summary>
/// Loads a project file from disk
/// </summary>
/// <param name="fileRelativePath"></param>
/// <returns></returns>
internal static Project LoadProjectFileInTempProjectDirectory(string projectFileRelativePath)
{
return LoadProjectFileInTempProjectDirectory(projectFileRelativePath, false /* don't touch project*/);
}
/// <summary>
/// Loads a project file from disk
/// </summary>
/// <param name="fileRelativePath"></param>
/// <returns></returns>
internal static Project LoadProjectFileInTempProjectDirectory(string projectFileRelativePath, bool touchProject)
{
string projectFileFullPath = Path.Combine(TempProjectDir, projectFileRelativePath);
ProjectCollection projectCollection = new ProjectCollection();
Project project = new Project(projectFileFullPath, null, null, projectCollection);
if (touchProject)
{
File.SetLastWriteTime(projectFileFullPath, DateTime.Now);
}
return project;
}
/// <summary>
/// Builds a project file from disk, and asserts if the build does not succeed.
/// </summary>
/// <param name="projectFileRelativePath"></param>
/// <param name="targets"></param>
/// <param name="additionalProperties">Can be null.</param>
/// <param name="logger"></param>
/// <returns></returns>
internal static bool BuildTempProjectFileWithTargets
(
string projectFileRelativePath,
string[] targets,
IDictionary<string, string> globalProperties,
ILogger logger
)
{
// Build the default targets.
List<ILogger> loggers = new List<ILogger>(1);
loggers.Add(logger);
if (string.Equals(Path.GetExtension(projectFileRelativePath), ".sln"))
{
string projectFileFullPath = Path.Combine(TempProjectDir, projectFileRelativePath);
BuildRequestData data = new BuildRequestData(projectFileFullPath, globalProperties ?? new Dictionary<string, string>(), null, targets, null);
BuildParameters parameters = new BuildParameters();
parameters.Loggers = loggers;
BuildResult result = BuildManager.DefaultBuildManager.Build(parameters, data);
return result.OverallResult == BuildResultCode.Success;
}
else
{
Project project = LoadProjectFileInTempProjectDirectory(projectFileRelativePath);
if (globalProperties != null)
{
// add extra properties
foreach (KeyValuePair<string, string> globalProperty in globalProperties)