コード例 #1
0
        public static void SingleDocumentTwoErrors()
        {
            var code = @"
namespace N
{
    class C
    {
        private readonly int _value1;
        private readonly int _value2;
    }
}";

            var after              = @"
namespace N
{
    class C
    {
        private readonly int value1;
        private readonly int value2;
    }
}";
            var analyzer           = new FieldNameMustNotBeginWithUnderscore();
            var compilationOptions = CodeFactory.DefaultCompilationOptions(analyzer);
            var metadataReferences = new[] { MetadataReference.CreateFromFile(typeof(int).Assembly.Location) };
            var sln         = CodeFactory.CreateSolution(code, compilationOptions, metadataReferences);
            var diagnostics = Analyze.GetDiagnostics(sln, analyzer);
            var fixedSln    = Fix.Apply(sln, new DoNotUseUnderscoreFix(), diagnostics);

            CodeAssert.AreEqual(after, fixedSln.Projects.Single().Documents.Single());
        }
コード例 #2
0
            public void SevenPointThreeFeature()
            {
                var code     = @"
namespace RoslynSandbox
{
    class Foo<T>
        where T : struct, System.Enum
    {
    }
}";
                var analyzer = new NoErrorAnalyzer();

                AnalyzerAssert.Valid <NoErrorAnalyzer>(code);
                AnalyzerAssert.Valid(typeof(NoErrorAnalyzer), code);
                AnalyzerAssert.Valid(analyzer, code);
                AnalyzerAssert.Valid(analyzer, code, CodeFactory.DefaultCompilationOptions(analyzer, AnalyzerAssert.SuppressedDiagnostics), AnalyzerAssert.MetadataReferences);
                AnalyzerAssert.Valid(analyzer, new[] { code }, CodeFactory.DefaultCompilationOptions(analyzer, AnalyzerAssert.SuppressedDiagnostics), AnalyzerAssert.MetadataReferences);

                var descriptor = NoErrorAnalyzer.Descriptor;

                AnalyzerAssert.Valid <NoErrorAnalyzer>(descriptor, code);
                AnalyzerAssert.Valid(typeof(NoErrorAnalyzer), descriptor, code);
                AnalyzerAssert.Valid(analyzer, descriptor, code);

                AnalyzerAssert.Valid <NoErrorAnalyzer>(new[] { descriptor }, code);
                AnalyzerAssert.Valid(typeof(NoErrorAnalyzer), new[] { descriptor }, code);
                AnalyzerAssert.Valid(analyzer, new[] { descriptor }, code);
            }
コード例 #3
0
        public void ConstructorCycle(DiagnosticAnalyzer analyzer)
        {
            var testCode = @"
namespace RoslynSandbox
{
    using System;

    public class Constructors : IDisposable
    {
        private IDisposable disposable;

        public Constructors(int i, IDisposable disposable)
            : this(disposable, i)
        {
            this.disposable = disposable;
        }

        public Constructors(IDisposable disposable, int i)
            : this(i, disposable)
        {
            this.disposable = disposable;
        }

        public void Dispose()
        {
        }
    }
}";
            var solution = CodeFactory.CreateSolution(testCode, CodeFactory.DefaultCompilationOptions(analyzer, AnalyzerAssert.SuppressedDiagnostics), AnalyzerAssert.MetadataReferences);

            AnalyzerAssert.NoDiagnostics(Analyze.GetDiagnostics(analyzer, solution));
        }
コード例 #4
0
        public void SingleClassOneErrorCorrectFixAll()
        {
            var code = @"
namespace RoslynSandbox
{
    class Foo
    {
        private readonly int _value;
    }
}";

            var fixedCode = @"
namespace RoslynSandbox
{
    class Foo
    {
        private readonly int value;
    }
}";
            var analyzer  = new FieldNameMustNotBeginWithUnderscore();
            var cSharpCompilationOptions = CodeFactory.DefaultCompilationOptions(analyzer);
            var metadataReferences       = new[] { MetadataReference.CreateFromFile(typeof(int).Assembly.Location) };
            var sln         = CodeFactory.CreateSolution(code, cSharpCompilationOptions, metadataReferences);
            var diagnostics = Analyze.GetDiagnostics(sln, analyzer);
            var fixedSln    = Fix.Apply(sln, new DontUseUnderscoreCodeFixProvider(), diagnostics);

            CodeAssert.AreEqual(fixedCode, fixedSln.Projects.Single().Documents.Single());
        }
