public static void AddSystem()
        {
            var code          = @"
namespace N
{

    using System.Text;
}";
            var syntaxTree    = CSharpSyntaxTree.ParseText(code);
            var compilation   = CSharpCompilation.Create("test", new[] { syntaxTree }, Settings.Default.MetadataReferences);
            var semanticModel = compilation.GetSemanticModel(syntaxTree);

            var expected        = @"
namespace N
{
usingSystem;

    using System.Text;
}";
            var usingDirective  = SyntaxFactory.UsingDirective(SyntaxFactory.ParseName("System"));
            var compilationUnit = syntaxTree.GetCompilationUnitRoot(CancellationToken.None);

            var updated = compilationUnit.AddUsing(usingDirective, semanticModel);

            CodeAssert.AreEqual(expected, updated.ToFullString());
        }
Exemplo n.º 2
0
        public void EnsureThatConfigSeverityIsAsExpected(BaseInfo info)
        {
            var expected = GetConfigSeverity(info.Stub);

            DumpIfDebug(expected);
            var actual = GetConfigSeverity(info.DocumentationFile.AllText);

            CodeAssert.AreEqual(expected, actual);

            string GetConfigSeverity(string doc)
            {
                return(GetSection(doc, "<!-- start generated config severity -->", "<!-- end generated config severity -->"));
            }

            string GetSection(string doc, string startToken, string endToken)
            {
                var start = doc.IndexOf(startToken, StringComparison.Ordinal);

                Assert.That(start, Is.GreaterThan(0), "Missing: " + startToken);
                var end = doc.IndexOf(endToken, start, StringComparison.Ordinal);

                Assert.That(end, Is.GreaterThan(start), "Missing: " + endToken);
                return(doc.Substring(start, end + endToken.Length - start));
            }
        }
Exemplo n.º 3
0
        public void EnsureThatSuppressionIndexIsAsExpected(int tableNumber)
        {
            var          builder   = new StringBuilder();
            const string headerRow = "| Id       | Title       | :mag: | :memo: | :bulb: |";

            builder.AppendLine(headerRow)
            .AppendLine("| :--      | :--         | :--:  | :--:   | :--:   |");

            var suppressors = SuppressorsWithDocs
                              .Distinct()
                              .OrderBy(x => x.Descriptor.Id);

            foreach (var suppressor in suppressors)
            {
                var enabledEmoji  = ":white_check_mark:";
                var severityEmoji = SeverityEmoji[DiagnosticSeverity.Info];

                var codefixEmoji = ":x:";

                builder.Append($"| [{suppressor.Id}]({suppressor.HelpLinkUri}) ")
                .Append($"| {EscapeTags(suppressor.Title)} | {enabledEmoji} ")
                .AppendLine($"| {severityEmoji} | {codefixEmoji} |");
            }

            var expected = builder.ToString();

            DumpIfDebug(expected);
            var actual = GetTable(File.ReadAllText(Path.Combine(DocumentsDirectory.FullName, "index.md")), headerRow, tableNumber);

            CodeAssert.AreEqual(expected, actual);
        }
Exemplo n.º 4
0
        public void WhenEqualWhitespaceEnd()
        {
            var expected = @"
namespace RoslynSandbox
{
    class Foo
    {
        private readonly int _value;
    }
}

a
";

            var actual = @"
namespace RoslynSandbox
{
    class Foo
    {
        private readonly int _value;
    }
}

a
";

            CodeAssert.AreEqual(expected, actual);
        }
