CodeCleanupTests.cs 8.4 KB
Newer Older
C
Carol Hu 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System.Collections.Generic;
using System.Collections.Immutable;
using System.ComponentModel.Composition;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeCleanup;
using Microsoft.CodeAnalysis.CSharp.UseExpressionBody;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Diagnostics.CSharp;
14
using Microsoft.CodeAnalysis.Editing;
C
Carol Hu 已提交
15 16 17
using Microsoft.CodeAnalysis.Editor.UnitTests;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Shared.Extensions;
18
using Microsoft.CodeAnalysis.Shared.Utilities;
C
Carol Hu 已提交
19 20
using Microsoft.CodeAnalysis.SolutionCrawler;
using Microsoft.CodeAnalysis.Test.Utilities;
21
using Roslyn.Test.Utilities;
C
Carol Hu 已提交
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
using Xunit;

namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Formatting
{
    [UseExportProvider]
    public class CodeCleanupTests
    {
        [Fact]
        [Trait(Traits.Feature, Traits.Features.CodeCleanup)]
        public Task RemoveUsings()
        {
            var code = @"using System;
using System.Collections.Generic;
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine();
    }
}
";

            var expected = @"using System;
S
Sam Harwell 已提交
45 46

internal class Program
C
Carol Hu 已提交
47
{
S
Sam Harwell 已提交
48
    private static void Main(string[] args)
C
Carol Hu 已提交
49 50 51 52 53
    {
        Console.WriteLine();
    }
}
";
S
Sam Harwell 已提交
54
            return AssertCodeCleanupResult(expected, code);
C
Carol Hu 已提交
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
        }

        [Fact]
        [Trait(Traits.Feature, Traits.Features.CodeCleanup)]
        public Task SortUsings()
        {
            var code = @"using System.Collections.Generic;
using System;
class Program
{
    static void Main(string[] args)
    {
        var list = new List<int>();
        Console.WriteLine(list.Count);
    }
}
";

            var expected = @"using System;
using System.Collections.Generic;
S
Sam Harwell 已提交
75 76

internal class Program
C
Carol Hu 已提交
77
{
S
Sam Harwell 已提交
78
    private static void Main(string[] args)
C
Carol Hu 已提交
79
    {
S
Sam Harwell 已提交
80
        List<int> list = new List<int>();
C
Carol Hu 已提交
81 82 83 84
        Console.WriteLine(list.Count);
    }
}
";
S
Sam Harwell 已提交
85
            return AssertCodeCleanupResult(expected, code);
C
Carol Hu 已提交
86 87
        }

88
        [Fact, WorkItem(36984, "https://github.com/dotnet/roslyn/issues/36984")]
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
        [Trait(Traits.Feature, Traits.Features.CodeCleanup)]
        public Task GroupUsings()
        {
            var code = @"using M;
using System;

internal class Program
{
    private static void Main(string[] args)
    {
        Console.WriteLine(""Hello World!"");

        new Goo();
    }
}

namespace M
{
    public class Goo { }
}
";

            var expected = @"using M;

using System;

internal class Program
{
    private static void Main(string[] args)
    {
        Console.WriteLine(""Hello World!"");

        new Goo();
    }
}

namespace M
{
    public class Goo { }
}
";
            return AssertCodeCleanupResult(expected, code, systemUsingsFirst: false, separateUsingGroups: true);
        }

133
        [Fact, WorkItem(36984, "https://github.com/dotnet/roslyn/issues/36984")]
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
        [Trait(Traits.Feature, Traits.Features.CodeCleanup)]
        public Task SortAndGroupUsings()
        {
            var code = @"using M;
using System;

internal class Program
{
    private static void Main(string[] args)
    {
        Console.WriteLine(""Hello World!"");

        new Goo();
    }
}

namespace M
{
    public class Goo { }
}
";

            var expected = @"using System;

using M;

internal class Program
{
    private static void Main(string[] args)
    {
        Console.WriteLine(""Hello World!"");

        new Goo();
    }
}

namespace M
{
    public class Goo { }
}
";
            return AssertCodeCleanupResult(expected, code, systemUsingsFirst: true, separateUsingGroups: true);
        }

C
Carol Hu 已提交
178 179 180 181 182 183 184 185 186 187 188 189 190 191
        [Fact]
        [Trait(Traits.Feature, Traits.Features.CodeCleanup)]
        public Task FixAddRemoveBraces()
        {
            var code = @"class Program
{
    void Method()
    {
        int a = 0;
        if (a > 0)
            a ++;
    }
}
";
S
Sam Harwell 已提交
192
            var expected = @"internal class Program
C
Carol Hu 已提交
193
{
S
Sam Harwell 已提交
194
    private void Method()
C
Carol Hu 已提交
195 196 197 198 199 200 201 202 203
    {
        int a = 0;
        if (a > 0)
        {
            a++;
        }
    }
}
";
S
Sam Harwell 已提交
204
            return AssertCodeCleanupResult(expected, code);
C
Carol Hu 已提交
205 206 207 208 209 210 211 212 213 214 215 216 217 218
        }

        [Fact]
        [Trait(Traits.Feature, Traits.Features.CodeCleanup)]
        public Task RemoveUnusedVariable()
        {
            var code = @"class Program
{
    void Method()
    {
        int a;
    }
}
";
S
Sam Harwell 已提交
219
            var expected = @"internal class Program
C
Carol Hu 已提交
220
{
S
Sam Harwell 已提交
221
    private void Method()
C
Carol Hu 已提交
222 223 224 225
    {
    }
}
";
S
Sam Harwell 已提交
226
            return AssertCodeCleanupResult(expected, code);
C
Carol Hu 已提交
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
        }

        [Fact]
        [Trait(Traits.Feature, Traits.Features.CodeCleanup)]
        public Task FixAccessibilityModifiers()
        {
            var code = @"class Program
{
    void Method()
    {
        int a;
    }
}
";
            var expected = @"internal class Program
{
    private void Method()
    {
    }
}
";
S
Sam Harwell 已提交
248
            return AssertCodeCleanupResult(expected, code);
C
Carol Hu 已提交
249 250
        }