コード例 #5
0
        public static void ConstructorCycle(DiagnosticAnalyzer analyzer)
        {
            var code     = @"
namespace N
{
    using System;

    public sealed class C : IDisposable
    {
        private IDisposable disposable;

        public C(int i, IDisposable disposable)
            : this(disposable, i)
        {
            this.disposable = disposable;
        }

        public C(IDisposable disposable, int i)
            : this(i, disposable)
        {
            this.disposable = disposable;
        }

        public void Dispose()
        {
        }
    }
}";
            var solution = CodeFactory.CreateSolution(code, CodeFactory.DefaultCompilationOptions(analyzer), MetadataReferences.FromAttributes());

            RoslynAssert.NoDiagnostics(Analyze.GetDiagnostics(analyzer, solution));
        }
コード例 #6
0
            public void BinarySolution()
            {
                var binaryReferencedCode = @"
namespace BinaryReferencedAssembly
{
    public class Base
    {
        private int _fieldName;
    }
}";
                var code     = @"
namespace RoslynSandbox
{
    using System.Reflection;

    public class C : BinaryReferencedAssembly.Base
    {
        private int f;
    }
}";
                var analyzer = new FieldNameMustNotBeginWithUnderscore();
                var solution = CodeFactory.CreateSolution(
                    code,
                    CodeFactory.DefaultCompilationOptions(new[] { analyzer }),
                    AnalyzerAssert.MetadataReferences.Append(Asserts.MetadataReferences.CreateBinary(binaryReferencedCode)));

                AnalyzerAssert.Valid(analyzer, solution);
            }
コード例 #7
0
        public static async Task SingleDocumentOneError()
        {
            var code = @"
namespace N
{
    class C
    {
        private readonly int _value;
    }
}";

            var after    = @"
namespace N
{
    class C
    {
        private readonly int value;
    }
}";
            var analyzer = new FieldNameMustNotBeginWithUnderscore();
            var cSharpCompilationOptions = CodeFactory.DefaultCompilationOptions(analyzer);
            var metadataReferences       = new[] { MetadataReference.CreateFromFile(typeof(int).Assembly.Location) };
            var sln        = CodeFactory.CreateSolution(code, cSharpCompilationOptions, metadataReferences);
            var diagnostic = Analyze.GetDiagnostics(sln, analyzer).SelectMany(x => x).Single();
            var fixedSln   = Fix.Apply(sln, new DoNotUseUnderscoreFix(), diagnostic);

            CodeAssert.AreEqual(after, fixedSln.Projects.Single().Documents.Single());

            fixedSln = await Fix.ApplyAsync(sln, new DoNotUseUnderscoreFix(), diagnostic).ConfigureAwait(false);

            CodeAssert.AreEqual(after, fixedSln.Projects.Single().Documents.Single());
        }
コード例 #8
0
        public static void WithSyntaxErrors(DiagnosticAnalyzer analyzer)
        {
            var code     = @"
namespace N
{
    using System;
    using System.IO;

    public class C : SyntaxError
    {
        private readonly Stream stream = File.SyntaxError(string.Empty);
        private bool disposed;

        protected override void Dispose(bool disposing)
        {
            if (this.syntaxError)
            {
                return;
            }

            this.disposed = true;
            if (disposing)
            {
                this.stream.Dispose();
            }

            base.Dispose(disposing);
        }
    }
}";
            var solution = CodeFactory.CreateSolution(code, CodeFactory.DefaultCompilationOptions(analyzer), MetadataReferences.FromAttributes());

            RoslynAssert.NoDiagnostics(Analyze.GetDiagnostics(analyzer, solution));
        }
