public void ExtensionMethodCallSelfErrors2()
        {
            const string Template = @"
using System;
using System.Collections.Generic;
using System.Linq;

public static class Foo
{{
  public static void RemoveByKeys<TKey, TValue>(this IDictionary<TKey, TValue> dict, IEnumerable<TKey> keys)
  {{
    foreach (var item in keys)
      dict.Remove(item);
  }}

  public static void RemoveWhereValue<TKey, TValue>(this IDictionary<TKey, TValue> dict, Predicate<TValue> predicate)
  {{
    var items = new List<TKey>(dict.Keys);
    {0};
  }}
}}
";
            var          text     = string.Format(Template, "RemoveByKeys(dict, items)");

            DiagnosticResult[] result = new[] { DiagnosticResultHelper.Create(DiagnosticIds.ExtensionMethodsCalledLikeInstanceMethods) };

            VerifyCSharpDiagnostic(text, result);

            string newText = string.Format(Template, "dict.RemoveByKeys(items)");

            VerifyCSharpFix(text, newText);
        }
        public void DontStringFormatUselessly6a()
        {
            const string template = @"
using System;

static class StringHelper
{
	public static string Format(string format, params object[] args)
	{
		return string.Empty;
	}
}

class Foo
{
	string XPath => ""tests""

	public void Test()
	{
		Foo obx = new Foo();

		string tooltip = StringHelper.Format(""{0}"", obx.XPath);
	}
}
";

            VerifyCSharpDiagnostic(template, DiagnosticResultHelper.Create(DiagnosticIds.NoUnnecessaryStringFormats));
        }
Exemple #3
0
        public void LockObjectsMustBeReadonlyFunctionReturn(string field, bool isError)
        {
            const string template = @"using System;
class Foo
{{
	public object GetFoo()
	{{
		return null;
	}}

	public void Test()
	{{
		{0} = GetFoo();
		lock(foo) {{ }}
	}}
}}
";
            var          result   = Array.Empty <DiagnosticResult>();

            if (isError)
            {
                result = new[] { DiagnosticResultHelper.Create(DiagnosticIds.LocksShouldBeReadonly) };
            }

            VerifyCSharpDiagnostic(string.Format(template, field), result);
        }
        public void DontStringFormatUselessly2()
        {
            const string template = @"
using System;

namespace Philips.Platform
{
public static class StringHelper
{
	public static string Format(string format, params object[] args)
	{
		return string.Empty;
	}
}
}

class Foo
{
	public void Test()
	{
		string t = Philips.Platform.StringHelper.Format(""test"");
	}
}
";

            VerifyCSharpDiagnostic(template, DiagnosticResultHelper.Create(DiagnosticIds.NoUnnecessaryStringFormats));
        }
        public void ExtensionMethodCallSelfErrors()
        {
            const string Template = @"
using System;

public static class Foo
{{
  public static void Bar(this object obj)
  {{
    {0};
  }}

  public static void Bar(this object obj, object other)
  {{
  }}
}}
";
            var          text     = string.Format(Template, "Bar(obj, null)");

            DiagnosticResult[] result = new[] { DiagnosticResultHelper.Create(DiagnosticIds.ExtensionMethodsCalledLikeInstanceMethods) };

            VerifyCSharpDiagnostic(text, result);

            string newText = string.Format(Template, "obj.Bar(null)");

            VerifyCSharpFix(text, newText);
        }
