-
Notifications
You must be signed in to change notification settings - Fork 508
/
StyleCopCodeFixVerifier`2.cs
293 lines (244 loc) · 13.6 KB
/
StyleCopCodeFixVerifier`2.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
// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
#nullable disable
namespace StyleCop.Analyzers.Test.Verifiers
{
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using global::LightJson;
using global::LightJson.Serialization;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Testing;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Testing;
using Microsoft.CodeAnalysis.Testing.Verifiers;
using Microsoft.CodeAnalysis.Text;
using StyleCop.Analyzers.Lightup;
using StyleCop.Analyzers.Settings.ObjectModel;
using StyleCop.Analyzers.Test.Helpers;
using Xunit;
internal static class StyleCopCodeFixVerifier<TAnalyzer, TCodeFix>
where TAnalyzer : DiagnosticAnalyzer, new()
where TCodeFix : CodeFixProvider, new()
{
internal static DiagnosticResult Diagnostic()
=> CSharpCodeFixVerifier<TAnalyzer, TCodeFix, XUnitVerifier>.Diagnostic();
internal static DiagnosticResult Diagnostic(string diagnosticId)
=> CSharpCodeFixVerifier<TAnalyzer, TCodeFix, XUnitVerifier>.Diagnostic(diagnosticId);
internal static DiagnosticResult Diagnostic(DiagnosticDescriptor descriptor)
=> new DiagnosticResult(descriptor);
internal static Task VerifyCSharpDiagnosticAsync(string source, DiagnosticResult expected, CancellationToken cancellationToken)
=> StyleCopDiagnosticVerifier<TAnalyzer>.VerifyCSharpDiagnosticAsync(source, expected, cancellationToken);
internal static Task VerifyCSharpDiagnosticAsync(string source, DiagnosticResult[] expected, CancellationToken cancellationToken)
=> StyleCopDiagnosticVerifier<TAnalyzer>.VerifyCSharpDiagnosticAsync(source, expected, cancellationToken);
internal static Task VerifyCSharpDiagnosticAsync(LanguageVersion? languageVersion, string source, DiagnosticResult expected, CancellationToken cancellationToken)
=> StyleCopDiagnosticVerifier<TAnalyzer>.VerifyCSharpDiagnosticAsync(languageVersion, source, expected, cancellationToken);
internal static Task VerifyCSharpDiagnosticAsync(LanguageVersion? languageVersion, string source, DiagnosticResult[] expected, CancellationToken cancellationToken)
=> StyleCopDiagnosticVerifier<TAnalyzer>.VerifyCSharpDiagnosticAsync(languageVersion, source, settings: null, expected, cancellationToken);
internal static Task VerifyCSharpDiagnosticAsync(LanguageVersion? languageVersion, string source, string settings, DiagnosticResult[] expected, CancellationToken cancellationToken)
=> StyleCopDiagnosticVerifier<TAnalyzer>.VerifyCSharpDiagnosticAsync(languageVersion, source, settings, expected, cancellationToken);
internal static Task VerifyCSharpFixAsync(string source, DiagnosticResult expected, string fixedSource, CancellationToken cancellationToken)
=> VerifyCSharpFixAsync(source, new[] { expected }, fixedSource, cancellationToken);
internal static Task VerifyCSharpFixAsync(string source, DiagnosticResult[] expected, string fixedSource, CancellationToken cancellationToken)
{
var test = new CSharpTest
{
TestCode = source,
FixedCode = fixedSource,
};
test.ExpectedDiagnostics.AddRange(expected);
return test.RunAsync(cancellationToken);
}
internal static Task VerifyCSharpFixAsync(LanguageVersion? languageVersion, string source, DiagnosticResult expected, string fixedSource, CancellationToken cancellationToken)
=> VerifyCSharpFixAsync(languageVersion, source, settings: null, new[] { expected }, fixedSource, cancellationToken);
internal static Task VerifyCSharpFixAsync(LanguageVersion? languageVersion, string source, DiagnosticResult[] expected, string fixedSource, CancellationToken cancellationToken)
=> VerifyCSharpFixAsync(languageVersion, source, settings: null, expected, fixedSource, cancellationToken);
internal static Task VerifyCSharpFixAsync(LanguageVersion? languageVersion, string source, string settings, DiagnosticResult[] expected, string fixedSource, CancellationToken cancellationToken)
{
var test = new CSharpTest(languageVersion)
{
TestCode = source,
Settings = settings,
FixedCode = fixedSource,
};
test.ExpectedDiagnostics.AddRange(expected);
return test.RunAsync(cancellationToken);
}
internal class CSharpTest : CSharpCodeFixTest<TAnalyzer, TCodeFix, XUnitVerifier>
{
private const int DefaultIndentationSize = 4;
private const int DefaultTabSize = 4;
private const bool DefaultUseTabs = false;
static CSharpTest()
{
// If we have outdated defaults from the host unit test application targeting an older .NET Framework,
// use more reasonable TLS protocol version for outgoing connections.
if (ServicePointManager.SecurityProtocol == (SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls))
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
}
}
public CSharpTest()
: this(languageVersion: null)
{
}
public CSharpTest(LanguageVersion? languageVersion)
{
this.ReferenceAssemblies = GenericAnalyzerTest.ReferenceAssemblies;
this.LanguageVersion = languageVersion ?? this.GetDefaultLanguageVersion();
this.OptionsTransforms.Add(options =>
options
.WithChangedOption(FormattingOptions.IndentationSize, this.Language, this.IndentationSize)
.WithChangedOption(FormattingOptions.TabSize, this.Language, this.TabSize)
.WithChangedOption(FormattingOptions.UseTabs, this.Language, this.UseTabs));
this.TestState.AdditionalFilesFactories.Add(GenerateSettingsFile);
this.CodeActionValidationMode = CodeActionValidationMode.None;
this.SolutionTransforms.Add((solution, projectId) =>
{
var corlib = solution.GetProject(projectId).MetadataReferences.OfType<PortableExecutableReference>()
.Single(reference => Path.GetFileName(reference.FilePath) == "mscorlib.dll");
var system = solution.GetProject(projectId).MetadataReferences.OfType<PortableExecutableReference>()
.Single(reference => Path.GetFileName(reference.FilePath) == "System.dll");
return solution
.RemoveMetadataReference(projectId, corlib)
.RemoveMetadataReference(projectId, system)
.AddMetadataReference(projectId, corlib.WithAliases(new[] { "global", "corlib" }))
.AddMetadataReference(projectId, system.WithAliases(new[] { "global", "system" }));
});
return;
// Local function
IEnumerable<(string filename, SourceText content)> GenerateSettingsFile()
{
var settings = this.Settings;
StyleCopSettings defaultSettings = new StyleCopSettings();
if (this.IndentationSize != defaultSettings.Indentation.IndentationSize
|| this.UseTabs != defaultSettings.Indentation.UseTabs
|| this.TabSize != defaultSettings.Indentation.TabSize)
{
var indentationSettings = $@"
{{
""settings"": {{
""indentation"": {{
""indentationSize"": {this.IndentationSize},
""useTabs"": {this.UseTabs.ToString().ToLowerInvariant()},
""tabSize"": {this.TabSize}
}}
}}
}}
";
if (string.IsNullOrEmpty(settings))
{
settings = indentationSettings;
}
else
{
JsonObject indentationObject = JsonReader.Parse(indentationSettings).AsJsonObject;
JsonObject settingsObject = JsonReader.Parse(settings).AsJsonObject;
JsonObject mergedSettings = JsonTestHelper.MergeJsonObjects(settingsObject, indentationObject);
using (var writer = new JsonWriter(pretty: true))
{
settings = writer.Serialize(mergedSettings);
}
}
}
if (!string.IsNullOrEmpty(settings))
{
yield return (this.SettingsFileName, SourceText.From(settings));
}
}
}
public SourceFileList TestSources => this.TestState.Sources;
public SourceFileList FixedSources => this.FixedState.Sources;
public SourceFileCollection FixedAdditionalFiles => this.FixedState.AdditionalFiles;
public List<DiagnosticResult> RemainingDiagnostics => this.FixedState.ExpectedDiagnostics;
/// <summary>
/// Gets or sets the value of the <see cref="FormattingOptions.IndentationSize"/> to apply to the test
/// workspace.
/// </summary>
/// <value>
/// The value of the <see cref="FormattingOptions.IndentationSize"/> to apply to the test workspace.
/// </value>
public int IndentationSize { get; set; } = DefaultIndentationSize;
/// <summary>
/// Gets or sets a value indicating whether the <see cref="FormattingOptions.UseTabs"/> option is applied to the
/// test workspace.
/// </summary>
/// <value>
/// The value of the <see cref="FormattingOptions.UseTabs"/> to apply to the test workspace.
/// </value>
public bool UseTabs { get; set; } = DefaultUseTabs;
/// <summary>
/// Gets or sets the value of the <see cref="FormattingOptions.TabSize"/> to apply to the test workspace.
/// </summary>
/// <value>
/// The value of the <see cref="FormattingOptions.TabSize"/> to apply to the test workspace.
/// </value>
public int TabSize { get; set; } = DefaultTabSize;
/// <summary>
/// Gets or sets the content of the settings file to use.
/// </summary>
/// <value>
/// The content of the settings file to use.
/// </value>
public string Settings { get; set; } = null;
/// <summary>
/// Gets or sets the name of the settings file to use.
/// </summary>
/// <value>
/// The name of the settings file to use.
/// </value>
public string SettingsFileName { get; set; } = SettingsHelper.SettingsFileName;
/// <summary>
/// Gets the list of diagnostic identifier that will be explicitly enabled in the compilation options.
/// </summary>
/// <value>
/// The list of explicitly enabled diagnostic identifiers.
/// </value>
public List<string> ExplicitlyEnabledDiagnostics { get; } = new List<string>();
private LanguageVersion? LanguageVersion { get; }
protected override CompilationOptions CreateCompilationOptions()
{
var compilationOptions = base.CreateCompilationOptions();
var specificDiagnosticOptions = compilationOptions.SpecificDiagnosticOptions;
foreach (var id in this.ExplicitlyEnabledDiagnostics)
{
specificDiagnosticOptions = specificDiagnosticOptions.SetItem(id, ReportDiagnostic.Warn);
}
return compilationOptions.WithSpecificDiagnosticOptions(specificDiagnosticOptions);
}
protected override ParseOptions CreateParseOptions()
{
var parseOptions = base.CreateParseOptions();
if (this.LanguageVersion is { } languageVersion)
{
parseOptions = ((CSharpParseOptions)parseOptions).WithLanguageVersion(languageVersion);
}
return parseOptions;
}
protected override IEnumerable<CodeFixProvider> GetCodeFixProviders()
{
var codeFixProvider = new TCodeFix();
Assert.NotSame(WellKnownFixAllProviders.BatchFixer, codeFixProvider.GetFixAllProvider());
return new[] { codeFixProvider };
}
// TODO: Remove when c# 11 is a supported language version
private LanguageVersion? GetDefaultLanguageVersion()
{
// Temporary fix since c# 11 is not yet the default language version
// in the c# 11 test project.
if (LightupHelpers.SupportsCSharp11)
{
return LanguageVersionEx.Preview;
}
return null;
}
}
}
}