From 37ebbed60ef3a427534b4b67010d83e034e9fe57 Mon Sep 17 00:00:00 2001 From: Cristian <67206480+CristianAmbrosini@users.noreply.github.com> Date: Mon, 13 May 2024 17:01:35 +0200 Subject: [PATCH] S1066: Add reproducer for #9221 (#9264) --- .../Rules/IfCollapsibleTest.cs | 21 ++++++----- .../TestCases/IfCollapsible.cs | 35 +++++++++++++++++++ 2 files changed, 45 insertions(+), 11 deletions(-) diff --git a/analyzers/tests/SonarAnalyzer.Test/Rules/IfCollapsibleTest.cs b/analyzers/tests/SonarAnalyzer.Test/Rules/IfCollapsibleTest.cs index a7abd3e8c75..ac9324541ae 100644 --- a/analyzers/tests/SonarAnalyzer.Test/Rules/IfCollapsibleTest.cs +++ b/analyzers/tests/SonarAnalyzer.Test/Rules/IfCollapsibleTest.cs @@ -21,17 +21,16 @@ using CS = SonarAnalyzer.Rules.CSharp; using VB = SonarAnalyzer.Rules.VisualBasic; -namespace SonarAnalyzer.Test.Rules +namespace SonarAnalyzer.Test.Rules; + +[TestClass] +public class IfCollapsibleTest { - [TestClass] - public class IfCollapsibleTest - { - [TestMethod] - public void IfCollapsible_CS() => - new VerifierBuilder().AddPaths("IfCollapsible.cs").Verify(); + [TestMethod] + public void IfCollapsible_CS() => + new VerifierBuilder().AddPaths("IfCollapsible.cs").Verify(); - [TestMethod] - public void IfCollapsible_VB() => - new VerifierBuilder().AddPaths("IfCollapsible.vb").Verify(); - } + [TestMethod] + public void IfCollapsible_VB() => + new VerifierBuilder().AddPaths("IfCollapsible.vb").Verify(); } diff --git a/analyzers/tests/SonarAnalyzer.Test/TestCases/IfCollapsible.cs b/analyzers/tests/SonarAnalyzer.Test/TestCases/IfCollapsible.cs index 43e8ae47d4f..d7884fcece4 100644 --- a/analyzers/tests/SonarAnalyzer.Test/TestCases/IfCollapsible.cs +++ b/analyzers/tests/SonarAnalyzer.Test/TestCases/IfCollapsible.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.IO; using System.Linq; using System.Text; @@ -65,4 +66,38 @@ public void Test(bool cond1, bool cond2, bool cond3) } } } + + // Reproducer for https://github.com/SonarSource/sonar-dotnet/issues/9221 + public class Repro_9221 + { + public DateTime? ThisWorks() + { + dynamic anything = "2024-05-13"; + string notDynamic = "2024-05-13"; + + if (anything is string) // Secondary + if (DateTime.TryParseExact(anything, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime dt)) // Noncompliant FP + return dt; + + if (notDynamic != null) // Secondary + if (notDynamic == "something" && anything is string) // Noncompliant FP + return null; + + if (notDynamic != null) // Secondary + if (notDynamic == "something") // Noncompliant + return null; + + return null; + } + + public DateTime? ThisWontWork() + { + dynamic anything = "2024-04-29"; + + if (anything is string && DateTime.TryParseExact(anything, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime dt)) + return dt; // Error [CS0165] + + return null; + } + } }