-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathE2ETests.cs
More file actions
641 lines (560 loc) · 23.1 KB
/
Copy pathE2ETests.cs
File metadata and controls
641 lines (560 loc) · 23.1 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
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using ReferenceTrimmer.Loggers.MSVC;
[assembly: Parallelize(Workers = 1, Scope = ExecutionScope.MethodLevel)]
namespace ReferenceTrimmer.Tests;
[TestClass]
public sealed class E2ETests
{
private readonly record struct Warning(string Message, string Project, IEnumerable<string>? AltMessages = null);
private static readonly (string ExePath, string Verb) MSBuild = GetMsBuildExeAndVerb();
private static readonly Regex WarningErrorRegex = new(
@".+: (warning|error) (?<message>.+) \[(?<project>.+)\]",
RegexOptions.Compiled | RegexOptions.ExplicitCapture);
public TestContext? TestContext { get; set; }
[ClassInitialize]
public static void ClassInitialize(TestContext _)
{
// Delete the package cache to avoid reusing old content
if (Directory.Exists("Packages"))
{
Directory.Delete("Packages", recursive: true);
}
}
[TestMethod]
public Task UsedProjectReference()
{
return RunMSBuildAsync(
projectFile: "Library/Library.csproj",
expectedWarnings: []);
}
[TestMethod]
public Task UsedProjectReferenceProduceReferenceAssembly()
{
return RunMSBuildAsync(
projectFile: "Library/Library.csproj",
expectedWarnings: []);
}
[TestMethod]
public Task UsedProjectReferenceNoReferenceAssembly()
{
return RunMSBuildAsync(
projectFile: "Library/Library.csproj",
expectedWarnings: []);
}
[TestMethod]
[DataRow(true)]
[DataRow(false)]
public Task UnusedProjectReference(bool enableReferenceTrimmerDiagnostics)
{
return RunMSBuildAsync(
projectFile: "Library/Library.csproj",
expectedWarnings: new[]
{
new Warning("RT0002: ProjectReference ../Dependency/Dependency.csproj can be removed", "Library/Library.csproj"),
},
enableReferenceTrimmerDiagnostics: enableReferenceTrimmerDiagnostics);
}
[TestMethod]
public Task UnusedProjectReferenceProduceReferenceAssembly()
{
return RunMSBuildAsync(
projectFile: "Library/Library.csproj",
expectedWarnings: new[]
{
new Warning("RT0002: ProjectReference ../Dependency/Dependency.csproj can be removed", "Library/Library.csproj"),
});
}
[TestMethod]
public Task UnusedProjectReferenceNoReferenceAssembly()
{
return RunMSBuildAsync(
projectFile: "Library/Library.csproj",
expectedWarnings: new[]
{
new Warning("RT0002: ProjectReference ../Dependency/Dependency.csproj can be removed", "Library/Library.csproj"),
});
}
[TestMethod]
public Task UnusedProjectReferenceNoWarn()
{
return RunMSBuildAsync(
projectFile: "Library/Library.csproj",
expectedWarnings: []);
}
[TestMethod]
public Task UnusedProjectReferenceTreatAsUsed()
{
return RunMSBuildAsync(
projectFile: "Library/Library.csproj",
expectedWarnings: Array.Empty<Warning>());
}
[TestMethod]
public Task UnusedProjectReferenceSuppressed()
{
return RunMSBuildAsync(
projectFile: "Library/Library.csproj",
expectedWarnings: []);
}
[TestMethod]
public Task UnusedTransitiveProjectReference()
{
return RunMSBuildAsync(
projectFile: "Library/Library.csproj",
expectedWarnings: new[]
{
// Only the Dependency gets the warning. Library doesn't get penalized for a transitive dependency.
new Warning("RT0002: ProjectReference ../TransitiveDependency/TransitiveDependency.csproj can be removed", "Dependency/Dependency.csproj"),
});
}
[TestMethod]
public Task UnusedDirectAndTransitiveProjectReference()
{
return RunMSBuildAsync(
projectFile: "Library/Library.csproj",
expectedWarnings: new[]
{
// Both the Library and Dependency get the warning since both directly referenced it.
new Warning("RT0002: ProjectReference ../TransitiveDependency/TransitiveDependency.csproj can be removed", "Dependency/Dependency.csproj"),
new Warning("RT0002: ProjectReference ../TransitiveDependency/TransitiveDependency.csproj can be removed", "Library/Library.csproj"),
});
}
[TestMethod]
public async Task UsedReferenceHintPath()
{
// For direct references, MSBuild can't determine build order so we need to ensure the dependency is already built
await RunMSBuildAsync(
projectFile: "Dependency/Dependency.csproj",
expectedWarnings: []);
await RunMSBuildAsync(
projectFile: "Library/Library.csproj",
expectedWarnings: []);
}
[TestMethod]
public async Task UsedReferenceItemSpec()
{
// For direct references, MSBuild can't determine build order so we need to ensure the dependency is already built
await RunMSBuildAsync(
projectFile: "Dependency/Dependency.csproj",
expectedWarnings: []);
await RunMSBuildAsync(
projectFile: "Library/Library.csproj",
expectedWarnings: []);
}
[TestMethod]
public async Task UnusedReferenceHintPath()
{
// For direct references, MSBuild can't determine build order so we need to ensure the dependency is already built
await RunMSBuildAsync(
projectFile: "Dependency/Dependency.csproj",
expectedWarnings: []);
await RunMSBuildAsync(
projectFile: "Library/Library.csproj",
expectedWarnings: new[]
{
new Warning("RT0001: Reference Dependency can be removed", "Library/Library.csproj"),
});
}
[TestMethod]
public async Task UnusedReferenceHintPathNoWarn()
{
// For direct references, MSBuild can't determine build order so we need to ensure the dependency is already built
await RunMSBuildAsync(
projectFile: "Dependency/Dependency.csproj",
expectedWarnings: []);
await RunMSBuildAsync(
projectFile: "Library/Library.csproj",
expectedWarnings: []);
}
[TestMethod]
public async Task UnusedReferenceHintPathTreatAsUsed()
{
// For direct references, MSBuild can't determine build order so we need to ensure the dependency is already built
await RunMSBuildAsync(
projectFile: "Dependency/Dependency.csproj",
expectedWarnings: Array.Empty<Warning>());
await RunMSBuildAsync(
projectFile: "Library/Library.csproj",
expectedWarnings: Array.Empty<Warning>());
}
[TestMethod]
public async Task UnusedReferenceItemSpec()
{
// For direct references, MSBuild can't determine build order so we need to ensure the dependency is already built
await RunMSBuildAsync(
projectFile: "Dependency/Dependency.csproj",
expectedWarnings: []);
await RunMSBuildAsync(
projectFile: "Library/Library.csproj",
expectedWarnings: new[]
{
new Warning(
OperatingSystem.IsWindows()
? @"RT0001: Reference ..\Dependency\bin\x64\Debug\net472\\Dependency.dll can be removed"
: @"RT0001: Reference ../Dependency/bin/x64/Debug/net472/Dependency.dll can be removed",
"Library/Library.csproj",
[
// Alt: Can leave out 'x64' path segment on VS or Linux.
@"RT0001: Reference ..\Dependency\bin\Debug\net472\\Dependency.dll can be removed",
@"RT0001: Reference ../Dependency/bin/Debug/net472/Dependency.dll can be removed",
]),
});
}
[TestMethod]
public async Task UnusedReferenceItemSpecNoWarn()
{
// For direct references, MSBuild can't determine build order so we need to ensure the dependency is already built
await RunMSBuildAsync(
projectFile: "Dependency/Dependency.csproj",
expectedWarnings: []);
await RunMSBuildAsync(
projectFile: "Library/Library.csproj",
expectedWarnings: []);
}
[TestMethod]
public async Task UnusedReferenceItemSpecTreatAsUsed()
{
// For direct references, MSBuild can't determine build order so we need to ensure the dependency is already built
await RunMSBuildAsync(
projectFile: "Dependency/Dependency.csproj",
expectedWarnings: Array.Empty<Warning>());
await RunMSBuildAsync(
projectFile: "Library/Library.csproj",
expectedWarnings: Array.Empty<Warning>());
}
[TestMethod]
[OSCondition(OperatingSystems.Windows, IgnoreMessage = "The GAC is Windows-specific")]
public async Task UnusedReferenceFromGac()
{
await RunMSBuildAsync(
projectFile: "Library.csproj",
expectedWarnings: new[]
{
new Warning("RT0001: Reference Microsoft.Office.Interop.Outlook can be removed", "Library.csproj"),
});
}
[TestMethod]
[OSCondition(OperatingSystems.Windows, IgnoreMessage = "The GAC is Windows-specific")]
public async Task UsedReferenceFromGac()
{
await RunMSBuildAsync(
projectFile: "Library.csproj",
expectedWarnings: []);
}
[TestMethod]
public Task UsedPackageReference()
{
return RunMSBuildAsync(
projectFile: "Library/Library.csproj",
expectedWarnings: []);
}
[TestMethod]
public Task UsedIndirectPackageReference()
{
return RunMSBuildAsync(
projectFile: "WebHost/WebHost.csproj",
expectedWarnings: []);
}
[TestMethod]
public Task UnusedPackageReference()
{
return RunMSBuildAsync(
projectFile: "Library/Library.csproj",
expectedWarnings: new[]
{
new Warning("RT0003: PackageReference Newtonsoft.Json can be removed", "Library/Library.csproj")
});
}
[TestMethod]
public Task UnusedPackageReferenceWithSdk()
{
return RunMSBuildAsync(
projectFile: "Test/Test.csproj",
expectedWarnings:
[
new Warning("RT0003: PackageReference Moq can be removed", "Test/Test.csproj")
]);
}
[TestMethod]
public Task UnusedPackageReferenceNoWarn()
{
return RunMSBuildAsync(
projectFile: "Library/Library.csproj",
expectedWarnings: []);
}
[TestMethod]
public Task UnusedPackageReferenceTreatAsUsed()
{
return RunMSBuildAsync(
projectFile: "Library/Library.csproj",
expectedWarnings: []);
}
[TestMethod]
public Task UnusedPackageReferenceDocDisabled()
{
return RunMSBuildAsync(
projectFile: "Library/Library.csproj",
expectedWarnings: new[]
{
new Warning("RT0000: Enable /doc parameter or in MSBuild set <GenerateDocumentationFile>true</GenerateDocumentationFile> for accuracy of used references detection", "Library/Library.csproj")
});
}
[TestMethod]
public Task BuildPackageReference()
{
return RunMSBuildAsync(
projectFile: "Library/Library.csproj",
expectedWarnings: []);
}
[TestMethod]
public Task MissingReferenceSourceTarget()
{
return RunMSBuildAsync(
projectFile: "Library/Library.csproj",
expectedWarnings: []);
}
[TestMethod]
public Task PlatformPackageConflictResolution()
{
return RunMSBuildAsync(
projectFile: "Library/Library.csproj",
expectedWarnings: new[]
{
// TODO: These "metapackages" should not be reported.
new Warning("RT0003: PackageReference NETStandard.Library can be removed", "Library/Library.csproj"),
});
}
[TestMethod]
public Task NoTargets()
{
return RunMSBuildAsync(
projectFile: "Project.csproj",
expectedWarnings: []);
}
[TestMethod]
public Task TargetFrameworkWithOs()
{
return RunMSBuildAsync(
projectFile: "Library/Library.csproj",
expectedWarnings: []);
}
[TestMethod]
public Task AbsoluteIntermediateOutputPath()
{
return RunMSBuildAsync(
projectFile: "Library/Library.csproj",
expectedWarnings: []);
}
[TestMethod]
public Task BuildExtensions()
{
return RunMSBuildAsync(
projectFile: "Library/Library.csproj",
expectedWarnings: []);
}
[TestMethod]
public Task ReferenceInPackage()
{
return RunMSBuildAsync(
projectFile: "Tests/Tests.csproj",
expectedWarnings: []);
}
[TestMethod]
public Task ReferenceTrimmerDisabled()
{
return RunMSBuildAsync(
projectFile: "Library/Library.csproj",
expectedWarnings: []);
}
[TestMethod]
[OSCondition(OperatingSystems.Windows, IgnoreMessage = "This test only applies to Windows")]
public async Task LegacyStyleProject()
{
await RunMSBuildAsync(
projectFile: "Library/Library.csproj",
expectedWarnings: []);
}
[TestMethod]
[OSCondition(OperatingSystems.Windows, IgnoreMessage = "This test only applies to Windows")]
public async Task UnusedWinSdkImportLibrary()
{
await RunMSBuildAsync(
projectFile: "App/App.vcxproj",
expectedWarnings: [],
expectedConsoleOutputs:
[
"Unused libraries:", // Ensure link.exe unused lib flags are active
@"\user32.lib", // Tail of variable unused lib paths like "C:\Program Files (x86)\Windows Kits\10\lib\10.0.19041.0\um\x86\user32.lib"
"Unused MSVC libraries detected in project",
" * Default Windows SDK import libraries:",
" - Libraries needed: ",
" - Unneeded: ",
],
expectUnusedMsvcLibrariesLog: true);
}
[TestMethod]
[OSCondition(OperatingSystems.Windows, IgnoreMessage = "This test only applies to Windows")]
public async Task UnusedCppLibrary()
{
await RunMSBuildAsync(
projectFile: "App/App.vcxproj",
expectedWarnings: [],
expectedConsoleOutputs:
[
"Unused libraries:", // Ensure link.exe unused lib flags are active
"Unused MSVC libraries detected in project",
" * Other libraries - ",
@"\Library.lib", // Tail of variable unused lib paths like "C:\Program Files (x86)\Windows Kits\10\lib\10.0.19041.0\um\x86\user32.lib"
],
expectUnusedMsvcLibrariesLog: true);
}
[TestMethod]
[OSCondition(OperatingSystems.Windows, IgnoreMessage = "This test only applies to Windows")]
public async Task UnusedCppDelayLoadLibrary()
{
await RunMSBuildAsync(
projectFile: "App/App.vcxproj",
expectedWarnings: [],
expectedConsoleOutputs:
[
"Unused libraries:", // Ensure link.exe unused lib flags are active
"Unused MSVC libraries detected in project",
" * Other libraries - ",
@"\DLL.lib", // Tail of variable unused lib paths like "C:\Program Files (x86)\Windows Kits\10\lib\10.0.19041.0\um\x86\user32.lib"
],
expectUnusedMsvcLibrariesLog: true);
}
[TestMethod]
public Task WpfApp()
{
return RunMSBuildAsync(
projectFile: "WpfApp/WpfApp.csproj",
expectedWarnings: []);
}
[TestMethod]
public Task PackageReferenceWithFakeBuildFile()
{
return RunMSBuildAsync(
projectFile: "Library/Library.csproj",
expectedWarnings:
[
new Warning("RT0003: PackageReference Microsoft.Extensions.Primitives can be removed", "Library/Library.csproj"),
]);
}
private static (string ExePath, string Verb) GetMsBuildExeAndVerb()
{
// On Windows, try to find Visual Studio
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
// When running from a developer command prompt, Visual Studio can be found under VSINSTALLDIR
string? vsInstallDir = Environment.GetEnvironmentVariable("VSINSTALLDIR");
if (string.IsNullOrEmpty(vsInstallDir))
{
// When running Visual Studio can be found under VSAPPIDDIR
string? vsAppIdeDir = Environment.GetEnvironmentVariable("VSAPPIDDIR");
if (!string.IsNullOrEmpty(vsAppIdeDir))
{
vsInstallDir = Path.Combine(vsAppIdeDir, "..", "..");
}
}
if (!string.IsNullOrEmpty(vsInstallDir))
{
string msbuildExePath = Path.Combine(vsInstallDir, @"MSBuild\Current\Bin\amd64\MSBuild.exe");
if (!File.Exists(msbuildExePath))
{
throw new InvalidOperationException($"Could not find MSBuild.exe path for unit tests: {msbuildExePath}");
}
return (msbuildExePath, string.Empty);
}
}
// Fall back to just using dotnet. Assume it's on the PATH
return ("dotnet", "build");
}
private async Task RunMSBuildAsync(string projectFile, Warning[] expectedWarnings, string[]? expectedConsoleOutputs = null, bool expectUnusedMsvcLibrariesLog = false, bool enableReferenceTrimmerDiagnostics = false)
{
var testDataSourcePath = Path.GetFullPath(Path.Combine("TestData", TestContext?.TestName ?? string.Empty));
string logDirBase = Path.Combine(testDataSourcePath, "Logs");
string binlogFilePath = Path.Combine(logDirBase, Path.GetFileName(projectFile) + ".binlog");
string warningsFilePath = Path.Combine(logDirBase, Path.GetFileName(projectFile) + ".warnings.log");
string errorsFilePath = Path.Combine(logDirBase, Path.GetFileName(projectFile) + ".errors.log");
TestContext?.WriteLine($"Log directory: {logDirBase}");
string unusedLibraryLogPath = Path.Combine(testDataSourcePath, ForwardingLogger.HelpKeyword + ".json.log");
if (File.Exists(unusedLibraryLogPath))
{
File.Delete(unusedLibraryLogPath);
}
string loggersAssemblyPath = Path.Combine(Environment.CurrentDirectory, "ReferenceTrimmer.Loggers.dll");
string msbuildArgs = $"{MSBuild.Verb} \"{projectFile}\" " +
$"-m:1 -t:Rebuild -restore -nologo -nodeReuse:false -noAutoResponse " +
$"-bl:\"{binlogFilePath}\" " +
$"-flp1:logfile=\"{errorsFilePath}\";errorsonly " +
$"-flp2:logfile=\"{warningsFilePath}\";warningsonly " +
$"-distributedlogger:CentralLogger,\"{loggersAssemblyPath}\"*ForwardingLogger,\"{loggersAssemblyPath}\" " +
(enableReferenceTrimmerDiagnostics ? "-p:EnableReferenceTrimmerDiagnostics=true" : string.Empty);
Process? process = Process.Start(
new ProcessStartInfo
{
FileName = MSBuild.ExePath,
Arguments = msbuildArgs,
WorkingDirectory = testDataSourcePath,
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
});
Assert.IsNotNull(process);
string stdOut = await process.StandardOutput.ReadToEndAsync();
string stdErr = await process.StandardError.ReadToEndAsync();
await process.WaitForExitAsync();
Assert.AreEqual(0, process.ExitCode, $"Build of {projectFile} was not successful.{Environment.NewLine}StandardError: {stdErr}{Environment.NewLine}StandardOutput: {stdOut}");
Assert.AreEqual(File.Exists(unusedLibraryLogPath), expectUnusedMsvcLibrariesLog);
string errors = await File.ReadAllTextAsync(errorsFilePath);
Assert.AreEqual(0, errors.Length, $"Build of {projectFile} was not successful.{Environment.NewLine}Error log: {errors}");
List<Warning> actualWarnings = new();
foreach (string line in await File.ReadAllLinesAsync(warningsFilePath))
{
Match match = WarningErrorRegex.Match(line);
if (match.Success)
{
string message = match.Groups["message"].Value;
string projectFullPath = match.Groups["project"].Value;
string projectRelativePath = projectFullPath[(testDataSourcePath.Length + 1)..];
// Normalize slashes for the project paths
projectRelativePath = projectRelativePath.Replace('\\', '/');
actualWarnings.Add(new Warning(message, projectRelativePath));
}
}
bool warningsMatched = expectedWarnings.Length == actualWarnings.Count;
if (warningsMatched)
{
for (var i = 0; i < actualWarnings.Count; i++)
{
warningsMatched &=
expectedWarnings[i].Project == actualWarnings[i].Project &&
(expectedWarnings[i].Message == actualWarnings[i].Message ||
(expectedWarnings[i].AltMessages is not null &&
expectedWarnings[i].AltMessages!.Any(m => m == actualWarnings[i].Message)));
}
}
Assert.IsTrue(
warningsMatched,
$@"
Expected warnings:
{(expectedWarnings.Length == 0 ? "<none>" : string.Join(Environment.NewLine, expectedWarnings))}
Actual warnings:
{(actualWarnings.Count == 0 ? "<none>" : string.Join(Environment.NewLine, actualWarnings))}");
if (expectedConsoleOutputs is not null)
{
foreach (string expectedLogOutput in expectedConsoleOutputs)
{
Assert.IsTrue(stdOut.Contains(expectedLogOutput, StringComparison.OrdinalIgnoreCase), $"Expected log output '{expectedLogOutput}' was not found. Full console stdout: {stdOut}{Environment.NewLine}Console stderr: {stdErr}");
}
}
// local tests run debug, CI builds run release, thus the assertion needs to look for the file
var usedReferencesFiles = Directory.GetFiles(testDataSourcePath, "_ReferenceTrimmer_UsedReferences.log", SearchOption.AllDirectories);
var unusedReferencesFiles = Directory.GetFiles(testDataSourcePath, "_ReferenceTrimmer_UnusedReferences.log", SearchOption.AllDirectories);
Assert.AreEqual(enableReferenceTrimmerDiagnostics, usedReferencesFiles.Length > 0);
Assert.AreEqual(enableReferenceTrimmerDiagnostics, unusedReferencesFiles.Length > 0);
}
}