Exemple #6
0
        public void EmptyMethodTriggersAnalyzer(string attribute)
        {
            const string template = @"using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass] public class Foo {{ [{0}] public void Method() {{ }} }}";

            VerifyCSharpDiagnostic(string.Format(template, attribute), DiagnosticResultHelper.Create(DiagnosticIds.TestMethodsMustNotBeEmpty));
        }
        public void CatchesHardCodedPaths2()
        {
            const string template = @"
using System;

enum DialogResult { }

static class MessageBoxHelper
{
	public static DialogResult Warn(string format, params object[] args)
	{
		return string.Empty;
	}
}

class Foo
{
	public void Test()
	{
		string t = @""c:\users\Bin\example.xml"";
	}
}
";

            VerifyCSharpDiagnostic(template, DiagnosticResultHelper.Create(DiagnosticIds.NoHardcodedPaths));
        }
        public void DontStringFormatUselessly2a(string arg)
        {
            string template = $@"
using System;

class Log
{{
	public void Err(string format, params object[] args)
	{{
	}}

	public Log Platform {{ get; }}
}}

class Foo
{{
	public void Test()
	{{
		Log.Platform.Err(""{arg}"");
	}}
}}
";

            VerifyCSharpDiagnostic(template, DiagnosticResultHelper.Create(DiagnosticIds.NoUnnecessaryStringFormats));
        }
        public void DontStringFormatUselesslyFromOutParameter()
        {
            const string template = @"
using System;

static class StringHelper
{
	public static string Format(string format, params object[] args)
	{
		return string.Empty;
	}
}

class Foo
{
	public static void Bar(out string s)
	{
		s = string.Empty;
	}

	public void Test()
	{
		Bar(out string s);
		string tooltip = StringHelper.Format(""{0}"", s);
	}
}
";

            VerifyCSharpDiagnostic(template, DiagnosticResultHelper.Create(DiagnosticIds.NoUnnecessaryStringFormats));
        }
Exemple #10
0
        public void TestMethodsMustBeInTestClass2(string testType, int parameters, int dataRowParameters, bool isDynamicData, bool hasDisplayName, bool isCorrect)
        {
            const string template = @"using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;

[TestClass]
public class Tests
{{
	{3}
	{2}
	{0}
	public void Foo({1}) {{ }}

	private static IEnumerable<object[]> GetVariants()
	{{ return Array.Empty<object[]>(); }}
}}";

            string[] parameterListStrings = new string[parameters];
            for (int i = 0; i < parameters; i++)
            {
                parameterListStrings[i] = $"int p{i}";
            }

            string parameterListString = string.Join(',', parameterListStrings);

            string dataRow = string.Empty;

            if (dataRowParameters >= 0)
            {
                List <string> dataRowParametersStrings = new List <string>();
                for (int i = 0; i < dataRowParameters; i++)
                {
                    dataRowParametersStrings.Add(i.ToString());
                }

                if (hasDisplayName)
                {
                    dataRowParametersStrings.Add("DisplayName = \"blah\"");
                }

                string dataRowText = string.Format($"[DataRow({string.Join(',', dataRowParametersStrings)})]");

                dataRow = dataRowText;
            }

            string code = string.Format(template, testType, parameterListString, dataRow, isDynamicData ? "[DynamicData(nameof(GetVariants))]" : string.Empty);

            if (isCorrect)
            {
                VerifyCSharpDiagnostic(code);
            }
            else
            {
                VerifyCSharpDiagnostic(code, DiagnosticResultHelper.Create(DiagnosticIds.TestMethodsMustHaveTheCorrectNumberOfArguments));
            }
        }
        public void ExtensionMethodsDontCallDifferentMethods(string template, bool isError)
        {
            DiagnosticResult[] result = Array.Empty <DiagnosticResult>();
            if (isError)
            {
                result = new[] { DiagnosticResultHelper.Create(DiagnosticIds.ExtensionMethodsCalledLikeInstanceMethods) };
            }

            VerifyCSharpDiagnostic(template, result);
        }