コード例 #9
0
            public void SingleClassNoErrorAnalyzer()
            {
                var code     = @"
namespace RoslynSandbox
{
    class Foo
    {
    }
}";
                var analyzer = new NoErrorAnalyzer();

                AnalyzerAssert.Valid <NoErrorAnalyzer>(code);
                AnalyzerAssert.Valid(typeof(NoErrorAnalyzer), code);
                AnalyzerAssert.Valid(analyzer, code);
                AnalyzerAssert.Valid(analyzer, code, CodeFactory.DefaultCompilationOptions(analyzer, AnalyzerAssert.SuppressedDiagnostics), AnalyzerAssert.MetadataReferences);
                AnalyzerAssert.Valid(analyzer, new[] { code }, CodeFactory.DefaultCompilationOptions(analyzer, AnalyzerAssert.SuppressedDiagnostics), AnalyzerAssert.MetadataReferences);

                var descriptor = NoErrorAnalyzer.Descriptor;

                AnalyzerAssert.Valid <NoErrorAnalyzer>(descriptor, code);
                AnalyzerAssert.Valid(typeof(NoErrorAnalyzer), descriptor, code);
                AnalyzerAssert.Valid(analyzer, descriptor, code);

                AnalyzerAssert.Valid <NoErrorAnalyzer>(new[] { descriptor }, code);
                AnalyzerAssert.Valid(typeof(NoErrorAnalyzer), new[] { descriptor }, code);
                AnalyzerAssert.Valid(analyzer, new[] { descriptor }, code);
            }
コード例 #10
0
        public void ClassLibrary1NopAnalyzer()
        {
            var analyzer   = new NopAnalyzer();
            var code       = ProjectFile.Find("ClassLibrary1.csproj");
            var descriptor = NopAnalyzer.Descriptor;

            RoslynAssert.Valid(typeof(NopAnalyzer), descriptor, code);
            RoslynAssert.Valid(analyzer, descriptor, code);
            RoslynAssert.Valid(analyzer, code, compilationOptions: CodeFactory.DefaultCompilationOptions(analyzer, descriptor, null));
        }
コード例 #11
0
        public void WpfAppNoErrorAnalyzer()
        {
            var analyzer   = new NoErrorAnalyzer();
            var csproj     = ProjectFile.Find("WpfApp1.csproj");
            var descriptor = NoErrorAnalyzer.Descriptor;

            AnalyzerAssert.Valid <NoErrorAnalyzer>(descriptor, csproj);
            AnalyzerAssert.Valid(typeof(NoErrorAnalyzer), descriptor, csproj);
            AnalyzerAssert.Valid(analyzer, descriptor, csproj);
            AnalyzerAssert.Valid(analyzer, csproj, CodeFactory.DefaultCompilationOptions(analyzer, descriptor, null), AnalyzerAssert.MetadataReferences);
        }
コード例 #12
0
        public static async Task InvisibleProperty(string before, string after)
        {
            var code = @"
namespace RoslynSandbox
{
    using System.Reflection;

    public class C
    {
        public object Get => typeof(BinaryReferencedAssembly.C).GetMethod(""get_P"", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly);
    }
}".AssertReplace("GetMethod(\"get_P\", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly)", before);

            var fixedCode = @"
namespace RoslynSandbox
{
    using System.Reflection;

    public class C
    {
        public object Get => typeof(BinaryReferencedAssembly.C).GetProperty(""P"", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly).GetMethod;
    }
}".AssertReplace("GetProperty(\"P\", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly).GetMethod", after);

            var binaryReferencedCode = @"
namespace BinaryReferencedAssembly
{
    public class C
    {
        private int P { get; set; }
    }
}";
            var binaryReference      = TestHelper.CompileBinaryReference(binaryReferencedCode);

            var solution = CodeFactory.CreateSolution(
                code,
                CodeFactory.DefaultCompilationOptions(new[] { Analyzer })
                .WithMetadataImportOptions(MetadataImportOptions.Public),
                RoslynAssert.MetadataReferences.Append(binaryReference));

            // To make sure the test is effective, assert that ReflectionAnalyzers *can’t* see C.P.
            var compilation = await solution.Projects.Single()
                              .GetCompilationAsync()
                              .ConfigureAwait(true);

            var fooType = compilation.GetTypeByMetadataName("BinaryReferencedAssembly.C");

            Assert.That(fooType.GetMembers(), Has.None.With.Property("Name")
                        .EqualTo("P"));

            RoslynAssert.CodeFix(Analyzer, Fix, ExpectedDiagnostic, solution, fixedCode);
        }
