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));
        }
        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));
        }
Пример #3
0
        public void DereferenceNullAsExpressionWithNestedExpression()
        {
            string testCode = @"
class Foo 
{{
  public void Scan(MethodDefinition method, MethodData data)
		{

Instruction i = method.Body.Instructions[0];
			
				switch (i.OpCode.Code)
				{
					case Code.Call:
					case Code.Calli:
					case Code.Callvirt:
						MethodReference mr = i.Operand as MethodReference;

						MethodDefinition md = mr.Resolve();

						Scan(md, _locks[md]);


						break;
					default:
						break;
				}
			
		}
}}
";
            var    expected = DiagnosticResultHelper.CreateArray(DiagnosticIds.DereferenceNull);

            VerifyCSharpDiagnostic(testCode, expected);
        }
Пример #4
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));
        }
Пример #5
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 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);
        }
        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));
        }
Пример #8
0
        public void CheckPasswordTest(string content0, string content1)
        {
            string testCode = string.Format(GetTemplate(), content0, content1);
            var    expected = DiagnosticResultHelper.CreateArray(DiagnosticIds.AvoidPasswordField);

            VerifyCSharpDiagnostic(testCode, expected);
        }
        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);
        }
Пример #10
0
        public void DereferenceNullAsExpressionFindingTest(string content1, string content2)
        {
            string testCode = string.Format(GetTemplate(), content1, content2);
            var    expected = DiagnosticResultHelper.CreateArray(DiagnosticIds.DereferenceNull);

            VerifyCSharpDiagnostic(testCode, expected);
        }
        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));
        }
Пример #13
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);
        }
Пример #15
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 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 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 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 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 TestMethodsMustReturnVoid(bool isAsync, string returnType, bool isError)
        {
            string code = $@"using System;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;

[TestClass]
public class Tests
{{
	[TestMethod]
	public {(isAsync ? "async" : string.Empty)} {returnType} Foo() {{ throw new Exception(); }}
}}";

            VerifyCSharpDiagnostic(code, isError ? DiagnosticResultHelper.CreateArray(DiagnosticIds.TestMethodsMustHaveValidReturnType) : Array.Empty <DiagnosticResult>());
        }
        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));
        }
Пример #24
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 NoLabeledStatements()
        {
            const string template = @"
using System;
class Foo
{
	public void Test()
	{
		test:
			Console.WriteLine();
	}
}
";

            VerifyCSharpDiagnostic(template, DiagnosticResultHelper.Create(DiagnosticIds.GotoNotAllowed));
        }
        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 TestMethodsMustNotHaveDataRows(string arg, bool isError)
        {
            const string code = @"using Microsoft.VisualStudio.TestTools.UnitTesting;

[TestClass]
public class Tests
{{
	{0}
	[TestMethod]
	public void Foo() {{ }}
}}";

            DiagnosticResult[] expected = Array.Empty <DiagnosticResult>();
            if (isError)
            {
                expected = DiagnosticResultHelper.CreateArray(DiagnosticIds.DataTestMethodsHaveDataRows);
            }

            VerifyCSharpDiagnostic(string.Format(code, arg), expected);
        }