Exemplo n.º 5
0
        private static void CompareAssemblyAgainstCSharp(string expectedCSharpCode, string asmFilePath)
        {
            var module = Utils.OpenModule(asmFilePath);

            try
            {
                try { module.LoadPdb(); } catch { }
                AstBuilder decompiler = AstBuilder.CreateAstBuilderTestContext(module);
                decompiler.AddAssembly(module, false, true, true);
                new Helpers.RemoveCompilerAttribute().Run(decompiler.SyntaxTree);
                StringWriter output = new StringWriter();

                // the F# assembly contains a namespace `<StartupCode$tmp6D55>` where the part after tmp is randomly generated.
                // remove this from the ast to simplify the diff
                var startupCodeNode = decompiler.SyntaxTree.Children.OfType <NamespaceDeclaration>().SingleOrDefault(d => d.Name.StartsWith("<StartupCode$", StringComparison.Ordinal));
                if (startupCodeNode != null)
                {
                    startupCodeNode.Remove();
                }

                decompiler.GenerateCode(new PlainTextOutput(output));
                var fullCSharpCode = output.ToString();

                CodeAssert.AreEqual(expectedCSharpCode, output.ToString());
            }
            finally
            {
                File.Delete(asmFilePath);
                File.Delete(Path.ChangeExtension(asmFilePath, ".pdb"));
            }
        }
            public void TwoClassesOneErrorCodeFixFixedTheCode()
            {
                var barCode = @"
namespace RoslynSandbox
{
    class Bar
    {
        private readonly int value;
    }
}";

                var code = @"
namespace RoslynSandbox
{
    class Foo
    {
        private readonly int ↓_value;
    }
}";

                var exception = Assert.Throws <AssertException>(() => AnalyzerAssert.NoFix <FieldNameMustNotBeginWithUnderscore, DontUseUnderscoreCodeFixProvider>(barCode, code));
                var expected  = "Expected code to have no fixable diagnostics.\r\n" +
                                "The following actions were registered:\r\n" +
                                "Rename to: value\r\n";

                CodeAssert.AreEqual(expected, exception.Message);
            }
Exemplo n.º 7
0
        public static void LocalInForEach()
        {
            var code          = @"
namespace N
{
    using System;

    class C
    {
        public void M()
        {
            foreach (var x in new[] { 1, 2 })
            {
                _  = x.ToString();
            }
        }
    }
}";
            var syntaxTree    = CSharpSyntaxTree.ParseText(code);
            var compilation   = CSharpCompilation.Create("test", new[] { syntaxTree }, Settings.Default.MetadataReferences);
            var semanticModel = compilation.GetSemanticModel(syntaxTree);
            var node          = syntaxTree.FindIdentifierName("x");

            Assert.AreEqual(true, semanticModel.TryGetSymbol(node, CancellationToken.None, out ILocalSymbol symbol));
            Assert.AreEqual(true, symbol.TryGetScope(CancellationToken.None, out var scope));
            CodeAssert.AreEqual("{\r\n                _  = x.ToString();\r\n            }", scope.ToString());
        }
Exemplo n.º 8
0
        public static async Task SystemWhenEmptyOutside()
        {
            var code = @"
namespace N
{
}";

            var otherCode = @"
using System;

namespace N
{
}";
            var sln       = CodeFactory.CreateSolution(new[] { code, otherCode });
            var editor    = await DocumentEditor.CreateAsync(sln.Projects.First().Documents.First()).ConfigureAwait(false);

            var expected       = @"using System;

namespace N
{
}";
            var usingDirective = SyntaxFactory.UsingDirective(SyntaxFactory.ParseName("System"));

            _ = editor.AddUsing(usingDirective);
            CodeAssert.AreEqual(expected, editor.GetChangedDocument());
        }
Exemplo n.º 9
0
        public static async Task TypeInSameNamespaceWhenEmptyNamespace()
        {
            var classCode = @"
namespace N
{
    class C1 { }
}
";
            var code      = @"
namespace N
{
}";
            var sln       = CodeFactory.CreateSolution(new[] { classCode, code });
            var document  = sln.Projects.First().Documents.Last();
            var editor    = await DocumentEditor.CreateAsync(document).ConfigureAwait(false);

            var expected = @"
namespace N
{
}";
            var type     = editor.SemanticModel.Compilation.GetTypeByMetadataName("N.C1");

            _ = editor.AddUsing(type);
            CodeAssert.AreEqual(expected, editor.GetChangedDocument());
        }
Exemplo n.º 10
0
        public static async Task ListOfStringBuilderType()
        {
            var code     = @"
namespace N
{
}";
            var sln      = CodeFactory.CreateSolution(code);
            var document = sln.Projects.First().Documents.First();
            var editor   = await DocumentEditor.CreateAsync(document).ConfigureAwait(false);

            var expected = @"
namespace N
{
    using System.Collections.Generic;
    using System.Text;
}";

            var type = editor.SemanticModel.GetSpeculativeTypeInfo(
                0,
                SyntaxFactory.ParseTypeName("System.Collections.Generic.List<System.Text.StringBuilder>"),
                SpeculativeBindingOption.BindAsTypeOrNamespace).Type;

            _ = editor.AddUsing(type);
            CodeAssert.AreEqual(expected, editor.GetChangedDocument());
        }
