-
Notifications
You must be signed in to change notification settings - Fork 173
/
Copy pathCodeFormatterTests.cs
758 lines (664 loc) · 30.2 KB
/
CodeFormatterTests.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
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information.
using System;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Tools.Tests.Utilities;
using Microsoft.CodeAnalysis.Tools.Tests.XUnit;
using Microsoft.CodeAnalysis.Tools.Utilities;
using Microsoft.Extensions.Logging;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.Tools.Tests
{
public class CodeFormatterTests
{
private static readonly string s_formattedProjectPath = Path.Combine("for_code_formatter", "formatted_project");
private static readonly string s_formattedProjectFilePath = Path.Combine(s_formattedProjectPath, "formatted_project.csproj");
private static readonly string s_formattedSolutionFilePath = Path.Combine("for_code_formatter", "formatted_solution", "formatted_solution.sln");
private static readonly string s_unformattedProjectPath = Path.Combine("for_code_formatter", "unformatted_project");
private static readonly string s_unformattedProjectFilePath = Path.Combine(s_unformattedProjectPath, "unformatted_project.csproj");
private static readonly string s_unformattedProgramFilePath = Path.Combine(s_unformattedProjectPath, "program.cs");
private static readonly string s_unformattedSolutionFilePath = Path.Combine("for_code_formatter", "unformatted_solution", "unformatted_solution.sln");
private static readonly string s_fSharpProjectPath = Path.Combine("for_code_formatter", "fsharp_project");
private static readonly string s_fSharpProjectFilePath = Path.Combine(s_fSharpProjectPath, "fsharp_project.fsproj");
private static readonly string s_generatedProjectPath = Path.Combine("for_code_formatter", "generated_project");
private static readonly string s_generatedProjectFilePath = Path.Combine(s_generatedProjectPath, "generated_project.csproj");
private static readonly string s_codeStyleSolutionPath = Path.Combine("for_code_formatter", "codestyle_solution");
private static readonly string s_codeStyleSolutionFilePath = Path.Combine(s_codeStyleSolutionPath, "codestyle_solution.sln");
private static readonly string s_codeStyleSolutionFilterFilePath = Path.Combine(s_codeStyleSolutionPath, "codestyle_solution_filter.slnf");
private static readonly string s_analyzersSolutionPath = Path.Combine("for_code_formatter", "analyzers_solution");
private static readonly string s_analyzersSolutionFilePath = Path.Combine(s_analyzersSolutionPath, "analyzers_solution.sln");
private static readonly string s_generatorSolutionPath = Path.Combine("for_code_formatter", "generator_solution");
private static readonly string s_generatorSolutionFileName = "generator_solution.sln";
private static string[] EmptyFilesList => Array.Empty<string>();
private Regex FindFormattingLogLine => new Regex(@"((.*)\(\d+,\d+\): (.*))\r|((.*)\(\d+,\d+\): (.*))");
private readonly ITestOutputHelper _output;
public CodeFormatterTests(ITestOutputHelper output)
{
_output = output;
}
[MSBuildFact]
public async Task NoFilesFormattedInFormattedProject()
{
await TestFormatWorkspaceAsync(
s_formattedProjectFilePath,
include: EmptyFilesList,
exclude: EmptyFilesList,
includeGenerated: false,
expectedExitCode: 0,
expectedFilesFormatted: 0,
expectedFileCount: 3);
}
[MSBuildFact]
public async Task NoFilesFormattedInFormattedSolution()
{
await TestFormatWorkspaceAsync(
s_formattedSolutionFilePath,
include: EmptyFilesList,
exclude: EmptyFilesList,
includeGenerated: false,
expectedExitCode: 0,
expectedFilesFormatted: 0,
expectedFileCount: 3);
}
[MSBuildFact]
public async Task FilesFormattedInUnformattedProject()
{
await TestFormatWorkspaceAsync(
s_unformattedProjectFilePath,
include: EmptyFilesList,
exclude: EmptyFilesList,
includeGenerated: false,
expectedExitCode: 0,
expectedFilesFormatted: 2,
expectedFileCount: 6);
}
[MSBuildFact]
public async Task NoFilesFormattedInUnformattedProjectWhenFixingCodeStyle()
{
await TestFormatWorkspaceAsync(
s_unformattedProjectFilePath,
include: EmptyFilesList,
exclude: EmptyFilesList,
includeGenerated: false,
fixCategory: FixCategory.CodeStyle,
codeStyleSeverity: DiagnosticSeverity.Error,
expectedExitCode: 0,
expectedFilesFormatted: 0,
expectedFileCount: 6);
}
[MSBuildFact]
public async Task GeneratedFilesFormattedInUnformattedProject()
{
var log = await TestFormatWorkspaceAsync(
s_unformattedProjectFilePath,
include: EmptyFilesList,
exclude: EmptyFilesList,
includeGenerated: true,
expectedExitCode: 0,
expectedFilesFormatted: 5,
expectedFileCount: 6);
var logLines = log.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries);
Assert.Contains(logLines, line => line.Contains("unformatted_project.AssemblyInfo.cs"));
Assert.Contains(logLines, line => line.Contains("NETCoreApp,Version=v3.1.AssemblyAttributes.cs"));
}
[MSBuildFact]
public async Task FilesFormattedInUnformattedSolution()
{
await TestFormatWorkspaceAsync(
s_unformattedSolutionFilePath,
include: EmptyFilesList,
exclude: EmptyFilesList,
includeGenerated: false,
expectedExitCode: 0,
expectedFilesFormatted: 2,
expectedFileCount: 6);
}
[MSBuildFact]
public async Task FilesFormattedInUnformattedProjectFolder()
{
// Since the code files are beneath the project folder, files are found and formatted.
await TestFormatWorkspaceAsync(
Path.GetDirectoryName(s_unformattedProjectFilePath),
include: EmptyFilesList,
exclude: EmptyFilesList,
includeGenerated: false,
expectedExitCode: 0,
expectedFilesFormatted: 2,
expectedFileCount: 6);
}
[MSBuildFact]
public async Task NoFilesFormattedInUnformattedSolutionFolder()
{
// Since the code files are outside the solution folder, no files are found or formatted.
await TestFormatWorkspaceAsync(
Path.GetDirectoryName(s_unformattedSolutionFilePath),
include: EmptyFilesList,
exclude: EmptyFilesList,
includeGenerated: false,
expectedExitCode: 0,
expectedFilesFormatted: 0,
expectedFileCount: 0);
}
[MSBuildFact]
public async Task FSharpProjectsDoNotCreateException()
{
var log = await TestFormatWorkspaceAsync(
s_fSharpProjectFilePath,
include: EmptyFilesList,
exclude: EmptyFilesList,
includeGenerated: false,
expectedExitCode: 1,
expectedFilesFormatted: 0,
expectedFileCount: 0);
var pattern = string.Format(Resources.Could_not_format_0_Format_currently_supports_only_CSharp_and_Visual_Basic_projects, "(.*)");
var match = new Regex(pattern, RegexOptions.Multiline).Match(log);
Assert.True(match.Success, log);
Assert.EndsWith(s_fSharpProjectFilePath, match.Groups[1].Value);
}
[MSBuildFact]
public async Task OnlyFormatPathsFromList()
{
// To match a folder pattern it needs to end with a directory separator.
var include = new[] { s_unformattedProjectPath + Path.DirectorySeparatorChar };
await TestFormatWorkspaceAsync(
s_unformattedProjectFilePath,
include,
exclude: EmptyFilesList,
includeGenerated: false,
expectedExitCode: 0,
expectedFilesFormatted: 2,
expectedFileCount: 6);
}
[MSBuildFact]
public async Task OnlyFormatFilesFromList()
{
var include = new[] { s_unformattedProgramFilePath };
await TestFormatWorkspaceAsync(
s_unformattedProjectFilePath,
include,
exclude: EmptyFilesList,
includeGenerated: false,
expectedExitCode: 0,
expectedFilesFormatted: 1,
expectedFileCount: 6);
}
[MSBuildFact]
public async Task NoFilesFormattedWhenNotInList()
{
var include = new[] { Path.Combine(s_unformattedProjectPath, "does_not_exist.cs") };
await TestFormatWorkspaceAsync(
s_unformattedProjectFilePath,
include,
exclude: EmptyFilesList,
includeGenerated: false,
expectedExitCode: 0,
expectedFilesFormatted: 0,
expectedFileCount: 6);
}
[MSBuildFact]
public async Task OnlyLogFormattedFiles()
{
var include = new[] { s_unformattedProgramFilePath };
var log = await TestFormatWorkspaceAsync(
s_unformattedSolutionFilePath,
include,
exclude: EmptyFilesList,
includeGenerated: false,
expectedExitCode: 0,
expectedFilesFormatted: 1,
expectedFileCount: 6);
var pattern = string.Format(Resources.Formatted_code_file_0, @"(.*)");
var match = new Regex(pattern, RegexOptions.Multiline).Match(log);
Assert.True(match.Success, log);
Assert.EndsWith("Program.cs", match.Groups[1].Value);
}
[MSBuildFact]
public async Task FormatLocationsLoggedInUnformattedProject()
{
var log = await TestFormatWorkspaceAsync(
s_unformattedProjectFilePath,
include: EmptyFilesList,
exclude: EmptyFilesList,
includeGenerated: false,
expectedExitCode: 0,
expectedFilesFormatted: 2,
expectedFileCount: 6);
var formatLocations = log.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries)
.Where(line => FindFormattingLogLine.Match(line).Success)
.ToArray();
var expectedFormatLocations = new[]
{
@"other_items\OtherClass.cs(5,3): Fix whitespace formatting.",
@"other_items\OtherClass.cs(6,3): Fix whitespace formatting.",
@"other_items\OtherClass.cs(7,5): Fix whitespace formatting.",
@"other_items\OtherClass.cs(8,5): Fix whitespace formatting.",
@"other_items\OtherClass.cs(9,7): Fix whitespace formatting.",
@"other_items\OtherClass.cs(10,5): Fix whitespace formatting.",
@"other_items\OtherClass.cs(11,3): Fix whitespace formatting.",
@"Program.cs(5,3): Fix whitespace formatting.",
@"Program.cs(6,3): Fix whitespace formatting.",
@"Program.cs(7,5): Fix whitespace formatting.",
@"Program.cs(8,5): Fix whitespace formatting.",
@"Program.cs(9,7): Fix whitespace formatting.",
@"Program.cs(10,5): Fix whitespace formatting.",
@"Program.cs(11,3): Fix whitespace formatting.",
@"other_items\OtherClass.cs(12,2): Add final newline.",
@"Program.cs(12,2): Add final newline.",
}.Select(path => path.Replace('\\', Path.DirectorySeparatorChar)).ToArray();
// We can't assert the location of the format message because different platform
// line endings change the position in the file.
Assert.Equal(expectedFormatLocations.Length, formatLocations.Length);
for (var index = 0; index < expectedFormatLocations.Length; index++)
{
var expectedParts = FindFormattingLogLine.Match(expectedFormatLocations[index]);
var formatParts = FindFormattingLogLine.Match(formatLocations[index]);
// Match filename
Assert.Equal(expectedParts.Groups[2].Value, formatParts.Groups[2].Value);
// Match formatter message
Assert.Equal(expectedParts.Groups[3].Value, formatParts.Groups[3].Value);
}
}
[MSBuildFact]
public async Task FormatLocationsNotLoggedInFormattedProject()
{
var log = await TestFormatWorkspaceAsync(
s_formattedProjectFilePath,
include: EmptyFilesList,
exclude: EmptyFilesList,
includeGenerated: false,
expectedExitCode: 0,
expectedFilesFormatted: 0,
expectedFileCount: 3);
var formatLocations = log.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries)
.Where(line => FindFormattingLogLine.Match(line).Success);
Assert.Empty(formatLocations);
}
[MSBuildFact]
public async Task LogFilesThatDontMatchExclude()
{
var include = new[] { s_unformattedProgramFilePath };
var log = await TestFormatWorkspaceAsync(
s_unformattedSolutionFilePath,
include,
exclude: EmptyFilesList,
includeGenerated: false,
expectedExitCode: 0,
expectedFilesFormatted: 1,
expectedFileCount: 6);
var pattern = string.Format(Resources.Formatted_code_file_0, @"(.*)");
var match = new Regex(pattern, RegexOptions.Multiline).Match(log);
Assert.True(match.Success, log);
Assert.EndsWith("Program.cs", match.Groups[1].Value);
}
[MSBuildFact]
public async Task IgnoreFileWhenListedInExcludeList()
{
var include = new[] { s_unformattedProgramFilePath };
await TestFormatWorkspaceAsync(
s_unformattedSolutionFilePath,
include: include,
exclude: include,
includeGenerated: false,
expectedExitCode: 0,
expectedFilesFormatted: 0,
expectedFileCount: 6);
}
[MSBuildFact]
public async Task IgnoreFileWhenContainingFolderListedInExcludeList()
{
var include = new[] { s_unformattedProgramFilePath };
var exclude = new[] { s_unformattedProjectPath };
await TestFormatWorkspaceAsync(
s_unformattedSolutionFilePath,
include: include,
exclude: exclude,
includeGenerated: false,
expectedExitCode: 0,
expectedFilesFormatted: 0,
expectedFileCount: 6);
}
[MSBuildFact]
public async Task IgnoreAllFileWhenExcludingAllFiles()
{
var include = new[] { s_unformattedProgramFilePath };
var exclude = new[] { "**/*.*" };
await TestFormatWorkspaceAsync(
s_unformattedSolutionFilePath,
include: include,
exclude: exclude,
includeGenerated: false,
expectedExitCode: 0,
expectedFilesFormatted: 0,
expectedFileCount: 6);
}
[MSBuildFact]
public async Task NoFilesFormattedInGeneratedProject_WhenNotIncludingGeneratedCode()
{
await TestFormatWorkspaceAsync(
s_generatedProjectFilePath,
include: EmptyFilesList,
exclude: EmptyFilesList,
includeGenerated: false,
expectedExitCode: 0,
expectedFilesFormatted: 0,
expectedFileCount: 3);
}
[MSBuildFact]
public async Task FilesFormattedInGeneratedProject_WhenIncludingGeneratedCode()
{
await TestFormatWorkspaceAsync(
s_generatedProjectFilePath,
include: EmptyFilesList,
exclude: EmptyFilesList,
includeGenerated: true,
expectedExitCode: 0,
expectedFilesFormatted: 3,
expectedFileCount: 3);
}
[MSBuildFact]
public async Task NoFilesFormattedInCodeStyleSolution_WhenNotFixingCodeStyle()
{
await TestFormatWorkspaceAsync(
s_codeStyleSolutionFilePath,
include: EmptyFilesList,
exclude: EmptyFilesList,
includeGenerated: false,
expectedExitCode: 0,
expectedFilesFormatted: 0,
expectedFileCount: 6,
fixCategory: FixCategory.Whitespace | FixCategory.CodeStyle);
}
[MSBuildFact]
public async Task NoFilesFormattedInCodeStyleSolution_WhenFixingCodeStyleErrors()
{
await TestFormatWorkspaceAsync(
s_codeStyleSolutionFilePath,
include: EmptyFilesList,
exclude: EmptyFilesList,
includeGenerated: false,
expectedExitCode: 0,
expectedFilesFormatted: 0,
expectedFileCount: 6,
fixCategory: FixCategory.Whitespace | FixCategory.CodeStyle,
codeStyleSeverity: DiagnosticSeverity.Error);
}
[MSBuildFact]
public async Task FilesFormattedInCodeStyleSolution_WhenFixingCodeStyleWarnings()
{
await TestFormatWorkspaceAsync(
s_codeStyleSolutionFilePath,
include: EmptyFilesList,
exclude: EmptyFilesList,
includeGenerated: false,
expectedExitCode: 0,
expectedFilesFormatted: 2,
expectedFileCount: 6,
fixCategory: FixCategory.Whitespace | FixCategory.CodeStyle,
codeStyleSeverity: DiagnosticSeverity.Warning);
}
[MSBuildFact]
public async Task FilesFormattedInCodeStyleSolutionFilter_WhenFixingCodeStyleWarnings()
{
var restoreExitCode = await Utilities.DotNetHelper.PerformRestoreAsync(s_codeStyleSolutionFilterFilePath, _output);
Assert.Equal(0, restoreExitCode);
await TestFormatWorkspaceAsync(
s_codeStyleSolutionFilterFilePath,
include: EmptyFilesList,
exclude: EmptyFilesList,
includeGenerated: false,
expectedExitCode: 0,
expectedFilesFormatted: 1,
expectedFileCount: 3,
fixCategory: FixCategory.Whitespace | FixCategory.CodeStyle,
codeStyleSeverity: DiagnosticSeverity.Warning);
}
[MSBuildFact]
public async Task NoFilesFormattedInAnalyzersSolution_WhenNotFixingAnalyzers()
{
await TestFormatWorkspaceAsync(
s_analyzersSolutionFilePath,
include: EmptyFilesList,
exclude: EmptyFilesList,
includeGenerated: false,
expectedExitCode: 0,
expectedFilesFormatted: 0,
expectedFileCount: 7,
fixCategory: FixCategory.Whitespace);
}
[MSBuildFact]
public async Task FilesFormattedInAnalyzersSolution_WhenFixingAnalyzerErrors()
{
await TestFormatWorkspaceAsync(
s_analyzersSolutionFilePath,
include: EmptyFilesList,
exclude: EmptyFilesList,
includeGenerated: false,
expectedExitCode: 0,
expectedFilesFormatted: 1,
expectedFileCount: 7,
fixCategory: FixCategory.Whitespace | FixCategory.Analyzers,
analyzerSeverity: DiagnosticSeverity.Error);
}
[MSBuildFact]
public async Task AdditionalDocumentsSavedInAnalyzersSolution_WhenFixingAnalyzerErrors()
{
// Copy solution to temp folder so we can write changes to disk.
var solutionPath = CopyToTempFolder(s_analyzersSolutionPath);
try
{
// Fix PublicAPI analyzer diagnostics.
await TestFormatWorkspaceAsync(
Path.Combine(solutionPath, "library", "library.csproj"),
include: EmptyFilesList,
exclude: EmptyFilesList,
includeGenerated: false,
expectedExitCode: 0,
expectedFilesFormatted: 1,
expectedFileCount: 3,
fixCategory: FixCategory.Analyzers,
analyzerSeverity: DiagnosticSeverity.Warning,
diagnostics: new[] { "RS0016" },
saveFormattedFiles: true);
// Verify that changes were persisted to disk.
var unshippedPublicApi = File.ReadAllText(Path.Combine(solutionPath, "library", "PublicAPI.Unshipped.txt"));
Assert.NotEqual(string.Empty, unshippedPublicApi);
}
finally
{
// Cleanup
Directory.Delete(solutionPath, true);
}
}
[MSBuildFact]
public async Task GeneratorSolution_NoDiagnosticsReported_WhenNotIncludingGenerated()
{
// Copy solution to temp folder so we can write changes to disk.
var solutionPath = CopyToTempFolder(s_generatorSolutionPath);
try
{
var solutionFilePath = Path.Combine(solutionPath, s_generatorSolutionFileName);
var buildExitCode = await Utilities.DotNetHelper.PerformBuildAsync(solutionFilePath, _output);
Assert.Equal(0, buildExitCode);
// Fix PublicAPI analyzer diagnostics.
await TestFormatWorkspaceAsync(
solutionFilePath,
include: EmptyFilesList,
exclude: EmptyFilesList,
includeGenerated: false,
expectedExitCode: 0,
expectedFilesFormatted: 0,
expectedFileCount: 7,
fixCategory: FixCategory.Analyzers,
analyzerSeverity: DiagnosticSeverity.Warning,
diagnostics: new[] { "RS0016" },
saveFormattedFiles: true);
// Verify that changes were persisted to disk.
var unshippedPublicApi = File.ReadAllText(Path.Combine(solutionPath, "console_app", "PublicAPI.Unshipped.txt"));
Assert.Equal(string.Empty, unshippedPublicApi);
}
finally
{
try
{
Directory.Delete(solutionPath, true);
}
catch (UnauthorizedAccessException)
{
// The Windows the generator library may still be locked
}
}
}
[MSBuildFact]
public async Task GeneratorSolution_AdditionalDocumentsUpdated_WhenIncludingGenerated()
{
const string ExpectedPublicApi = @"Greeter
Greeter.Greet() -> void
Greeter.Greeter() -> void";
// Copy solution to temp folder so we can write changes to disk.
var solutionPath = CopyToTempFolder(s_generatorSolutionPath);
try
{
var solutionFilePath = Path.Combine(solutionPath, s_generatorSolutionFileName);
var buildExitCode = await Utilities.DotNetHelper.PerformBuildAsync(solutionFilePath, _output);
Assert.Equal(0, buildExitCode);
// Fix PublicAPI analyzer diagnostics.
await TestFormatWorkspaceAsync(
solutionFilePath,
include: EmptyFilesList,
exclude: EmptyFilesList,
includeGenerated: true,
expectedExitCode: 0,
expectedFilesFormatted: 1,
expectedFileCount: 8,
fixCategory: FixCategory.Analyzers,
analyzerSeverity: DiagnosticSeverity.Warning,
diagnostics: new[] { "RS0016" },
saveFormattedFiles: true);
// Verify that changes were persisted to disk.
var unshippedPublicApi = File.ReadAllText(Path.Combine(solutionPath, "console_app", "PublicAPI.Unshipped.txt"));
Assert.Equal(ExpectedPublicApi, unshippedPublicApi);
}
finally
{
try
{
Directory.Delete(solutionPath, true);
}
catch (UnauthorizedAccessException)
{
// On Windows the generator library may still be locked
}
}
}
internal async Task<string> TestFormatWorkspaceAsync(
string workspaceFilePath,
string[] include,
string[] exclude,
bool includeGenerated,
int expectedExitCode,
int expectedFilesFormatted,
int expectedFileCount,
FixCategory fixCategory = FixCategory.Whitespace,
DiagnosticSeverity codeStyleSeverity = DiagnosticSeverity.Error,
DiagnosticSeverity analyzerSeverity = DiagnosticSeverity.Error,
string[] diagnostics = null,
bool noRestore = false,
bool saveFormattedFiles = false)
{
var currentDirectory = Environment.CurrentDirectory;
Environment.CurrentDirectory = TestProjectsPathHelper.GetProjectsDirectory();
var workspacePath = Path.GetFullPath(workspaceFilePath);
WorkspaceType workspaceType;
if (Directory.Exists(workspacePath))
{
workspaceType = WorkspaceType.Folder;
}
else
{
workspaceType = workspacePath.EndsWith("proj")
? WorkspaceType.Project
: WorkspaceType.Solution;
}
var logger = new TestLogger();
var msBuildPath = MSBuildRegistrar.RegisterInstance();
logger.LogTrace(Resources.Using_msbuildexe_located_in_0, msBuildPath);
var fileMatcher = SourceFileMatcher.CreateMatcher(include, exclude);
var formatOptions = new FormatOptions(
workspacePath,
workspaceType,
noRestore,
LogLevel.Trace,
fixCategory,
codeStyleSeverity,
analyzerSeverity,
diagnostics?.ToImmutableHashSet() ?? ImmutableHashSet<string>.Empty,
ExcludeDiagnostics: ImmutableHashSet<string>.Empty,
saveFormattedFiles,
ChangesAreErrors: false,
fileMatcher,
ReportPath: string.Empty,
IncludeGeneratedFiles: includeGenerated,
BinaryLogPath: null);
var formatResult = await CodeFormatter.FormatWorkspaceAsync(formatOptions, logger, CancellationToken.None);
Environment.CurrentDirectory = currentDirectory;
var log = logger.GetLog();
try
{
Assert.Equal(expectedExitCode, formatResult.ExitCode);
Assert.Equal(expectedFilesFormatted, formatResult.FilesFormatted);
Assert.Equal(expectedFileCount, formatResult.FileCount);
}
catch
{
_output.WriteLine(log);
throw;
}
return log;
}
/// <summary>
/// Copies the specified folder to the temp folder and returns the path.
/// </summary>
private static string CopyToTempFolder(string sourcePath)
{
var fullPath = Path.GetFullPath(sourcePath, TestProjectsPathHelper.GetProjectsDirectory());
var tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
DirectoryCopy(fullPath, tempPath, true);
return tempPath;
static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
{
// Get the subdirectories for the specified directory.
var dir = new DirectoryInfo(sourceDirName);
if (!dir.Exists)
{
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ sourceDirName);
}
var dirs = dir.GetDirectories();
// If the destination directory doesn't exist, create it.
Directory.CreateDirectory(destDirName);
// Get the files in the directory and copy them to the new location.
var files = dir.GetFiles();
foreach (var file in files)
{
var tempPath = Path.Combine(destDirName, file.Name);
file.CopyTo(tempPath, false);
}
// If copying subdirectories, copy them and their contents to new location.
if (copySubDirs)
{
foreach (var subdir in dirs)
{
var tempPath = Path.Combine(destDirName, subdir.Name);
DirectoryCopy(subdir.FullName, tempPath, copySubDirs);
}
}
}
}
}
}