public void DoNotUseValuesWhenMultipleIsFalse() { var testContent = @" using Bridge.React; namespace TestCase { public class Example { public void Go() { new SelectAttributes { Multiple = false, Values = new[] { ""1"" } }; } } }"; var expected = new DiagnosticResult { Id = SelectAttributesAnalyzer.DiagnosticId, Message = SelectAttributesAnalyzer.DoNotUseValuesWhenMultipleIsFalseRule.MessageFormat.ToString(), Severity = DiagnosticSeverity.Warning, Locations = new[] { new DiagnosticResultLocation("Test0.cs", 10, 29) } }; VerifyCSharpDiagnostic(testContent, expected); }
public void Test1() { var test = @" class C { public void M1() { } public virtual void M2() { } public int M3() { } }"; var expected = new DiagnosticResult { Id = DiagnosticIds.CodeBlockAnalyzerRuleId, Message = string.Format(Resources.CodeBlockAnalyzerMessageFormat, "M1"), Severity = DiagnosticSeverity.Warning, Locations = new[] { new DiagnosticResultLocation("Test0.cs", 4, 17) } }; VerifyCSharpDiagnostic(test, expected); }
public void AccessWithoutChecking() { var code = @" using System; using System.Linq; namespace ConsoleApp1 { public class Test0 { public void Tested() { var obj = new Object(); var s = obj as String; var toString = s.ToString(); } } } "; var expected = new DiagnosticResult { Id = "AV1570", Message = "Always check the result of an as operation", Severity = DiagnosticSeverity.Warning, Locations = new[] { new DiagnosticResultLocation("Test0.cs", 15, 52) } }; VerifyCSharpDiagnostic(code, expected); }
public void TestMethod2() { const String test = @" using System; namespace ConsoleApplication1 { class TypeName { } }"; var expected = new DiagnosticResult { Id = "CSharpCodeFixes", Message = $"Type name '{"TypeName"}' contains lowercase letters", Severity = DiagnosticSeverity.Warning, Locations = new[] { new DiagnosticResultLocation("Test0.cs", 6, 15) } }; VerifyCSharpDiagnostic(test, expected); const String fixtest = @" using System; namespace ConsoleApplication1 { class TYPENAME { } }"; VerifyCSharpFix(test, fixtest); }
public void AssertEquals_IfActualValueIsAStringLiteral_ThenItTriggersTheDiagnostic() { var test = @" using System; using System.Linq; using Xunit; namespace WongaTests { class WongaTest { [Fact] public void MyTest() { var result = Testee.GetSomeData(); Assert.Equal(result.Id, ""someId""); } } }"; var expected = new DiagnosticResult { Id = "AssertExpectedActualAnalyser", Message = "Possible incorrect argument order in 'Assert.Equal': '\"someId\"' is likely to be the expected value", Severity = DiagnosticSeverity.Warning, Locations = new[] { new DiagnosticResultLocation("Test0.cs", 14, 17) } }; VerifyCSharpDiagnostic(test, expected); }
public void CorrectDiagnosticWhenAnonymousTypeIsUsed() { // Fixture setup var test = @" using System; namespace ConsoleApplication1 { class C { void M() { var a = new { P = ""dummy"" }; } } }"; var expected = new DiagnosticResult { Id = "ExtractAnonymousType", Message = "Anonymous type used", Severity = DiagnosticSeverity.Info, Locations = new[] { new DiagnosticResultLocation("Test0.cs", 10, 25) } }; // Exercise system & Verify outcome VerifyCSharpDiagnostic(test, expected); // Teardown }
public void TestMethod2() { var test = @"using System; using FluentArithmetic; class Program { static void Main(string[] args) { var x = 1.Add(2).Mul(3).Sub(1).Div(0); Console.WriteLine(x); } } "; var expected = new DiagnosticResult { Id = DivByZeroAnalyzer.DiagnosticId, Message = DivByZeroAnalyzer.MessageFormat.ToString(), Severity = DiagnosticSeverity.Error, Locations = new[] { new DiagnosticResultLocation("Test0.cs", 8, 44) } }; VerifyCSharpDiagnostic(test, expected); }
public void ValidateDiagnosticFires() { var test = @" using System; using System.Collections.Generic; namespace ConsoleApplication1 { class TypeName { var a = new System.Collections.ArrayList(); } }"; var expected = new DiagnosticResult { Id = DontUseArrayList.DiagnosticId, Message = "The type ArrayList should not be used", Severity = DiagnosticSeverity.Warning, Locations = new[] { new DiagnosticResultLocation("Test0.cs", 9, 20) } }; VerifyCSharpDiagnostic(test, expected); }
public void ForeachSimpleStatementAssignment() { var code = @" using System; using System.Linq; namespace ConsoleApp1 { public class Test0 { public void Tested() { var list = new List<int>(); foreach(var item in list) item = null; } } } "; var expected = new DiagnosticResult { Id = "AV1530", Message = "Don’t change a loop variable inside a for or foreach loop", Severity = DiagnosticSeverity.Warning, Locations = new[] { new DiagnosticResultLocation("Test0.cs", 13, 41) } }; VerifyCSharpDiagnostic(code, expected); }
public void MethodNamesTest() { string test = System.IO.File.ReadAllText(@"TestCodes\AsyncTestCode_1.cs"); var expected1 = new DiagnosticResult { Id = AsyncAnalyzerAnalyzer.DiagnosticId, Message = String.Format("Async method name '{0}' does not end with Async", "Test"), Severity = DiagnosticSeverity.Warning, Locations = new[] { new DiagnosticResultLocation("Test0.cs", 12, 27), } }; var expected2 = new DiagnosticResult { Id = AsyncAnalyzerAnalyzer.DiagnosticId, Message = String.Format("Async method name '{0}' does not end with Async", "Something"), Severity = DiagnosticSeverity.Warning, Locations = new[] { new DiagnosticResultLocation("Test0.cs", 28, 33), } }; VerifyCSharpDiagnostic(test, expected1, expected2); string fixtest = System.IO.File.ReadAllText(@"TestCodes\AsyncTestCode_1_fix.cs"); VerifyCSharpFix(test, fixtest); }
public void TestBasicEmptyComment() { var testCode = @" class Foo { public void Bar() { // } }"; var expected = new DiagnosticResult { Id = EmptyCommentAnalyzer.DiagnosticId, Message = EmptyCommentAnalyzer.MessageFormat.ToString(), Severity = DiagnosticSeverity.Warning, Locations = new[] { new DiagnosticResultLocation("Test0.cs", 6, 9) } }; this.VerifyCSharpDiagnostic(testCode, expected); var expectedFixedCode = @" class Foo { public void Bar() { } }"; this.VerifyCSharpFix(testCode, expectedFixedCode); }
public void FindAsyncMethodsOnlyWithReturnTypeTaskTest() { string test = System.IO.File.ReadAllText(@"TestCodes\AsyncTestCode_1.cs"); var expected1 = new DiagnosticResult { Id = DetectAsyncTaskAnalyzer.DiagnosticId, Message = string.Format("Async method '{0}' has return type Task.", "Test"), Severity = DiagnosticSeverity.Info, Locations = new[] { new DiagnosticResultLocation("Test0.cs", 12, 27), } }; var expected2 = new DiagnosticResult { Id = DetectAsyncTaskAnalyzer.DiagnosticId, Message = string.Format("Async method '{0}' has return type Task.", "Test4Async"), Severity = DiagnosticSeverity.Info, Locations = new[] { new DiagnosticResultLocation("Test0.cs", 24, 27), } }; VerifyCSharpDiagnostic(test, expected1, expected2); }
public void InstantiationOfNestedGenericTypeThatReferencesReactElementWillFail() { var testContent = @" using System.Collections.Generic; using Bridge.React; namespace TestCase { public class Example { public void Go() { var x = new List<KeyValuePair<string, ReactElement>>(); } } }"; var expected = new DiagnosticResult { Id = ReactElementAnalyser.DiagnosticId, Message = ReactElementAnalyser.InstantiationsThatReferToTypesNotAvailableAtRuntimeRule.MessageFormat.ToString(), Severity = DiagnosticSeverity.Error, Locations = new[] { new DiagnosticResultLocation("Test0.cs", 11, 46) } }; VerifyCSharpDiagnostic(testContent, expected); }
public void UnHandle() { var source = @" using System; class Test { IObservable<int> GetObservable() => null; void Hoge() { GetObservable(); } }"; var expected = new DiagnosticResult { Id = UniRxAnalyzer.HandleObservableAnalyzer.DiagnosticId, Message = "This call does not handle IObservable<T>.", Severity = DiagnosticSeverity.Warning, Locations = new[] { new DiagnosticResultLocation("Test0.cs", 10, 9) } }; this.VerifyCSharpDiagnostic(source, expected); }
public void Test1() { var test = @" class C { public void M() { } }"; var expected = new DiagnosticResult { Id = DiagnosticIds.SyntaxTreeAnalyzerRuleId, Message = string.Format(Resources.SyntaxTreeAnalyzerMessageFormat, "Test0.cs"), Severity = DiagnosticSeverity.Warning }; var parseOptions = CSharpParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose); VerifyCSharpDiagnostic(test, parseOptions, compilationOptions: null); parseOptions = CSharpParseOptions.Default.WithDocumentationMode(DocumentationMode.None); VerifyCSharpDiagnostic(test, parseOptions, compilationOptions: null, expected: expected); parseOptions = CSharpParseOptions.Default.WithDocumentationMode(DocumentationMode.Parse); VerifyCSharpDiagnostic(test, parseOptions, compilationOptions: null, expected: expected); }
public void Test1() { var test = @" class C { public void M() { var implicitTypedLocal = 0; int explicitTypedLocal = 1; } }"; var expected = new DiagnosticResult { Id = DiagnosticIds.SyntaxNodeAnalyzerRuleId, Message = string.Format(Resources.SyntaxNodeAnalyzerMessageFormat, "implicitTypedLocal"), Severity = DiagnosticSeverity.Warning, Locations = new[] { new DiagnosticResultLocation("Test0.cs", 6, 13) } }; VerifyCSharpDiagnostic(test, expected); }
public void CorrectDiagnosticWhenAnonymousTypeInProjection() { // Fixture setup var test = @" using System; using System.Linq; namespace N { class C { void M() { var q = Enumerable.Range(0, 5) .Select(i => new { Qux = i }); } } }"; var expected = new DiagnosticResult { Id = "ExtractAnonymousType", Message = "Anonymous type used", Severity = DiagnosticSeverity.Info, Locations = new[] { new DiagnosticResultLocation("Test0.cs", 12, 30) } }; // Exercise system & Verify outcome VerifyCSharpDiagnostic(test, expected); // Teardown }
public void NestedExplicitPrivateClassInStruct() { const string Test = @" namespace N { struct S { private class NC { } } }"; const string Fixed = @" namespace N { struct S { class NC { } } }"; var expected = new DiagnosticResult { Id = ExplicitDefaultAccessModifiersAnalyzer.DiagnosticId, Severity = DiagnosticSeverity.Warning, Locations = new[] { new DiagnosticResultLocation("Test0.cs", 6, 3) } }; VerifyCSharpDiagnostic(Test, expected); VerifyCSharpFix(Test, Fixed); }
public void Test1() { var test = @" class BadOne { public void BadOne() {} } class GoodOne { }"; var expected = new DiagnosticResult { Id = DiagnosticIds.SymbolAnalyzerRuleId, Message = string.Format(Resources.SymbolAnalyzerMessageFormat, "BadOne"), Severity = DiagnosticSeverity.Warning, Locations = new[] { new DiagnosticResultLocation("Test0.cs", 2, 7) } }; VerifyCSharpDiagnostic(test, expected); }
public void ExplicitPrivateMethod() { const string Test = @" namespace N { class C { private int M() { }; } }"; const string Fixed = @" namespace N { class C { int M() { }; } }"; var expected = new DiagnosticResult { Id = ExplicitDefaultAccessModifiersAnalyzer.DiagnosticId, Severity = DiagnosticSeverity.Warning, Locations = new[] { new DiagnosticResultLocation("Test0.cs", 6, 3) } }; VerifyCSharpDiagnostic(Test, expected); VerifyCSharpFix(Test, Fixed); }
public void Test1() { var test = @" class C { public int M1(int p1, int p2) { return M2(p1, p1); } public int M2(int p1, int p2) { return p1 + p2; } }"; var expected = new DiagnosticResult { Id = DiagnosticIds.CodeBlockStartedAnalyzerRuleId, Message = string.Format(Resources.CodeBlockStartedAnalyzerMessageFormat, "p2", "M1"), Severity = DiagnosticSeverity.Warning, Locations = new[] { new DiagnosticResultLocation("Test0.cs", 4, 31) } }; VerifyCSharpDiagnostic(test, expected); }
public void Test1() { var test = @" class C { public void M() { } }"; var expected = new DiagnosticResult { Id = DiagnosticIds.CompilationAnalyzerRuleId, Message = string.Format(Resources.CompilationAnalyzerMessageFormat, DiagnosticIds.SymbolAnalyzerRuleId), Severity = DiagnosticSeverity.Warning }; var specificOption = new KeyValuePair<string, ReportDiagnostic>(DiagnosticIds.SymbolAnalyzerRuleId, ReportDiagnostic.Error); var compilationOptions = new CSharpCompilationOptions(OutputKind.ConsoleApplication, specificDiagnosticOptions: new[]{ specificOption }); VerifyCSharpDiagnostic(test, parseOptions: null, compilationOptions: compilationOptions); specificOption = new KeyValuePair<string, ReportDiagnostic>(DiagnosticIds.SymbolAnalyzerRuleId, ReportDiagnostic.Suppress); compilationOptions = compilationOptions.WithSpecificDiagnosticOptions(new[] { specificOption }); VerifyCSharpDiagnostic(test, parseOptions: null, compilationOptions: compilationOptions, expected: expected); }
public void Test1() { var test = @" namespace MyInterfaces { public interface Interface {} class MyInterfaceImpl : Interface { } class MyInterfaceImpl2 : Interface { } }"; var expected = new DiagnosticResult { Id = DiagnosticIds.CompilationStartedAnalyzerRuleId, Message = string.Format(Resources.CompilationStartedAnalyzerMessageFormat, "MyInterfaceImpl2", CompilationStartedAnalyzer.DontInheritInterfaceTypeName), Severity = DiagnosticSeverity.Warning, Locations = new[] { new DiagnosticResultLocation("Test0.cs", 10, 11) } }; VerifyCSharpDiagnostic(test, expected); }
public void IfDateTimeAddMethodIsCalledAndResultNotAssigned_ItIsDiagnosed() { var test = @" using System; namespace ConsoleApplication1 { class C { public void Oops() { DateTime t = DateTime.UtcNow; t.AddSeconds(1); Console.WriteLine(s); } } }"; var expected = new DiagnosticResult { Id = "OperationsMistakenForInPlace", Message = "Result of 'System.DateTime.AddSeconds' is discarded - did you mean to assign it?", Severity = DiagnosticSeverity.Warning, Locations = new[] { new DiagnosticResultLocation("Test0.cs", 11, 17) } }; VerifyCSharpDiagnostic(test, expected); }
public void TestCSharpAtrributesPresentButEmpty() { var expected = new DiagnosticResult[4]; expected[0] = CompanyAttributeResult; expected[1] = CopyrightAttributeResult; expected[2] = DescriptionAttributeResult; expected[3] = TitleAttributeResult; VerifyCSharpDiagnostic(@" using System; using System.Reflection; [assembly: AssemblyTitle("""")] [assembly: AssemblyDescription("""")] [assembly: AssemblyCompany("""")] [assembly: AssemblyCopyright("""")] namespace SomeTests { public class BasicClass { public void SomeWork(String message) { Console.WriteLine(message); } } } ", expected); }
public void TestMethod2() { var test = @" using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Diagnostics; namespace ConsoleApplication1 { class TypeName { static void Main(string[] args) { if (true) { Console.WriteLine(""Hello World""); } } } }"; var expected = new DiagnosticResult { Id = SyntaxNodeAnalyzerAnalyzer.spacingRuleId, Message = String.Format("If statements must contain a space between the 'if' keyword and the boolean expression)"), //make sure this message matches the original message Severity = DiagnosticSeverity.Warning, //make sure this matches the original Locations = new[] { new DiagnosticResultLocation("Test0.cs", 15, 17) } }; VerifyCSharpDiagnostic(test, expected); var fixtest = @" using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Diagnostics; namespace ConsoleApplication1 { class TypeName { static void Main(string[] args) { if (true) { Console.WriteLine(""Hello World""); } } } }"; VerifyCSharpFix(test, fixtest); }
public void Diagnostics_and_code_fix_when_enum_value_missing() { var test = @" using System; namespace Application { enum MyEnum { A, B, C, D, E, F } class MyClass { public static void Function() { MyEnum e = 0; switch (e) { case MyEnum.A: case MyEnum.B: case MyEnum.C: case MyEnum.D: case MyEnum.E: break; } } } }"; var expected = new DiagnosticResult { Id = "EnumSwitchAnalyzer", Message = string.Format("switch on enum 'MyEnum' is missing the following members: 'F'"), Severity = DiagnosticSeverity.Error, Locations = new[] { new DiagnosticResultLocation("Test0.cs", 10, 13) } }; VerifyCSharpDiagnostic(test, expected); var fixtest = @" using System; namespace Application { enum MyEnum { A, B, C, D, E, F } class MyClass { public static void Function() { MyEnum e = 0; switch (e) { case MyEnum.A: case MyEnum.B: case MyEnum.C: case MyEnum.D: case MyEnum.E: break; case MyEnum.F: throw new NotImplementedException(); } } } }"; VerifyCSharpFix(test, fixtest); }
public void TestMethod2() { var test = @" using System; using DDDCore; namespace MyDomain { public class MyAggregateRoot : IAggregateRoot<int> { public int AggregateRootId { get; set; } int IAggregateRoot<int>.Id { get { return AggregateRootId; } } } } "; var expected = new DiagnosticResult { Id = "PropertiesCannotBePublic", Message = String.Format("Property '{0}' in '{1}' cannot not be public", "AggregateRootId", "MyAggregateRoot"), Severity = DiagnosticSeverity.Error, Locations = new[] { new DiagnosticResultLocation("Test0.cs", 9, 24) } }; VerifyCSharpDiagnostic(test, expected); var fixtest = @" using System; using DDDCore; namespace MyDomain { public class MyAggregateRoot : IAggregateRoot<int> { private int AggregateRootId { get; set; } int IAggregateRoot<int>.Id { get { return AggregateRootId; } } } } "; VerifyCSharpFix(test, fixtest); }
public void TestMethod2() { var test = @" using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Diagnostics; namespace ConsoleApplication1 { class TypeName { public void TestMethod() { string strTest = ""; } } }"; var expected = new DiagnosticResult { Id = DehungarianAnalyzer.DiagnosticId, Message = String.Format("Identifier '{0}' contains a Hungarian style prefix", "strTest"), Severity = DiagnosticSeverity.Warning, Locations = new[] { new DiagnosticResultLocation("Test0.cs", 15, 20) } }; VerifyCSharpDiagnostic(test, expected); var fixtest = @" using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Diagnostics; namespace ConsoleApplication1 { class TypeName { public void TestMethod() { string someString = ""; } } }"; VerifyCSharpFix(test, fixtest); }
public void Empty() { var test = @""; var expected = new DiagnosticResult { Id = RequireIPluginAnalyzer.DiagnosticId, Severity = DiagnosticSeverity.Error, Message = message, }; this.VerifyCSharpDiagnostic(test, expected); }
/// <summary> /// Checks each of the actual Diagnostics found and compares them with the corresponding DiagnosticResult in the array of expected results. /// Diagnostics are considered equal only if the DiagnosticResultLocation, Id, Severity, and Message of the DiagnosticResult match the actual diagnostic. /// </summary> /// <param name="actualResults">The Diagnostics found by the compiler after running the analyzer on the source code</param> /// <param name="analyzer">The analyzer that was being run on the sources</param> /// <param name="expectedResults">Diagnostic Results that should have appeared in the code</param> private static void VerifyDiagnosticResults(IEnumerable <Diagnostic> actualResults, DiagnosticAnalyzer analyzer, params DiagnosticResult[] expectedResults) { int expectedCount = expectedResults.Length; int actualCount = actualResults.Count(); if (expectedCount != actualCount) { string diagnosticsOutput = actualResults.Any() ? FormatDiagnostics(analyzer, actualResults.ToArray()) : " NONE."; Assert.IsTrue(false, string.Format("Mismatch between number of diagnostics returned, expected \"{0}\" actual \"{1}\"\r\n\r\nDiagnostics:\r\n{2}\r\n", expectedCount, actualCount, diagnosticsOutput)); } for (int i = 0; i < expectedResults.Length; i++) { Diagnostic actual = actualResults.ElementAt(i); DiagnosticResult expected = expectedResults[i]; if (expected.Line == -1 && expected.Column == -1) { if (actual.Location != Location.None) { Assert.IsTrue(false, string.Format("Expected:\nA project diagnostic with No location\nActual:\n{0}", FormatDiagnostics(analyzer, actual))); } } else { VerifyDiagnosticLocation(analyzer, actual, actual.Location, expected.Locations.First()); Location[] additionalLocations = actual.AdditionalLocations.ToArray(); if (additionalLocations.Length != expected.Locations.Length - 1) { Assert.IsTrue(false, string.Format("Expected {0} additional locations but got {1} for Diagnostic:\r\n {2}\r\n", expected.Locations.Length - 1, additionalLocations.Length, FormatDiagnostics(analyzer, actual))); } for (int j = 0; j < additionalLocations.Length; ++j) { VerifyDiagnosticLocation(analyzer, actual, additionalLocations[j], expected.Locations[j + 1]); } } if (actual.Id != expected.Id) { Assert.IsTrue(false, string.Format("Expected diagnostic id to be \"{0}\" was \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n", expected.Id, actual.Id, FormatDiagnostics(analyzer, actual))); } if (actual.Severity != expected.Severity) { Assert.IsTrue(false, string.Format("Expected diagnostic severity to be \"{0}\" was \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n", expected.Severity, actual.Severity, FormatDiagnostics(analyzer, actual))); } if (actual.GetMessage() != expected.Message) { Assert.IsTrue(false, string.Format("Expected diagnostic message to be \"{0}\" was \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n", expected.Message, actual.GetMessage(), FormatDiagnostics(analyzer, actual))); } } }
/// <summary> /// Called to test a C# <see cref="DiagnosticAnalyzer"/> when applied on the single input source as a string. /// <note type="note"> /// <para>Input a <see cref="DiagnosticResult"/> for the expected <see cref="Diagnostic"/>.</para> /// </note> /// </summary> /// <param name="source">A class in the form of a string to run the analyzer on.</param> /// <param name="expected">A <see cref="DiagnosticResult"/>s describing the <see cref="Diagnostic"/> that should /// be reported by the analyzer for the specified source.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> that the task will observe.</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> protected Task VerifyCSharpDiagnosticAsync(string source, DiagnosticResult expected, CancellationToken cancellationToken) { return(this.VerifyCSharpDiagnosticAsync(source, new[] { expected }, cancellationToken)); }