Exemplo n.º 11
0
        public static async Task TypeInNestedDeepNamespace()
        {
            var classCode = @"
namespace A.B.C.Extensions
{
    class C { }
}
";
            var code      = @"
namespace A.B.C
{
}";
            var sln       = CodeFactory.CreateSolution(new[] { classCode, code });
            var document  = sln.Projects.First().Documents.First();
            var editor    = await DocumentEditor.CreateAsync(document).ConfigureAwait(false);

            var expected = @"
namespace A.B.C
{
    using A.B.C.Extensions;
}";
            var type     = editor.SemanticModel.Compilation.GetTypeByMetadataName("A.B.C.Extensions.C");

            _ = editor.AddUsing(type);
            CodeAssert.AreEqual(expected, editor.GetChangedDocument());
        }
Exemplo n.º 12
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());
        }
Exemplo n.º 13
0
        public static async Task AddPublicFieldWhenPublicAndPrivateExists()
        {
            var code   = @"
namespace N
{
    class C
    {
        public int F;

        private int f;
    }
}";
            var sln    = CodeFactory.CreateSolution(code);
            var editor = await DocumentEditor.CreateAsync(sln.Projects.First().Documents.First()).ConfigureAwait(false);

            var containingType = editor.OriginalRoot.SyntaxTree.FindClassDeclaration("C");

            var expected = @"
namespace N
{
    class C
    {
        public int F;
        public int NewField;

        private int f;
    }
}";

            var newField = (FieldDeclarationSyntax)SyntaxFactory.ParseMemberDeclaration("public int NewField;");

            _ = editor.AddField(containingType, newField);
            CodeAssert.AreEqual(expected, editor.GetChangedDocument());
        }
Exemplo n.º 14
0
        public void EnsureThatIndexIsAsExpected()
        {
            var          builder   = new StringBuilder();
            const string HeaderRow = "| Id       | Title";

            builder.AppendLine(HeaderRow)
            .AppendLine("| :--      | :--");

            var descriptors = DescriptorsWithDocs.Select(x => x.Descriptor)
                              .Distinct()
                              .OrderBy(x => x.Id);

            foreach (var descriptor in descriptors)
            {
                builder.Append($"| [{descriptor.Id}]({descriptor.HelpLinkUri})")
                .AppendLine($"| {descriptor.Title}");
            }

            var expected = builder.ToString();

            DumpIfDebug(expected);
            var actual = GetTable(File.ReadAllText(Path.Combine(DocumentsDirectory.FullName, "index.md")), HeaderRow);

            CodeAssert.AreEqual(expected, actual);
        }
Exemplo n.º 15
0
        public static async Task AfterPropertyWhenLastMember()
        {
            var code   = @"
namespace N
{
    public class C
    {
        public int P { get; }
    }
}";
            var sln    = CodeFactory.CreateSolution(code);
            var editor = await DocumentEditor.CreateAsync(sln.Projects.First().Documents.First()).ConfigureAwait(false);

            var containingType = editor.OriginalRoot.SyntaxTree.FindClassDeclaration("C");
            var property       = (PropertyDeclarationSyntax)SyntaxFactory.ParseMemberDeclaration("public int NewProperty => 1;");

            var expected = @"
namespace N
{
    public class C
    {
        public int P { get; }

        public int NewProperty => 1;
    }
}";

            _ = editor.AddProperty(containingType, property);
            CodeAssert.AreEqual(expected, editor.GetChangedDocument());
        }