コード例 #13
0
            public void WithTransitiveMetadataReference()
            {
                var code               = @"
namespace RoslynSandbox
{
    class Foo
    {
    }
}";
                var analyzer           = new NoErrorAnalyzer();
                var metadataReferences = Gu.Roslyn.Asserts.MetadataReferences.Transitive(typeof(Microsoft.CodeAnalysis.CSharp.CSharpCompilation)).ToArray();

                AnalyzerAssert.Valid(analyzer, code, CodeFactory.DefaultCompilationOptions(analyzer, AnalyzerAssert.SuppressedDiagnostics), metadataReferences);
            }
コード例 #14
0
            public void WithSingleMetadataReference()
            {
                var code     = @"
namespace RoslynSandbox
{
    class Foo
    {
    }
}";
                var analyzer = new NoErrorAnalyzer();

                AnalyzerAssert.Valid(analyzer, code, CodeFactory.DefaultCompilationOptions(analyzer, AnalyzerAssert.SuppressedDiagnostics), new[] { Gu.Roslyn.Asserts.MetadataReferences.CreateFromAssembly(typeof(object).Assembly) });
                AnalyzerAssert.Valid(analyzer, code, CodeFactory.DefaultCompilationOptions(analyzer, AnalyzerAssert.SuppressedDiagnostics), Gu.Roslyn.Asserts.MetadataReferences.Transitive(typeof(object).Assembly));
                AnalyzerAssert.Valid(analyzer, code, CodeFactory.DefaultCompilationOptions(analyzer, AnalyzerAssert.SuppressedDiagnostics), new[] { Gu.Roslyn.Asserts.MetadataReferences.CreateFromAssembly(typeof(object).Assembly).WithAliases(new[] { "global", "mscorlib" }) });
            }
コード例 #15
0
ファイル: Valid.cs プロジェクト: GeertvanHorrik/Gu.Analyzers
        public static void MultipleIEnumerableInterfaces()
        {
            var testCode    = @"
namespace N
{
    using System.Collections;
    using System.Collections.Generic;

    class C : IEnumerable<IEnumerable<char>>, IEnumerable<int>
    {
        IEnumerator<int> IEnumerable<int>.GetEnumerator()
        {
            yield return 42;
        }

        void GetEnumerator(int x)
        {
        }

        IEnumerator<IEnumerable<char>> IEnumerable<IEnumerable<char>>.GetEnumerator()
        {
            yield return string.Empty;
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return ((IEnumerable<IEnumerable<char>>)this).GetEnumerator();
        }
    }

    public class A
    {
        public void F()
        {
            foreach(int a in new C())
            {
            }
        }
    }
}";
            var sln         = CodeFactory.CreateSolution(testCode, CodeFactory.DefaultCompilationOptions(Analyzer), RoslynAssert.MetadataReferences);
            var diagnostics = Analyze.GetDiagnostics(Analyzer, sln);

            RoslynAssert.NoDiagnostics(diagnostics);
        }
コード例 #16
0
        public void AnalyzeWhenAllInformationIsProvidedByAttributeWhenDataClassIsInSeparateAssembly()
        {
            var testCode = @"
    using NUnit.Framework;
    using Project2;

    namespace Project1
    {
        public class Tests
        {
            [Test]
            [TestCaseSource(typeof(TestData), nameof(TestData.TestCaseDataProvider))]
            public void Test1(int a, int b, int c)
            {
                Assert.That(a + b, Is.EqualTo(c));
            }
        }
    }";

            var testDataCode = @"
    using System.Collections;

    namespace Project2
    {
        public static class TestData
        {
            public static IEnumerable TestCaseDataProvider()
            {
                yield return new object[] { 1, 2, 3 };
                yield return new object[] { 2, 3, 5 };
            }
        }
    }";

            var testDataReference = MetadataReferences.CreateBinary(testDataCode);
            var references        = MetadataReferences.FromAttributes().Concat(new[] { testDataReference });

            var solution = CodeFactory.CreateSolution(testCode,
                                                      CodeFactory.DefaultCompilationOptions(analyzer),
                                                      references);

            RoslynAssert.Valid(analyzer, solution);
        }