251
        protected static async Task AssertCodeCleanupResult(string expected, string code, bool systemUsingsFirst = true, bool separateUsingGroups = false)
C
Carol Hu 已提交
252 253 254 255 256 257
        {
            var exportProvider = ExportProviderCache
                .GetOrCreateExportProviderFactory(
                    TestExportProvider.EntireAssemblyCatalogWithCSharpAndVisualBasic.WithParts(typeof(CodeCleanupAnalyzerProviderService)))
                .CreateExportProvider();

C
Cyrus Najmabadi 已提交
258
            using var workspace = TestWorkspace.CreateCSharp(code, exportProvider: exportProvider);
M
Manish Vasani 已提交
259 260 261 262
            workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options
                .WithChangedOption(GenerationOptions.PlaceSystemNamespaceFirst, LanguageNames.CSharp, systemUsingsFirst)));
            workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options
                .WithChangedOption(GenerationOptions.SeparateImportDirectiveGroups, LanguageNames.CSharp, separateUsingGroups)));
263

C
Cyrus Najmabadi 已提交
264 265 266
            // register this workspace to solution crawler so that analyzer service associate itself with given workspace
            var incrementalAnalyzerProvider = workspace.ExportProvider.GetExportedValue<IDiagnosticAnalyzerService>() as IIncrementalAnalyzerProvider;
            incrementalAnalyzerProvider.CreateIncrementalAnalyzer(workspace);
C
Carol Hu 已提交
267

C
Cyrus Najmabadi 已提交
268 269
            var hostdoc = workspace.Documents.Single();
            var document = workspace.CurrentSolution.GetDocument(hostdoc.Id);
C
Carol Hu 已提交
270

C
Cyrus Najmabadi 已提交
271
            var codeCleanupService = document.GetLanguageService<ICodeCleanupService>();
J
JieCarolHu 已提交
272

C
Cyrus Najmabadi 已提交
273
            var enabledDiagnostics = codeCleanupService.GetAllDiagnostics();
J
JieCarolHu 已提交
274

C
Cyrus Najmabadi 已提交
275 276
            var newDoc = await codeCleanupService.CleanupAsync(
                document, enabledDiagnostics, new ProgressTracker(), CancellationToken.None);
C
Carol Hu 已提交
277

C
Cyrus Najmabadi 已提交
278
            var actual = await newDoc.GetTextAsync();
C
Carol Hu 已提交
279

C
Cyrus Najmabadi 已提交
280
            Assert.Equal(expected, actual.ToString());
C
Carol Hu 已提交
281 282
        }

283 284
        [Export(typeof(IHostDiagnosticAnalyzerPackageProvider))]
        private class CodeCleanupAnalyzerProviderService : IHostDiagnosticAnalyzerPackageProvider
C
Carol Hu 已提交
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
        {
            private readonly HostDiagnosticAnalyzerPackage _info;

            [ImportingConstructor]
            public CodeCleanupAnalyzerProviderService()
            {
                _info = new HostDiagnosticAnalyzerPackage("CodeCleanup", GetCompilerAnalyzerAssemblies().Distinct().ToImmutableArray());
            }

            private static IEnumerable<string> GetCompilerAnalyzerAssemblies()
            {
                yield return typeof(CSharpCompilerDiagnosticAnalyzer).Assembly.Location;
                yield return typeof(UseExpressionBodyDiagnosticAnalyzer).Assembly.Location;
            }

            public IAnalyzerAssemblyLoader GetAnalyzerAssemblyLoader()
            {
                return FromFileLoader.Instance;
            }

305
            public ImmutableArray<HostDiagnosticAnalyzerPackage> GetHostDiagnosticAnalyzerPackages()
C
Carol Hu 已提交
306
            {
307
                return ImmutableArray.Create(_info);
C
Carol Hu 已提交
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
            }

            public class FromFileLoader : IAnalyzerAssemblyLoader
            {
                public static FromFileLoader Instance = new FromFileLoader();

                public void AddDependencyLocation(string fullPath)
                {
                }

                public Assembly LoadFromPath(string fullPath)
                {
                    return Assembly.LoadFrom(fullPath);
                }
            }
        }
    }
}