Exemple #12
0
        public void ProtectedFieldsRaiseError(string modifiers, bool isError)
        {
            const string template = @"""
class Foo {{ {0} string _foo; }}
""";

            DiagnosticResult[] expected = isError ? new[] { DiagnosticResultHelper.Create(DiagnosticIds.NoProtectedFields) } : Array.Empty <DiagnosticResult>();

            VerifyCSharpDiagnostic(string.Format(template, modifiers), expected);
        }
        public void CantBeDynamic(string testCode, int errorCount)
        {
            List <DiagnosticResult> results = new List <DiagnosticResult>();

            for (int i = 0; i < errorCount; i++)
            {
                results.Add(DiagnosticResultHelper.Create(DiagnosticIds.DynamicKeywordProhibited));
            }

            VerifyCSharpDiagnostic(testCode, results.ToArray());
        }
        public void CheckNestedRange(string declaration, string countLengthMethod)
        {
            const string template = @"
public class Container
{{
  public {0};
}}

class Foo
{{
  public void test()
  {{
    Container container = new Container();
    // comment
    if(container.data.{1} > 0)
    {{
      foreach (int i in container.data)
      {{
      }}
      //middle comment
    }}
    // end comment
  }}
}}
";

            const string fixedTemplate = @"
public class Container
{{
  public {0};
}}

class Foo
{{
  public void test()
  {{
    Container container = new Container();
    // comment
    foreach (int i in container.data)
    {{
    }}
    //middle comment
    // end comment
  }}
}}
";

            string errorCode = string.Format(template, declaration, countLengthMethod);

            VerifyCSharpDiagnostic(errorCode, DiagnosticResultHelper.Create(DiagnosticIds.PreventUncessaryRangeChecks));

            VerifyCSharpFix(errorCode, string.Format(fixedTemplate, declaration));
        }
        public void CatchesHardCodedPathsRegardlessOfCase()
        {
            const string template = @"
using System;
class Foo
{
	public void Test()
	{
		string path = @""C:\USERS\BIN\EXAMPLE.XML"";
	}
}
";

            VerifyCSharpDiagnostic(template, DiagnosticResultHelper.Create(DiagnosticIds.NoHardcodedPaths));
        }
        public void CatchesHardCodedAbsoluteLinuxPaths()
        {
            const string template = @"
using System;
class Foo
{
	public void Test()
	{
		string path = @""/boot/grub/grub.conf"";
	}
}
";

            VerifyCSharpDiagnostic(template, DiagnosticResultHelper.Create(DiagnosticIds.NoHardcodedPaths));
        }
        public void CatchesHardCodedAbsoluteWindowsPathWithDoubleSlash()
        {
            const string template = @"
using System;
class Foo
{
	public void Test()
	{
		string path = @""c:\\users\\Bin\\example.xml"";
	}
}
";

            VerifyCSharpDiagnostic(template, DiagnosticResultHelper.Create(DiagnosticIds.NoHardcodedPaths));
        }
        public void CatchesNestedInterpolatedStringFormat()
        {
            const string template = @"
using System;
class Foo
{
	public void Test()
	{
		string t = string.Format($""test"", 1);
	}
}
";

            VerifyCSharpDiagnostic(template, DiagnosticResultHelper.Create(DiagnosticIds.NoNestedStringFormats));
        }
        public void CatchesHardCodedPathsWithSpecialCharacters()
        {
            const string template = @"
using System;
class Foo
{
	public void Test()
	{
		string path = @""c:\users\test_first-second.third@fourth\Bin\example.xml"";
	}
}
";

            VerifyCSharpDiagnostic(template, DiagnosticResultHelper.Create(DiagnosticIds.NoHardcodedPaths));
        }
        public void NoLabeledStatements()
        {
            const string template = @"
using System;
class Foo
{
	public void Test()
	{
		test:
			Console.WriteLine();
	}
}
";

            VerifyCSharpDiagnostic(template, DiagnosticResultHelper.Create(DiagnosticIds.GotoNotAllowed));
        }
