From c414e26cf67a60c625a8f925cd87f303b162fb9d Mon Sep 17 00:00:00 2001 From: Dariusz Komosinski Date: Sun, 19 Jul 2020 00:15:08 +0200 Subject: [PATCH] Ensure that TryParse won't throw. --- src/Avalonia.Visuals/Media/Color.cs | 13 ++++++++---- .../Media/ColorTests.cs | 20 +++++++++++++++++++ 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/src/Avalonia.Visuals/Media/Color.cs b/src/Avalonia.Visuals/Media/Color.cs index 052ee5e1b7..40515423dd 100644 --- a/src/Avalonia.Visuals/Media/Color.cs +++ b/src/Avalonia.Visuals/Media/Color.cs @@ -89,6 +89,11 @@ namespace Avalonia.Media /// The . public static Color Parse(string s) { + if (s is null) + { + throw new ArgumentNullException(nameof(s)); + } + if (TryParse(s, out Color color)) { return color; @@ -120,14 +125,16 @@ namespace Avalonia.Media /// The status of the operation. public static bool TryParse(string s, out Color color) { + color = default; + if (s == null) { - throw new ArgumentNullException(nameof(s)); + return false; } if (s.Length == 0) { - throw new FormatException(); + return false; } if (s[0] == '#' && TryParseInternal(s.AsSpan(), out color)) @@ -144,8 +151,6 @@ namespace Avalonia.Media return true; } - color = default; - return false; } diff --git a/tests/Avalonia.Visuals.UnitTests/Media/ColorTests.cs b/tests/Avalonia.Visuals.UnitTests/Media/ColorTests.cs index f3f3c9a4ca..d68c2fd5fd 100644 --- a/tests/Avalonia.Visuals.UnitTests/Media/ColorTests.cs +++ b/tests/Avalonia.Visuals.UnitTests/Media/ColorTests.cs @@ -179,5 +179,25 @@ namespace Avalonia.Visuals.UnitTests.Media { Assert.False(Color.TryParse("#ff808g80", out _)); } + + [Fact] + public void Parse_Throws_ArgumentNullException_For_Null_Input() + { + Assert.Throws(() => Color.Parse((string)null)); + } + + [Fact] + public void Parse_Throws_FormatException_For_Invalid_Input() + { + Assert.Throws(() => Color.Parse(string.Empty)); + } + + [Theory] + [InlineData("")] + [InlineData(null)] + public void TryParse_Returns_False_For_Invalid_Input(string input) + { + Assert.False(Color.TryParse(input, out _)); + } } }