Browse Source

Merge pull request #4323 from MarchingCube/fix-color-tryparse

Ensure that TryParse won't throw.
danwalmsley 5 years ago
parent
commit
7ad5f8aac7

+ 10 - 5
src/Avalonia.Visuals/Media/Color.cs

@@ -89,6 +89,11 @@ namespace Avalonia.Media
         /// <returns>The <see cref="Color"/>.</returns>
         /// <returns>The <see cref="Color"/>.</returns>
         public static Color Parse(string s)
         public static Color Parse(string s)
         {
         {
+            if (s is null)
+            {
+                throw new ArgumentNullException(nameof(s));
+            }
+
             if (TryParse(s, out Color color))
             if (TryParse(s, out Color color))
             {
             {
                 return color;
                 return color;
@@ -120,14 +125,16 @@ namespace Avalonia.Media
         /// <returns>The status of the operation.</returns>
         /// <returns>The status of the operation.</returns>
         public static bool TryParse(string s, out Color color)
         public static bool TryParse(string s, out Color color)
         {
         {
-            if (s == null)
+            color = default;
+
+            if (s is null)
             {
             {
-                throw new ArgumentNullException(nameof(s));
+                return false;
             }
             }
 
 
             if (s.Length == 0)
             if (s.Length == 0)
             {
             {
-                throw new FormatException();
+                return false;
             }
             }
 
 
             if (s[0] == '#' && TryParseInternal(s.AsSpan(), out color))
             if (s[0] == '#' && TryParseInternal(s.AsSpan(), out color))
@@ -144,8 +151,6 @@ namespace Avalonia.Media
                 return true;
                 return true;
             }
             }
 
 
-            color = default;
-
             return false;
             return false;
         }
         }
 
 

+ 20 - 0
tests/Avalonia.Visuals.UnitTests/Media/ColorTests.cs

@@ -179,5 +179,25 @@ namespace Avalonia.Visuals.UnitTests.Media
         {
         {
             Assert.False(Color.TryParse("#ff808g80", out _));
             Assert.False(Color.TryParse("#ff808g80", out _));
         }
         }
+
+        [Fact]
+        public void Parse_Throws_ArgumentNullException_For_Null_Input()
+        {
+            Assert.Throws<ArgumentNullException>(() => Color.Parse((string)null));
+        }
+
+        [Fact]
+        public void Parse_Throws_FormatException_For_Invalid_Input()
+        {
+            Assert.Throws<FormatException>(() => Color.Parse(string.Empty));
+        }
+
+        [Theory]
+        [InlineData("")]
+        [InlineData(null)]
+        public void TryParse_Returns_False_For_Invalid_Input(string input)
+        {
+            Assert.False(Color.TryParse(input, out _));
+        }
     }
     }
 }
 }