-
Notifications
You must be signed in to change notification settings - Fork 1k
/
GivenAResolveTargetingPackAssetsTask.cs
412 lines (324 loc) · 18.5 KB
/
GivenAResolveTargetingPackAssetsTask.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using FluentAssertions;
using Microsoft.Build.Framework;
using Microsoft.NET.TestFramework;
using System.Reflection;
using System.Runtime.CompilerServices;
using Xunit;
using Xunit.Abstractions;
using static Microsoft.NET.Build.Tasks.ResolveTargetingPackAssets;
namespace Microsoft.NET.Build.Tasks.UnitTests
{
public class GivenAResolveTargetingPackAssetsTask : SdkTest
{
public GivenAResolveTargetingPackAssetsTask(ITestOutputHelper log)
: base(log)
{
}
[Fact]
public void Given_ResolvedTargetingPacks_with_valid_PATH_in_PlatformManifest_It_resolves_TargetingPack()
{
ResolveTargetingPackAssets task = InitializeMockTargetingPackAssetsDirectory(out string mockPackageDirectory);
task.Execute().Should().BeTrue();
var reference = task.ReferencesToAdd[0];
reference.ItemSpec.Should().Be(Path.Combine(mockPackageDirectory, "lib/Microsoft.Windows.SDK.NET.dll"));
reference.GetMetadata("AssemblyName").Should().Be("Microsoft.Windows.SDK.NET");
reference.GetMetadata("AssemblyVersion").Should().Be("10.0.18362.3");
reference.GetMetadata("FileVersion").Should().Be("10.0.18362.3");
reference.GetMetadata("PublicKeyToken").Should().Be("null");
reference.GetMetadata("FrameworkReferenceName").Should().Be("Microsoft.Windows.SDK.NET.Ref");
reference.GetMetadata("FrameworkReferenceVersion").Should().Be("5.0.0-preview1");
task.PlatformManifests[0].ItemSpec.Should().Be(Path.Combine(mockPackageDirectory, $"data{Path.DirectorySeparatorChar}PlatformManifest.txt"));
task.AnalyzersToAdd.Length.Should().Be(2);
task.AnalyzersToAdd[0].ItemSpec.Should().Be(Path.Combine(mockPackageDirectory, "analyzers/dotnet/anyAnalyzer.dll"));
task.AnalyzersToAdd[1].ItemSpec.Should().Be(Path.Combine(mockPackageDirectory, "analyzers/dotnet/cs/csAnalyzer.dll"));
((MockBuildEngine)task.BuildEngine).RegisteredTaskObjectsQueries.Should().Be(2,
because: "There should be a lookup for the overall and the specific targeting pack");
((MockBuildEngine)task.BuildEngine).RegisteredTaskObjects.Count.Should().Be(2,
because: "There should be a cache entry for the overall lookup and for the specific targeting pack");
}
[Fact]
public void It_Uses_Multiple_Frameworks()
{
ResolveTargetingPackAssets task = InitializeMockTargetingPackAssetsDirectory(out string mockPackageDirectory);
// Add two RuntimeFrameworks that both point to the default targeting pack.
task.RuntimeFrameworks = new[] {
new MockTaskItem("RuntimeFramework1", new Dictionary<string, string>{ ["FrameworkName"] = "Microsoft.Windows.SDK.NET.Ref"}),
new MockTaskItem("RuntimeFramework2", new Dictionary<string, string>{ ["FrameworkName"] = "Microsoft.Windows.SDK.NET.Ref"}),
};
task.Execute().Should().BeTrue();
task.UsedRuntimeFrameworks.Select(item => item.ItemSpec)
.Should().BeEquivalentTo(new[]
{
"RuntimeFramework1",
"RuntimeFramework2",
});
}
[Fact]
public void Given_Passing_ResolvedTargetingPacks_It_Passes_Again_With_Cached_Results()
{
ResolveTargetingPackAssets task1 = InitializeMockTargetingPackAssetsDirectory(out string packageDirectory);
// Save off that build engine to inspect and reuse
MockBuildEngine buildEngine = (MockBuildEngine)task1.BuildEngine;
task1.Execute().Should().BeTrue();
buildEngine.RegisteredTaskObjectsQueries.Should().Be(2,
because: "there should be a lookup for the overall and the specific targeting pack");
buildEngine.RegisteredTaskObjects.Count.Should().Be(2,
because: "there should be a cache entry for the overall lookup and for the specific targeting pack");
ResolveTargetingPackAssets task2 = InitializeTask(packageDirectory, buildEngine);
task2.Execute().Should().BeTrue();
buildEngine.RegisteredTaskObjectsQueries.Should().Be(3,
because: "there should be a hit on the overall lookup this time through");
buildEngine.RegisteredTaskObjects.Count.Should().Be(2,
because: "the cache keys should match");
}
[Fact]
public void Given_Passing_ResolvedTargetingPacks_A_Different_Language_Parses_Again()
{
ResolveTargetingPackAssets task1 = InitializeMockTargetingPackAssetsDirectory(out string packageDirectory);
// Save off that build engine to inspect and reuse
MockBuildEngine buildEngine = (MockBuildEngine)task1.BuildEngine;
task1.Execute().Should().BeTrue();
buildEngine.RegisteredTaskObjectsQueries.Should().Be(2,
because: "there should be a lookup for the overall and the specific targeting pack");
buildEngine.RegisteredTaskObjects.Count.Should().Be(2,
because: "there should be a cache entry for the overall lookup and for the specific targeting pack");
ResolveTargetingPackAssets task2 = InitializeTask(packageDirectory, buildEngine);
task2.ProjectLanguage = "F#";
task2.Execute().Should().BeTrue();
buildEngine.RegisteredTaskObjectsQueries.Should().Be(4,
because: "there should be no hits on the overall or targeting pack lookup this time through");
buildEngine.RegisteredTaskObjects.Count.Should().Be(4,
because: "there should be distinct results for C# and F#");
}
private ResolveTargetingPackAssets InitializeMockTargetingPackAssetsDirectory(out string mockPackageDirectory,
[CallerMemberName] string testName = nameof(GivenAResolvePackageAssetsTask))
{
mockPackageDirectory = _testAssetsManager.CreateTestDirectory(testName: testName).Path;
string dataDir = Path.Combine(mockPackageDirectory, "data");
Directory.CreateDirectory(dataDir);
File.WriteAllText(Path.Combine(dataDir, "FrameworkList.xml"), _frameworkList);
File.WriteAllText(Path.Combine(dataDir, "PlatformManifest.txt"), "");
return InitializeTask(mockPackageDirectory, new MockBuildEngine());
}
private ResolveTargetingPackAssets InitializeTask(string mockPackageDirectory, IBuildEngine buildEngine)
{
var task = new ResolveTargetingPackAssets()
{
BuildEngine = buildEngine,
};
task.FrameworkReferences = DefaultFrameworkReferences();
task.ResolvedTargetingPacks = DefaultTargetingPacks(mockPackageDirectory);
task.ProjectLanguage = "C#";
return task;
}
private static MockTaskItem[] DefaultTargetingPacks(string mockPackageDirectory) => new[]
{
new MockTaskItem("Microsoft.Windows.SDK.NET.Ref",
new Dictionary<string, string>()
{
{MetadataKeys.NuGetPackageId, "Microsoft.Windows.SDK.NET.Ref"},
{MetadataKeys.NuGetPackageVersion, "5.0.0-preview1"},
{MetadataKeys.PackageConflictPreferredPackages, "Microsoft.Windows.SDK.NET.Ref;"},
{MetadataKeys.PackageDirectory, mockPackageDirectory},
{MetadataKeys.Path, mockPackageDirectory},
{"TargetFramework", "net5.0"}
})
};
private static MockTaskItem[] DefaultFrameworkReferences() => new[]
{
new MockTaskItem("Microsoft.Windows.SDK.NET.Ref", new Dictionary<string, string>())
};
private readonly string _frameworkList =
@"<FileList Name=""cswinrt .NET Core 5.0"">
<File Type=""Managed"" Path=""lib/Microsoft.Windows.SDK.NET.dll"" PublicKeyToken=""null"" AssemblyName=""Microsoft.Windows.SDK.NET"" AssemblyVersion=""10.0.18362.3"" FileVersion=""10.0.18362.3"" />
<File Type=""Analyzer"" Path=""analyzers/dotnet/anyAnalyzer.dll"" PublicKeyToken=""null"" AssemblyName=""anyAnalyzer"" AssemblyVersion=""10.0.18362.3"" FileVersion=""10.0.18362.3"" />
<File Type=""Analyzer"" Language=""cs"" Path=""analyzers/dotnet/cs/csAnalyzer.dll"" PublicKeyToken=""null"" AssemblyName=""csAnalyzer"" AssemblyVersion=""10.0.18362.3"" FileVersion=""10.0.18362.3"" />
<File Type=""Analyzer"" Language=""vb"" Path=""analyzers/dotnet/vb/vbAnalyzer.dll"" PublicKeyToken=""null"" AssemblyName=""vbAnalyzer"" AssemblyVersion=""10.0.18362.3"" FileVersion=""10.0.18362.3"" />
</FileList>";
[Fact]
public void It_Hashes_All_Inputs()
{
IEnumerable<PropertyInfo> inputProperties;
var task = InitializeTaskForHashTesting(out inputProperties);
string oldHash;
try
{
oldHash = task.GetInputs().CacheKey();
}
catch (ArgumentNullException)
{
Assert.True(
false,
nameof(StronglyTypedInputs) + " is likely not correctly handling null value of one or more optional task parameters");
throw; // unreachable
}
foreach (var property in inputProperties)
{
switch (property.PropertyType)
{
case var t when t == typeof(bool):
property.SetValue(task, !(bool)property.GetValue(task));
break;
case var t when t == typeof(string):
property.SetValue(task, property.Name);
break;
case var t when t == typeof(ITaskItem[]):
property.SetValue(task, new[] { new MockTaskItem() { ItemSpec = property.Name } });
// TODO: ideally this would also mutate the relevant metadata per item
break;
default:
Assert.True(false, $"{property.Name} is not a bool or string or ITaskItem[]. Update the test code to handle that.");
throw null; // unreachable
}
string newHash = task.GetInputs().CacheKey();
newHash.Should().NotBe(
oldHash,
because: $"{property.Name} should be included in hash");
oldHash = newHash;
}
}
private ResolveTargetingPackAssets InitializeTaskForHashTesting(out IEnumerable<PropertyInfo> inputProperties)
{
inputProperties = typeof(ResolveTargetingPackAssets)
.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public)
.Where(p => !p.IsDefined(typeof(OutputAttribute)) &&
p.Name != nameof(ResolvePackageAssets.DesignTimeBuild))
.OrderBy(p => p.Name, StringComparer.Ordinal);
var requiredProperties = inputProperties
.Where(p => p.IsDefined(typeof(RequiredAttribute)));
ResolveTargetingPackAssets task = new();
// Initialize all required properties as a genuine task invocation would. We do this
// because HashSettings need not defend against required parameters being null.
foreach (var property in requiredProperties)
{
property.PropertyType.Should().Be(
typeof(string),
because: $"this test hasn't been updated to handle non-string required task parameters like {property.Name}");
property.SetValue(task, "_");
}
return task;
}
[Fact]
public static void It_Hashes_All_Inputs_To_FrameworkList()
{
var constructor = typeof(FrameworkListDefinition).GetConstructors().Single();
var parameters = constructor.GetParameters();
var args = new object[parameters.Length];
for (int i = 0; i < parameters.Length; i++)
{
args[i] = parameters[i].ParameterType switch
{
var t when t == typeof(string) => string.Empty,
_ => throw new NotImplementedException($"{parameters[i].ParameterType} is an unknown type. Update the test code to handle that.")
};
}
FrameworkListDefinition defaultObject = (FrameworkListDefinition)constructor.Invoke(args);
List<string> seenKeys = new List<string>(args.Length + 1);
seenKeys.Add(defaultObject.CacheKey());
for (int i = 0; i < args.Length; i++)
{
args[i] = parameters[i].ParameterType switch
{
var t when t == typeof(string) => "newValue",
var t when t == typeof(ITaskItem) => new MockTaskItem() { ItemSpec = "NewSpec" },
_ => throw new NotImplementedException($"{parameters[i].ParameterType} is an unknown type. Update the test code to handle that.")
};
string newKey = ((FrameworkListDefinition)constructor.Invoke(args)).CacheKey();
seenKeys.Should().NotContain(newKey);
seenKeys.Add(newKey);
}
}
[Fact]
public static void StronglyTypedInputs_Includes_All_Inputs_In_CacheKey()
{
StronglyTypedInputs defaultObject = new(
frameworkReferences: DefaultFrameworkReferences(),
resolvedTargetingPacks: DefaultTargetingPacks(Path.GetTempPath()),
runtimeFrameworks: new[] {new MockTaskItem("RuntimeFramework1", new Dictionary<string, string>()) },
generateErrorForMissingTargetingPacks: true,
nuGetRestoreSupported: true,
disableTransitiveFrameworkReferences: false,
netCoreTargetingPackRoot: "netCoreTargetingPackRoot",
projectLanguage: "C#");
List<string> seenKeys = new();
seenKeys.Add(defaultObject.CacheKey());
foreach (var permutation in Permutations(defaultObject))
{
string newKey = permutation.Inputs.CacheKey();
seenKeys.Should().NotContain(newKey,
because: $"The input {permutation.LastFieldChanged} should be included in the cache key");
seenKeys.Add(newKey);
}
static IEnumerable<(string LastFieldChanged, StronglyTypedInputs Inputs)> Permutations(StronglyTypedInputs input)
{
var properties = typeof(StronglyTypedInputs).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (var property in properties)
{
if (property.PropertyType == typeof(FrameworkReference[]))
{
var currentValue = (FrameworkReference[])property.GetValue(input);
foreach (var subfield in typeof(FrameworkReference).GetProperties())
{
if (subfield.PropertyType == typeof(string))
{
subfield.SetValue(currentValue[0], $"{subfield.Name}_changed");
yield return ($"{property.Name}.{subfield.Name}", input);
continue;
}
Assert.True(false, $"update test to understand fields of type {subfield.PropertyType} in {nameof(FrameworkReference)}");
}
}
else if (property.PropertyType == typeof(TargetingPack[]))
{
var currentValue = (TargetingPack[])property.GetValue(input);
foreach (var subproperty in typeof(TargetingPack).GetProperties())
{
if (subproperty.PropertyType == typeof(string))
{
subproperty.SetValue(currentValue[0], $"{subproperty.Name}_changed");
yield return ($"{property.Name}.{subproperty.Name}", input);
continue;
}
Assert.True(false, $"update test to understand fields of type {subproperty.PropertyType} in {nameof(TargetingPack)}");
}
}
else if (property.PropertyType == typeof(RuntimeFramework[]))
{
var currentValue = (RuntimeFramework[])property.GetValue(input);
foreach (var subproperty in typeof(RuntimeFramework).GetProperties())
{
if (subproperty.PropertyType == typeof(string))
{
subproperty.SetValue(currentValue[0], $"{subproperty.Name}_changed");
yield return ($"{property.Name}.{subproperty.Name}", input);
continue;
}
if (subproperty.PropertyType == typeof(ITaskItem))
{
// Used to store original items but not cache-relevant
continue;
}
Assert.True(false, $"update test to understand fields of type {subproperty.PropertyType} in {nameof(RuntimeFramework)}");
}
}
else if (property.PropertyType == typeof(string))
{
property.SetValue(input, $"{property.Name}_changed");
yield return (property.Name, input);
}
else if (property.PropertyType == typeof(bool))
{
property.SetValue(input, !(bool)property.GetValue(input));
yield return (property.Name, input);
}
else
{
Assert.True(false, $"Unknown type {property.PropertyType} for field {property.Name}");
}
}
}
}
}
}