コード例 #17
0
            public static void Recursion()
            {
                var code     = @"
namespace RoslynSandbox
{
    using System;

    public class C<T1, T2>
        where T1 : T2
        where T2 : T1
    {
        public static void Bar()
        {
            var type = typeof(C<,>).MakeGenericType(typeof(int), typeof(int));
        }
    }
}";
                var solution = CodeFactory.CreateSolution(code, CodeFactory.DefaultCompilationOptions(Analyzer), RoslynAssert.MetadataReferences);

                RoslynAssert.NoDiagnostics(Analyze.GetDiagnostics(Analyzer, solution));
            }
コード例 #18
0
        public static void IServiceProviderGetRequiredService()
        {
            var code = @"
namespace N
{
    using System;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Logging;

    public class C
    {
        private readonly IServiceProvider serviceProvider;

        public C(IServiceProvider serviceProvider)
        {
            var disposable1 = serviceProvider.GetRequiredService<Disposable>();
            _ = serviceProvider.GetRequiredService<Disposable>();
            var loggerFactory1 = serviceProvider.GetRequiredService<ILoggerFactory>();
            _ = serviceProvider.GetRequiredService<ILoggerFactory>();

            this.serviceProvider = serviceProvider;
            var disposable2 = this.serviceProvider.GetRequiredService<Disposable>();
            _ = this.serviceProvider.GetRequiredService<Disposable>();
            var loggerFactory2 = this.serviceProvider.GetRequiredService<ILoggerFactory>();
            _ = this.serviceProvider.GetRequiredService<ILoggerFactory>();
        }

        public sealed class Disposable : IDisposable
        {
            public void Dispose()
            {
            }
        }
    }
}";

            var nullableContextOptions = CodeFactory.DefaultCompilationOptions(Analyzer, null).WithNullableContextOptions(NullableContextOptions.Enable);

            RoslynAssert.Valid(Analyzer, code, compilationOptions: nullableContextOptions);
        }
コード例 #19
0
            public void OneErrorIndicatedPosition()
            {
                var code               = @"
namespace RoslynSandbox
{
    class Foo
    {
        private readonly int ↓_value;
    }
}";
                var analyzer           = new FieldNameMustNotBeginWithUnderscore();
                var expectedDiagnostic = ExpectedDiagnostic.Create(FieldNameMustNotBeginWithUnderscore.DiagnosticId);

                AnalyzerAssert.Diagnostics <FieldNameMustNotBeginWithUnderscore>(code);
                AnalyzerAssert.Diagnostics(typeof(FieldNameMustNotBeginWithUnderscore), code);
                AnalyzerAssert.Diagnostics(analyzer, code);
                AnalyzerAssert.Diagnostics(analyzer, code, CodeFactory.DefaultCompilationOptions(analyzer, expectedDiagnostic, AnalyzerAssert.SuppressedDiagnostics), AnalyzerAssert.MetadataReferences);
                AnalyzerAssert.Diagnostics(analyzer, new[] { code }, CodeFactory.DefaultCompilationOptions(analyzer, expectedDiagnostic, AnalyzerAssert.SuppressedDiagnostics), AnalyzerAssert.MetadataReferences);

                AnalyzerAssert.Diagnostics <FieldNameMustNotBeginWithUnderscore>(expectedDiagnostic, code);
                AnalyzerAssert.Diagnostics(typeof(FieldNameMustNotBeginWithUnderscore), expectedDiagnostic, code);
                AnalyzerAssert.Diagnostics(analyzer, expectedDiagnostic, code);
            }