Exemplo n.º 16
0
            public static void WithSpanWhenAfterDoesNotMatch()
            {
                var before = @"
class c
{
}";

                var after = @"
class WRONG
{
}";

                var refactoring = new ClassNameToUpperCaseRefactoringProvider();
                var exception   = Assert.Throws <AssertException>(() => RoslynAssert.Refactoring(refactoring, before, new TextSpan(8, 3), after));
                var expected    = @"Mismatch on line 2 of file WRONG.cs.
Expected: class WRONG
Actual:   class C
                ^
Expected:

class WRONG
{
}
Actual:

class C
{
}
";

                CodeAssert.AreEqual(expected, exception.Message);
                exception = Assert.Throws <AssertException>(() => RoslynAssert.Refactoring(refactoring, before, new TextSpan(8, 3), after, title: "To uppercase"));
                CodeAssert.AreEqual(expected, exception.Message);
            }
Exemplo n.º 17
0
            public void Method()
            {
                var syntaxTree = CSharpSyntaxTree.ParseText(@"
namespace RoslynSandbox
{
    public class Foo
    {
        /// <summary>
        /// The identity function.
        /// </summary>
        /// <param name=""i"">The value to return.</param>
        /// <returns><paramref name=""i""/></returns>
        public int Id(int i) => i;
    }
}");
                var method     = syntaxTree.FindMethodDeclaration("Id");

                Assert.AreEqual(true, method.TryGetDocumentationComment(out var result));
                var expected = "/// <summary>\r\n" +
                               "        /// The identity function.\r\n" +
                               "        /// </summary>\r\n" +
                               "        /// <param name=\"i\">The value to return.</param>\r\n" +
                               "        /// <returns><paramref name=\"i\"/></returns>\r\n";

                CodeAssert.AreEqual(expected, result.ToFullString());
            }
            public void WithExpectedDiagnosticWithWrongId()
            {
                var code     = @"
namespace RoslynSandbox
{
    class Foo
    {
        private readonly int value1;
    }
}";
                var expected = "Analyzer Gu.Roslyn.Asserts.Tests.FieldNameMustNotBeginWithUnderscore does not produce a diagnostic with ID NoError.\r\n" +
                               "The analyzer produces the following diagnostics: {SA1309}\r\n" +
                               "The expected diagnostic is: NoError";

                var descriptor = NoErrorAnalyzer.Descriptor;

                var exception = Assert.Throws <AssertException>(() => AnalyzerAssert.Valid <FieldNameMustNotBeginWithUnderscore>(descriptor, code));

                CodeAssert.AreEqual(expected, exception.Message);

                exception = Assert.Throws <AssertException>(() => AnalyzerAssert.Valid(typeof(FieldNameMustNotBeginWithUnderscore), descriptor, code));
                Assert.AreEqual(expected, exception.Message);

                exception = Assert.Throws <AssertException>(() => AnalyzerAssert.Valid(new FieldNameMustNotBeginWithUnderscore(), descriptor, code));
                Assert.AreEqual(expected, exception.Message);

                exception = Assert.Throws <AssertException>(() => AnalyzerAssert.Valid <FieldNameMustNotBeginWithUnderscore>(new[] { descriptor }, code));
                Assert.AreEqual(expected, exception.Message);

                exception = Assert.Throws <AssertException>(() => AnalyzerAssert.Valid(typeof(FieldNameMustNotBeginWithUnderscore), new[] { descriptor }, code));
                Assert.AreEqual(expected, exception.Message);

                exception = Assert.Throws <AssertException>(() => AnalyzerAssert.Valid(new FieldNameMustNotBeginWithUnderscore(), new[] { descriptor }, code));
                Assert.AreEqual(expected, exception.Message);
            }
Exemplo n.º 19
0
        public static async Task AddEventWhenUsing()
        {
            var code   = @"
namespace N
{
    using System;

    class C
    {
    }
}";
            var sln    = CodeFactory.CreateSolution(code);
            var editor = await DocumentEditor.CreateAsync(sln.Projects.First().Documents.First()).ConfigureAwait(false);

            var eventDeclaration = (EventFieldDeclarationSyntax)editor.Generator.EventDeclaration("E", SyntaxFactory.ParseTypeName("System.EventHandler"), Accessibility.Public)
                                   .WithSimplifiedNames();
            var containingType = editor.OriginalRoot.SyntaxTree.FindClassDeclaration("C");

            _ = editor.AddEvent(containingType, eventDeclaration);
            var expected = @"
namespace N
{
    using System;

    class C
    {
        public event EventHandler E;
    }
}";

            CodeAssert.AreEqual(expected, editor.GetChangedDocument());
        }
Exemplo n.º 20
0
        public static async Task WithProtectedMember(string before, string after)
        {
            var code   = @"
namespace N
{
    class C
    {
        protected int f;
    }
}".AssertReplace("protected int f;", before);
            var sln    = CodeFactory.CreateSolution(code);
            var editor = await DocumentEditor.CreateAsync(sln.Projects.First().Documents.First()).ConfigureAwait(false);

            var expected = @"
namespace N
{
    sealed class C
    {
        private int f;
    }
}".AssertReplace("private int f;", after);

            _ = editor.Seal(editor.OriginalRoot.Find <ClassDeclarationSyntax>("class C"));
            CodeAssert.AreEqual(expected, editor.GetChangedDocument());
        }
Exemplo n.º 21
0
        public static void LocalInLambda()
        {
            var code          = @"
namespace N
{
    using System;

    class C
    {
        public void M()
        {
            Console.CancelKeyPress += (sender, args) =>
            {
                var i = 0;
            };
        }
    }
}";
            var syntaxTree    = CSharpSyntaxTree.ParseText(code);
            var compilation   = CSharpCompilation.Create("test", new[] { syntaxTree }, Settings.Default.MetadataReferences);
            var semanticModel = compilation.GetSemanticModel(syntaxTree);
            var node          = syntaxTree.FindVariableDeclaration("var i = 0");

            Assert.AreEqual(true, semanticModel.TryGetSymbol(node, CancellationToken.None, out ILocalSymbol symbol));
            Assert.AreEqual(true, symbol.TryGetScope(CancellationToken.None, out var scope));
            CodeAssert.AreEqual("(sender, args) =>\r\n            {\r\n                var i = 0;\r\n            }", scope.ToString());
        }
Exemplo n.º 22
0
            public void WithExpectedDiagnosticWithWrongId()
            {
                var code     = @"
namespace RoslynSandbox
{
    class Foo
    {
        private readonly int value1;
    }
}";
                var expected = "Analyzer Gu.Roslyn.Asserts.Tests.FieldNameMustNotBeginWithUnderscore does not produce a diagnostic with ID WRONG.\r\n" +
                               "The analyzer produces the following diagnostics: {SA1309}\r\n" +
                               "The expected diagnostic is: WRONG";

                var expectedDiagnostic = ExpectedDiagnostic.Create("WRONG");

                var exception = Assert.Throws <NUnit.Framework.AssertionException>(() => AnalyzerAssert.Valid <FieldNameMustNotBeginWithUnderscore>(expectedDiagnostic, code));

                CodeAssert.AreEqual(expected, exception.Message);

                exception = Assert.Throws <NUnit.Framework.AssertionException>(() => AnalyzerAssert.Valid(typeof(FieldNameMustNotBeginWithUnderscore), expectedDiagnostic, code));
                Assert.AreEqual(expected, exception.Message);

                exception = Assert.Throws <NUnit.Framework.AssertionException>(() => AnalyzerAssert.Valid(new FieldNameMustNotBeginWithUnderscore(), expectedDiagnostic, code));
                Assert.AreEqual(expected, exception.Message);

                exception = Assert.Throws <NUnit.Framework.AssertionException>(() => AnalyzerAssert.Valid <FieldNameMustNotBeginWithUnderscore>(new[] { expectedDiagnostic }, code));
                Assert.AreEqual(expected, exception.Message);

                exception = Assert.Throws <NUnit.Framework.AssertionException>(() => AnalyzerAssert.Valid(typeof(FieldNameMustNotBeginWithUnderscore), new[] { expectedDiagnostic }, code));
                Assert.AreEqual(expected, exception.Message);

                exception = Assert.Throws <NUnit.Framework.AssertionException>(() => AnalyzerAssert.Valid(new FieldNameMustNotBeginWithUnderscore(), new[] { expectedDiagnostic }, code));
                Assert.AreEqual(expected, exception.Message);
            }
        private static void RunTest(string testCase, Assemblies.AssemblyDefinition asm, IEnumerable <TypeDefinition> types, IEnumerable <IGrouping <string, string> > matchingCode)
        {
            if (testCase == "Generics")
            {
                testCase.GetHashCode();
            }

            string decompiledText = Decompile(asm, types);

            IEnumerable <string> matchingFiles =
                matchingCode.FirstOrDefault(kv => string.Equals(kv.Key, testCase, StringComparison.OrdinalIgnoreCase));

            if (matchingFiles == null ||
                matchingFiles.Count() == 0)
            {
                throw new FileNotFoundException("No source code found for " + testCase + ".");
            }

            if (matchingFiles.Count() != 1)
            {
                throw new AmbiguousMatchException("More than one source code file found for " + testCase + ".");
            }

            string originalCode = matchingFiles.Single();


            string noComments = CodeSampleFileParser.ConcatLines(
                from line in SplitLines(originalCode)
                where !CodeSampleFileParser.IsIgnorableLine(line)
                select line);

            CodeAssert.AreEqual(noComments, decompiledText);
        }
Exemplo n.º 24
0
        public static void InternalPropertyBeforePublicWithComments()
        {
            var code   = @"
namespace N
{
    class C
    {
        // P1
        internal int P1 { get; set; }

        // P2
        public int P2 { get; set; }
    }
}";
            var editor = CreateDocumentEditor(code);

            _ = editor.MoveAfter(editor.OriginalRoot.Find <PropertyDeclarationSyntax>("P1"), editor.OriginalRoot.Find <PropertyDeclarationSyntax>("P2"));

            var expected = @"
namespace N
{
    class C
    {
        // P2
        public int P2 { get; set; }

        // P1
        internal int P1 { get; set; }
    }
}";

            CodeAssert.AreEqual(expected, editor.GetChangedDocument());
        }
Exemplo n.º 25
0
        public static async Task AddEventFieldDeclarationSyntax()
        {
            var code   = @"
namespace N
{
    public abstract class C
    {
        public int Filed1 = 1;
        private int filed1;

        public C()
        {
        }

        private C(int i)
        {
        }

        public int P1 { get; set; }

        public void M1()
        {
        }
    }
}";
            var sln    = CodeFactory.CreateSolution(code);
            var editor = await DocumentEditor.CreateAsync(sln.Projects.First().Documents.First()).ConfigureAwait(false);

            var eventDeclaration = (EventFieldDeclarationSyntax)editor.Generator.EventDeclaration("SomeEvent", SyntaxFactory.ParseTypeName("System.EventHandler"), Accessibility.Public);
            var containingType   = editor.OriginalRoot.SyntaxTree.FindClassDeclaration("C");

            _ = editor.AddEvent(containingType, eventDeclaration);
            var expected = @"
namespace N
{
    public abstract class C
    {
        public int Filed1 = 1;
        private int filed1;

        public C()
        {
        }

        private C(int i)
        {
        }

        public event System.EventHandler SomeEvent;

        public int P1 { get; set; }

        public void M1()
        {
        }
    }
}";

            CodeAssert.AreEqual(expected, editor.GetChangedDocument());
        }
Exemplo n.º 26
0
            public static void TwoDocumentsOneErrorCodeFixFixedTheCode()
            {
                var barCode = @"
namespace N
{
    class Bar
    {
        private readonly int value;
    }
}";

                var code      = @"
namespace N
{
    class C
    {
        private readonly int ↓_value;
    }
}";
                var analyzer  = new FieldNameMustNotBeginWithUnderscore();
                var fix       = new DoNotUseUnderscoreFix();
                var exception = Assert.Throws <AssertException>(() => RoslynAssert.NoFix(analyzer, fix, barCode, code));
                var expected  = "Expected code to have no fixable diagnostics.\r\n" +
                                "The following actions were registered:\r\n" +
                                "  'Rename to: 'value''\r\n";

                CodeAssert.AreEqual(expected, exception.Message);
            }
Exemplo n.º 27
0
        public void EnsureThatAnalyzerIndexIsAsExpected(string category, int tableNumber)
        {
            var          builder   = new StringBuilder();
            const string headerRow = "| Id       | Title       | :mag: | :memo: | :bulb: |";

            builder.AppendLine(headerRow)
            .AppendLine("| :--      | :--         | :--:  | :--:   | :--:   |");

            var descriptors = DescriptorsWithDocs
                              .Select(x => x.Descriptor)
                              .Where(x => x.Category == category)
                              .Distinct()
                              .OrderBy(x => x.Id);

            foreach (var descriptor in descriptors)
            {
                var enabledEmoji  = descriptor.IsEnabledByDefault ? ":white_check_mark:" : ":x:";
                var severityEmoji = SeverityEmoji[descriptor.DefaultSeverity];

                var codefixEmoji = diagnosticsWithCodeFixes.Contains(descriptor.Id)
                    ? ":white_check_mark:"
                    : ":x:";

                builder.Append($"| [{descriptor.Id}]({descriptor.HelpLinkUri}) ")
                .Append($"| {EscapeTags(descriptor.Title)} | {enabledEmoji} ")
                .AppendLine($"| {severityEmoji} | {codefixEmoji} |");
            }

            var expected = builder.ToString();

            DumpIfDebug(expected);
            var actual = GetTable(File.ReadAllText(Path.Combine(DocumentsDirectory.FullName, "index.md")), headerRow, tableNumber);

            CodeAssert.AreEqual(expected, actual);
        }
Exemplo n.º 28
0
        public static async Task TypicalClass()
        {
            var code   = @"
namespace N
{
    public abstract class C
    {
        public int F1 = 1;
        private int f2;

        public C()
        {
        }

        private C(int i)
        {
        }

        public int P1 { get; set; }

        public void M1()
        {
        }
    }
}";
            var sln    = CodeFactory.CreateSolution(code);
            var editor = await DocumentEditor.CreateAsync(sln.Projects.First().Documents.First()).ConfigureAwait(false);

            var declaration    = (PropertyDeclarationSyntax)SyntaxFactory.ParseMemberDeclaration("public int NewProperty { get; set; }");
            var containingType = editor.OriginalRoot.SyntaxTree.FindClassDeclaration("C");

            _ = editor.AddProperty(containingType, declaration);
            var expected = @"
namespace N
{
    public abstract class C
    {
        public int F1 = 1;
        private int f2;

        public C()
        {
        }

        private C(int i)
        {
        }

        public int P1 { get; set; }

        public int NewProperty { get; set; }

        public void M1()
        {
        }
    }
}";

            CodeAssert.AreEqual(expected, editor.GetChangedDocument());
        }
        public async Task AddBackingFieldWhenNameCollision()
        {
            var testCode = @"
namespace RoslynSandbox
{
    public class Foo
    {
        private int value;

        public int Value { get; set; }
    }
}";
            var sln      = CodeFactory.CreateSolution(testCode);
            var editor   = await DocumentEditor.CreateAsync(sln.Projects.First().Documents.First()).ConfigureAwait(false);

            var property = editor.OriginalRoot.SyntaxTree.FindPropertyDeclaration("Value");
            var field    = editor.AddBackingField(property, usesUnderscoreNames: false, cancellationToken: CancellationToken.None);

            Assert.AreEqual("privateint value_;", field.ToFullString());
            var expected = @"
namespace RoslynSandbox
{
    public class Foo
    {
        private int value;
        private int value_;

        public int Value { get; set; }
    }
}";

            CodeAssert.AreEqual(expected, editor.GetChangedDocument());
        }
Exemplo n.º 30
0
            public static void TwoDocumentsIndicatedAndActualPositionDoNotMatch()
            {
                var code1 = @"
namespace N
{
    class C1
    {
        private readonly int _value1;
    }
}";

                var code2 = @"
namespace N
{
    class C2
    {
        private readonly int ↓value2;
    }
}";

                var analyzer  = new FieldNameMustNotBeginWithUnderscore();
                var exception = Assert.Throws <AssertException>(() => RoslynAssert.Diagnostics(analyzer, code1, code2));
                var expected  = @"Expected and actual diagnostics do not match.
Expected:
  SA1309 
    at line 5 and character 29 in file C2.cs | private readonly int ↓value2;
Actual:
  SA1309 Field '_value1' must not begin with an underscore
    at line 5 and character 29 in file C1.cs | private readonly int ↓_value1;
";

                CodeAssert.AreEqual(expected, exception.Message);
            }