Exemple #21
0
        public void HeaderIsDetected2()
        {
            string baseline  = @"using Microsoft.VisualStudio.TestTools.UnitTesting;
class Foo 
{{
  public void Foo()
  {{
  }}
}}
";
            string givenText = baseline;

            DiagnosticResult[] expected = new[] { DiagnosticResultHelper.Create(DiagnosticIds.CopyrightPresent) };

            VerifyCSharpDiagnostic(givenText, expected);
        }
        public void DontStringFormatUselessly()
        {
            const string template = @"
using System;

class Foo
{
	public void Test()
	{
		string t = string.Format(""test"");
	}
}
";

            VerifyCSharpDiagnostic(template, DiagnosticResultHelper.Create(DiagnosticIds.NoUnnecessaryStringFormats));
        }
        public void SwitchExpressionWithOnlyDefaultCaseIsFlagged(string type)
        {
            string input = $@"
public static class Foo
{{
  public static void Method({type} data)
  {{
    int a = data switch
    {{
      _ => 1
    }}
  }}
}}
";

            VerifyCSharpDiagnostic(input, DiagnosticResultHelper.Create(DiagnosticIds.AvoidSwitchStatementsWithNoCases));
        }
        public void SwitchWithOnlyDefaultCaseIsFlagged(string type)
        {
            string input = $@"
public static class Foo
{{
  public static void Method({type} data)
  {{
    switch(data)
    {{
      default:
        System.Console.WriteLine(data);
        break;
    }}
  }}
}}
";

            VerifyCSharpDiagnostic(input, DiagnosticResultHelper.Create(DiagnosticIds.AvoidSwitchStatementsWithNoCases));
        }
        public void DontStringFormatUselesslyLogStatement(string format, string args, bool isError)
        {
            const string template = @"
using System;

public static class LogExtensions
{{
	public void Err(this Log log, string format, params object[] args)
	{{
	}}
}}

public class Log
{{
	public void Err(FormattableString fs)
	{{
	}}
}}

public static class Logs
{{
	public static Log ServiceAudit {{ get; }}
}}

class Foo
{{
	public void Test(out string errorMessage)
	{{
		errorMessage = this.ToString();
		Logs.ServiceAudit.Err({0}{1});
	}}
}}
";

            DiagnosticResult[] expected = Array.Empty <DiagnosticResult>();
            if (isError)
            {
                expected = new[] { DiagnosticResultHelper.Create(DiagnosticIds.NoUnnecessaryStringFormats) };
            }

            VerifyCSharpDiagnostic(string.Format(template, format, args), expected);
        }
        public void NoGotoDefault()
        {
            const string template = @"
using System;
class Foo
{
	public void Test(int a)
	{
		switch(a)
		{
			case 1: goto case default;
			default:
				break;
		}
	}
}
";

            VerifyCSharpDiagnostic(template, DiagnosticResultHelper.Create(DiagnosticIds.GotoNotAllowed));
        }
        public void CatchesNestedInterpolatedStringFormatCustomMethod()
        {
            const string template = @"
using System;

class Foo
{
	public static void Log(int category, string format, params object[] args)
	{
	}

	public void Test()
	{
		Log(8, string.Format(""test"", 1));
	}
}
";

            VerifyCSharpDiagnostic(template, DiagnosticResultHelper.Create(DiagnosticIds.NoNestedStringFormats));
        }
Exemple #28
0
        public void CheckArrayRangeBraces(string declaration, string countLengthMethod)
        {
            const string template = @"
class Foo
{{
  public void test()
  {{
    {0};
    // comment
    if(data.{1} > 0)
      foreach (int i in data)
      {{
      }}
    // end comment
  }}
}}
";

            const string fixedTemplate = @"
class Foo
{{
  public void test()
  {{
    {0};
    // comment
    foreach (int i in data)
    {{
    }}
    // end comment
  }}
}}
";

            string errorCode = string.Format(template, declaration, countLengthMethod);

            VerifyCSharpDiagnostic(errorCode, DiagnosticResultHelper.Create(DiagnosticIds.PreventUncessaryRangeChecks));

            VerifyCSharpFix(errorCode, string.Format(fixedTemplate, declaration));
        }
        public void TestMethodsMustBeInTestClass(bool isError, string baseClass, string classQualifier, string testType)
        {
            const string code = @"using Microsoft.VisualStudio.TestTools.UnitTesting;

{0}
public {2} class Tests : {3}
{{
	{1}
	public void Foo() {{ }}
}}";

            VerifyCSharpDiagnostic(string.Format(code, "[TestClass]", testType, classQualifier, baseClass));

            DiagnosticResult[] expectedResult = Array.Empty <DiagnosticResult>();

            if (isError)
            {
                expectedResult = new[] { DiagnosticResultHelper.Create(DiagnosticIds.TestMethodsMustBeInTestClass) };
            }

            VerifyCSharpDiagnostic(string.Format(code, "", testType, classQualifier, baseClass), expectedResult);
        }
        public void ExtensionMethodErrors(bool isExtensionMethod, string call, bool isError, string fixedText)
        {
            const string Template = @"
using System;

public static class Foo
{{
  public static void Bar({0} object obj)
  {{
  }}
}}

public static class Program
{{
  public static void Main()
  {{
    {1};
  }}
}}
";

            string text = string.Format(Template, (isExtensionMethod ? "this" : ""), call);

            DiagnosticResult[] result = Array.Empty <DiagnosticResult>();
            if (isError)
            {
                result = new[] { DiagnosticResultHelper.Create(DiagnosticIds.ExtensionMethodsCalledLikeInstanceMethods) };
            }

            VerifyCSharpDiagnostic(text, result);

            if (!string.IsNullOrEmpty(fixedText))
            {
                string newText = string.Format(Template, (isExtensionMethod ? "this" : ""), fixedText);
                VerifyCSharpFix(text, newText);
            }
        }