コード例 #20
0
            public void ClassLibrary1ProjectFileFieldNameMustNotBeginWithUnderscoreDisabled()
            {
                var csproj   = ProjectFile.Find("ClassLibrary1.csproj");
                var expected = "Expected no diagnostics, found:\r\n" +
                               "SA13090 Field \'_value\' must not begin with an underscore\r\n" +
                               $"  at line 9 and character 20 in file {csproj.DirectoryName}\\ClassLibrary1Class1.cs | private int ↓_value;";
                var analyzer  = new FieldNameMustNotBeginWithUnderscoreDisabled();
                var exception = Assert.Throws <AssertException>(() => AnalyzerAssert.Valid <FieldNameMustNotBeginWithUnderscoreDisabled>(csproj));

                StringAssert.Contains(expected, exception.Message);

                exception = Assert.Throws <AssertException>(() => AnalyzerAssert.Valid(typeof(FieldNameMustNotBeginWithUnderscoreDisabled), csproj));
                StringAssert.Contains(expected, exception.Message);

                exception = Assert.Throws <AssertException>(() => AnalyzerAssert.Valid(analyzer, csproj));
                StringAssert.Contains(expected, exception.Message);

                var descriptor = FieldNameMustNotBeginWithUnderscoreDisabled.Descriptor;

                exception = Assert.Throws <AssertException>(() => AnalyzerAssert.Valid <FieldNameMustNotBeginWithUnderscoreDisabled>(descriptor, csproj));
                StringAssert.Contains(expected, exception.Message);

                exception = Assert.Throws <AssertException>(() => AnalyzerAssert.Valid(typeof(FieldNameMustNotBeginWithUnderscoreDisabled), descriptor, csproj));
                StringAssert.Contains(expected, exception.Message);

                exception = Assert.Throws <AssertException>(() => AnalyzerAssert.Valid(analyzer, descriptor, csproj));
                StringAssert.Contains(expected, exception.Message);

                exception = Assert.Throws <AssertException>(() => AnalyzerAssert.Valid(analyzer, csproj, CodeFactory.DefaultCompilationOptions(analyzer, descriptor, AnalyzerAssert.SuppressedDiagnostics), AnalyzerAssert.MetadataReferences));
                StringAssert.Contains(expected, exception.Message);
                if (Throw)
                {
                    AnalyzerAssert.Valid <FieldNameMustNotBeginWithUnderscoreDisabled>(csproj);
                }
            }
コード例 #21
0
            public static void WithTransitiveMetadataReference()
            {
                var code               = @"
namespace N
{
    class C
    {
    }
}";
                var analyzer           = new NopAnalyzer();
                var metadataReferences = Gu.Roslyn.Asserts.MetadataReferences.Transitive(typeof(Microsoft.CodeAnalysis.CSharp.CSharpCompilation)).ToArray();

                RoslynAssert.Valid(analyzer, code, metadataReferences: metadataReferences, compilationOptions: CodeFactory.DefaultCompilationOptions(analyzer));
            }
コード例 #22
0
            public static void BinaryStrings()
            {
                var binaryReferencedCode = @"
namespace BinaryReferencedAssembly
{
    public class Base
    {
        private int _fieldName;
    }
}";
                var code     = @"
namespace N
{
    using System.Reflection;

    public class C : BinaryReferencedAssembly.Base
    {
        private int f;
    }
}";
                var analyzer = new FieldNameMustNotBeginWithUnderscore();

                RoslynAssert.Valid(analyzer, code, metadataReferences: Gu.Roslyn.Asserts.MetadataReferences.FromAttributes().Append(Asserts.MetadataReferences.CreateBinary(binaryReferencedCode)), compilationOptions: CodeFactory.DefaultCompilationOptions(new[] { analyzer }));
                RoslynAssert.Valid(analyzer, code, metadataReferences: Gu.Roslyn.Asserts.MetadataReferences.FromAttributes().Append(Asserts.MetadataReferences.CreateBinary(binaryReferencedCode)));
            }
