-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathStyleCopCodeFixVerifier`2.cs
More file actions
381 lines (319 loc) · 16.6 KB
/
Copy pathStyleCopCodeFixVerifier`2.cs
File metadata and controls
381 lines (319 loc) · 16.6 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
// Copyright (c) Contributors to the New StyleCop Analyzers project.
// Licensed under the MIT License. See LICENSE in the project root for license information.
#nullable disable
namespace StyleCop.Analyzers.Test.CSharp6.Verifiers
{
using System;
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.Text;
using StyleCop.Analyzers.Lightup;
using StyleCop.Analyzers.Settings.ObjectModel;
using StyleCop.Analyzers.Test.CSharp6.Helpers;
using Xunit;
internal static class StyleCopCodeFixVerifier<TAnalyzer, TCodeFix>
where TAnalyzer : DiagnosticAnalyzer, new()
where TCodeFix : CodeFixProvider, new()
{
internal static DiagnosticResult Diagnostic()
=> CSharpCodeFixVerifier<TAnalyzer, TCodeFix, DefaultVerifier>.Diagnostic();
internal static DiagnosticResult Diagnostic(string diagnosticId)
=> CSharpCodeFixVerifier<TAnalyzer, TCodeFix, DefaultVerifier>.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(string source, string settings, DiagnosticResult[] expected, CancellationToken cancellationToken)
=> StyleCopDiagnosticVerifier<TAnalyzer>.VerifyCSharpDiagnosticAsync(languageVersion: null, source, settings, 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(string source, string settings, DiagnosticResult[] expected, string fixedSource, CancellationToken cancellationToken)
=> VerifyCSharpFixAsync(languageVersion: null, source, settings, 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, DefaultVerifier>
{
private const int DefaultIndentationSize = 4;
private const int DefaultTabSize = 4;
private const bool DefaultUseTabs = false;
private int indentationSize = DefaultIndentationSize;
private bool useTabs = DefaultUseTabs;
private int tabSize = DefaultTabSize;
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.SemanticStructure;
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
{
return this.indentationSize;
}
set
{
if (this.indentationSize == value)
{
return;
}
this.indentationSize = value;
this.UpdateGlobalAnalyzerConfig();
}
}
/// <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
{
return this.useTabs;
}
set
{
if (this.useTabs == value)
{
return;
}
this.useTabs = value;
this.UpdateGlobalAnalyzerConfig();
}
}
/// <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
{
return this.tabSize;
}
set
{
if (this.tabSize == value)
{
return;
}
this.tabSize = value;
this.UpdateGlobalAnalyzerConfig();
}
}
/// <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 };
}
private void UpdateGlobalAnalyzerConfig()
{
if (!LightupHelpers.SupportsCSharp11)
{
// Options support workspace options in this version
// https://github.com/dotnet/roslyn/issues/66779
return;
}
if (this.TestState.AnalyzerConfigFiles.Count == 1
&& this.TestState.AnalyzerConfigFiles[0].filename == "/.globalconfig")
{
this.TestState.AnalyzerConfigFiles.RemoveAt(0);
}
else if (this.TestState.AnalyzerConfigFiles.Count > 1
|| (this.TestState.AnalyzerConfigFiles.Count > 0 && this.TestState.AnalyzerConfigFiles[0].filename != "/.globalconfig"))
{
throw new NotSupportedException("Additional configuration files are not currently supported by the test");
}
this.TestState.AnalyzerConfigFiles.Add(("/.globalconfig", $@"is_global = true
indent_size = {this.IndentationSize}
indent_style = {(this.UseTabs ? "tab" : "space")}
tab_width = {this.TabSize}
"));
}
// NOTE: If needed, this method can be temporarily updated to default to a preview version
private LanguageVersion? GetDefaultLanguageVersion()
{
// Temporary fix since c# 15 is not yet the default language version in the c# 15 test project.
if (LightupHelpers.SupportsCSharp15)
{
return LanguageVersionEx.Preview;
}
return null;
}
}
}
}