コード例 #23
0
            public void SingleClassOneErrorNoFix()
            {
                var code               = @"
namespace RoslynSandbox
{
    class Foo
    {
        private readonly int ↓_value;
    }
}";
                var analyzer           = new FieldNameMustNotBeginWithUnderscore();
                var expectedDiagnostic = ExpectedDiagnostic.Create(FieldNameMustNotBeginWithUnderscore.DiagnosticId);

                AnalyzerAssert.NoFix <FieldNameMustNotBeginWithUnderscore, NoCodeFixProvider>(code);
                AnalyzerAssert.NoFix <FieldNameMustNotBeginWithUnderscore, NoCodeFixProvider>(expectedDiagnostic, code);
                AnalyzerAssert.NoFix <FieldNameMustNotBeginWithUnderscore, NoCodeFixProvider>((IReadOnlyList <string>) new[] { code });
                AnalyzerAssert.NoFix(analyzer, new NoCodeFixProvider(), code);
                AnalyzerAssert.NoFix(analyzer, new NoCodeFixProvider(), expectedDiagnostic, code);
                AnalyzerAssert.NoFix(analyzer, new NoCodeFixProvider(), expectedDiagnostic, new List <string> {
                    code
                });
                AnalyzerAssert.NoFix(analyzer, new NoCodeFixProvider(), new[] { code }, CodeFactory.DefaultCompilationOptions(analyzer, expectedDiagnostic, AnalyzerAssert.SuppressedDiagnostics), AnalyzerAssert.MetadataReferences);
            }
コード例 #24
0
            public void Issue63()
            {
                var viewModelBaseCode  = @"
namespace MVVM
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Diagnostics;
    using System.Reflection;

    using System.Runtime.CompilerServices;

    /// <summary>
    /// Base class for all ViewModel classes in the application.
    /// It provides support for property change notifications
    /// and has a DisplayName property. This class is abstract.
    /// </summary>
    public abstract class ViewModelBase : INotifyPropertyChanged, IDisposable
    {
        private readonly List<IDisposable> disposables = new List<IDisposable>();
        private readonly object disposeLock = new object();
        private bool isDisposed;

        protected ViewModelBase()
        {
        }

        public event PropertyChangedEventHandler PropertyChanged;
        public void Dispose()
        {
            lock (disposeLock)
            {
                this.OnDispose();

                if (isDisposed)
                    return;

                foreach (var disposable in disposables)
                    disposable.Dispose();

                isDisposed = true;
            }
        }

        protected virtual void OnDispose()
        {
        }
    }
}";
                var popupViewModelCode = @"
namespace ProjectX.ViewModel
{
    using System;
    using MVVM;

    public class PopupViewModel : ViewModelBase
    {
        public PopupViewModel()
        {
            ClosePopupCommand = new ClosePopupCommand(this);
        }

        // Gives an IDISP006 warning (need to implement IDispose)
        public ClosePopupCommand ClosePopupCommand { get; }

        protected override void OnDispose()
        {
            ClosePopupCommand.Dispose();
            CloseProgramCommand.Dispose();
        }
    }
}";

                var closePopupCommandCode = @"
namespace ProjectX.Commands
{
    using System;

    public sealed class ClosePopupCommand : IDisposable
    {
        private readonly object disposeLock = new object();
        private bool isDisposed;
        private bool isBusy = false;

        internal ClosePopupCommand()
        {
        }

        public event EventHandler CanExecuteChanged;

        public void Dispose()
        {
            lock (disposeLock)
            {
                if (isDisposed)
                    return;

                // Here we have code that actually needs to be disposed off...

                isDisposed = true;
            }
        }
    }
}";

                var solution = CodeFactory.CreateSolution(
                    new[] { viewModelBaseCode, popupViewModelCode, closePopupCommandCode },
                    CodeFactory.DefaultCompilationOptions(Analyzer, AnalyzerAssert.SuppressedDiagnostics),
                    AnalyzerAssert.MetadataReferences);

                AnalyzerAssert.NoDiagnostics(Analyze.GetDiagnostics(Analyzer, solution));
            }
コード例 #25
0
            public static void ClassLibrary1ProjectFileFieldNameMustNotBeginWithUnderscoreDisabled()
            {
                var code     = ProjectFile.Find("ClassLibrary1.csproj");
                var expected = "Expected no diagnostics, found:\r\n" +
                               "SA13090 Field \'_value\' must not begin with an underscore\r\n" +
                               $"  at line 5 and character 20 in file {code.DirectoryName}\\ClassLibrary1Class1.cs | private int ↓_value;";
                var analyzer = new FieldNameMustNotBeginWithUnderscoreDisabled();

                var exception = Assert.Throws <AssertException>(() => RoslynAssert.Valid(analyzer, code));

                StringAssert.Contains(expected, exception.Message);

                exception = Assert.Throws <AssertException>(() => RoslynAssert.Valid(typeof(FieldNameMustNotBeginWithUnderscoreDisabled), code));
                StringAssert.Contains(expected, exception.Message);

                var descriptor = FieldNameMustNotBeginWithUnderscoreDisabled.Descriptor;

                exception = Assert.Throws <AssertException>(() => RoslynAssert.Valid(typeof(FieldNameMustNotBeginWithUnderscoreDisabled), descriptor, code));
                StringAssert.Contains(expected, exception.Message);

                exception = Assert.Throws <AssertException>(() => RoslynAssert.Valid(analyzer, descriptor, code));
                StringAssert.Contains(expected, exception.Message);

                exception = Assert.Throws <AssertException>(() => RoslynAssert.Valid(analyzer, code, compilationOptions: CodeFactory.DefaultCompilationOptions(analyzer, descriptor, null)));
                StringAssert.Contains(expected, exception.Message);
            }
コード例 #26
0
            public static void WithSingleMetadataReference()
            {
                var code               = @"
namespace N
{
    class C
    {
    }
}";
                var analyzer           = new NopAnalyzer();
                var metadataReferences = new[] { Gu.Roslyn.Asserts.MetadataReferences.CreateFromAssembly(typeof(object).Assembly) };

                RoslynAssert.Valid(analyzer, code, metadataReferences: metadataReferences, compilationOptions: CodeFactory.DefaultCompilationOptions(analyzer));
            }
コード例 #27
0
        public async Task ReferencesMemberThatAnalyzerCannotSeeAsync()
        {
            var code      = @"
namespace RoslynSandbox
{
    using System.Reflection;

    public class C
    {
        public void M()
        {
            _ = typeof(BinaryReferencedAssembly.Foo).GetMethod(""add_Bar"", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly);
        }
    }
}";
            var fixedCode = @"
namespace RoslynSandbox
{
    using System.Reflection;

    public class C
    {
        public void M()
        {
            _ = typeof(BinaryReferencedAssembly.Foo).GetEvent(""Bar"", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly).AddMethod;
        }
    }
}";

            var binaryReferencedCode = @"
namespace RoslynSandbox.BinaryReferencedAssembly
{
    using System;

    public interface IFoo
    {
        event EventHandler Bar;
    }

    public class Foo : IFoo
    {
        #pragma warning disable CS0067
        internal event EventHandler Bar;

        event EventHandler IFoo.Bar
        {
            add { }
            remove { }
        }
    }
}";
            var binaryReference      = TestHelper.CompileBinaryReference(binaryReferencedCode);

            var solution = CodeFactory.CreateSolution(
                code,
                CodeFactory.DefaultCompilationOptions(new[] { Analyzer }).WithMetadataImportOptions(MetadataImportOptions.Public),
                AnalyzerAssert.MetadataReferences.Append(binaryReference));

            // To make sure the test is effective, assert that ReflectionAnalyzers *can’t* see Foo.Bar.
            var compilation = await solution.Projects.Single().GetCompilationAsync().ConfigureAwait(true);

            var fooType = compilation.GetTypeByMetadataName("RoslynSandbox.BinaryReferencedAssembly.Foo");

            Assert.That(fooType.GetMembers(), Has.None.With.Property("Name").EqualTo("Bar"));

            var message = @"Prefer typeof(BinaryReferencedAssembly.Foo).GetEvent(""Bar"", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly).AddMethod.";

            AnalyzerAssert.CodeFix(Analyzer, Fix, ExpectedDiagnostic.WithMessage(message), solution, fixedCode);
        }